@remnic/core 9.63.8 → 9.63.10

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 (454) hide show
  1. package/dist/access-admin-ops-surface.d.ts +11 -11
  2. package/dist/access-admin-ops-surface.js +23 -23
  3. package/dist/access-authorization-probe.d.ts +11 -11
  4. package/dist/access-authorization-probe.js +24 -24
  5. package/dist/access-boundary.d.ts +11 -11
  6. package/dist/access-boundary.js +23 -23
  7. package/dist/access-cli.js +84 -82
  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 +11 -11
  11. package/dist/access-extraction-force-flush.js +23 -23
  12. package/dist/access-health-types.d.ts +1 -1
  13. package/dist/access-http-lcm-compaction.d.ts +11 -11
  14. package/dist/access-http-lifecycle-flush.d.ts +11 -11
  15. package/dist/access-http-offline-stream.d.ts +11 -11
  16. package/dist/access-http-query.d.ts +2 -2
  17. package/dist/access-http-query.js +25 -25
  18. package/dist/access-http.d.ts +12 -12
  19. package/dist/access-http.js +36 -36
  20. package/dist/access-identity-continuity-surface.d.ts +9 -9
  21. package/dist/access-identity-continuity-surface.js +23 -23
  22. package/dist/access-lcm-surface.d.ts +11 -11
  23. package/dist/access-lcm-surface.js +23 -23
  24. package/dist/access-mcp.d.ts +11 -11
  25. package/dist/access-mcp.js +30 -30
  26. package/dist/access-memory-search-fanout.d.ts +2 -2
  27. package/dist/{access-namespace-preflight-DB0zXFek.d.ts → access-namespace-preflight-CrF0FKaz.d.ts} +1 -1
  28. package/dist/access-namespace-preflight.d.ts +3 -3
  29. package/dist/access-namespace-preflight.js +23 -23
  30. package/dist/access-observe-write-surface.d.ts +11 -11
  31. package/dist/access-observe-write-surface.js +23 -23
  32. package/dist/access-offline-manifest.d.ts +9 -9
  33. package/dist/access-operations-batch.js +25 -25
  34. package/dist/access-operations.d.ts +14 -14
  35. package/dist/access-operations.js +29 -29
  36. package/dist/access-recall-concurrency.d.ts +11 -11
  37. package/dist/access-recall-concurrency.js +23 -23
  38. package/dist/access-recall-response.d.ts +11 -11
  39. package/dist/access-recall-response.js +23 -23
  40. package/dist/access-recall-surface.d.ts +11 -11
  41. package/dist/access-recall-surface.js +23 -23
  42. package/dist/access-schema.d.ts +88 -88
  43. package/dist/access-schema.js +3 -3
  44. package/dist/{access-service-BaPa_km6.d.ts → access-service-C0AE0jLs.d.ts} +71 -71
  45. package/dist/access-service-helpers.d.ts +11 -11
  46. package/dist/access-service.d.ts +11 -11
  47. package/dist/access-service.js +23 -23
  48. package/dist/access-surface-catalog.d.ts +11 -11
  49. package/dist/access-surface-catalog.js +25 -25
  50. package/dist/access-wearables-meetings-surface.d.ts +3 -3
  51. package/dist/action-confidence.d.ts +1 -1
  52. package/dist/active-memory-bridge.d.ts +1 -1
  53. package/dist/active-recall.d.ts +1 -1
  54. package/dist/ambient-provenance.d.ts +1 -1
  55. package/dist/artifact-search.d.ts +1 -1
  56. package/dist/{auto-sync-3SHMZVQS.js → auto-sync-5L7EUZ27.js} +4 -3
  57. package/dist/{auto-sync-3SHMZVQS.js.map → auto-sync-5L7EUZ27.js.map} +1 -1
  58. package/dist/behavior-learner.d.ts +1 -1
  59. package/dist/behavior-signals.d.ts +1 -1
  60. package/dist/bootstrap.d.ts +9 -9
  61. package/dist/briefing-window.d.ts +2 -2
  62. package/dist/briefing.d.ts +5 -3
  63. package/dist/briefing.js +11 -9
  64. package/dist/buffer-surprise-report.d.ts +1 -1
  65. package/dist/buffer-turn-helpers.d.ts +1 -1
  66. package/dist/buffer.d.ts +2 -2
  67. package/dist/bulk-import/index.d.ts +3 -3
  68. package/dist/calibration.d.ts +1 -1
  69. package/dist/capabilities.d.ts +1 -1
  70. package/dist/{capsule-crypto-YO5QJ6L3.js → capsule-crypto-GWVG7LGC.js} +2 -2
  71. package/dist/{catalog-CCzmf8IH.d.ts → catalog-C0KIwZqR.d.ts} +1 -1
  72. package/dist/causal-behavior.d.ts +1 -1
  73. package/dist/causal-consolidation.d.ts +1 -1
  74. package/dist/causal-consolidation.js +10 -10
  75. package/dist/causal-trajectory-graph.d.ts +1 -1
  76. package/dist/{chunk-4POAMKV6.js → chunk-27IOSH2W.js} +5 -2
  77. package/dist/chunk-27IOSH2W.js.map +1 -0
  78. package/dist/{chunk-OQIRBGUU.js → chunk-2Q4UAPLD.js} +4 -4
  79. package/dist/{chunk-3IMYRX3W.js → chunk-34E5NBQI.js} +2 -2
  80. package/dist/{chunk-BRHKW7GY.js → chunk-4IIDTPSK.js} +2 -2
  81. package/dist/{chunk-Q5XKKDFQ.js → chunk-5SZ6CLGJ.js} +2 -2
  82. package/dist/{chunk-VDX2J7OX.js → chunk-5W7CTZ2E.js} +4 -4
  83. package/dist/{chunk-EUYWQ7TS.js → chunk-652S5A5D.js} +2 -2
  84. package/dist/{chunk-ULZFZL7K.js → chunk-6IKXAAJI.js} +17 -28
  85. package/dist/chunk-6IKXAAJI.js.map +1 -0
  86. package/dist/{chunk-3TDAA7VA.js → chunk-6NMZXEJ7.js} +2 -2
  87. package/dist/{chunk-ZOAAY2OE.js → chunk-77E7LLMV.js} +7 -7
  88. package/dist/{chunk-MIUL6AUZ.js → chunk-7ML7STOD.js} +3 -3
  89. package/dist/{chunk-5SCFDQEJ.js → chunk-BPLPGOUJ.js} +2 -2
  90. package/dist/{chunk-RWMSMTQP.js → chunk-BS75WJBH.js} +2 -2
  91. package/dist/{chunk-XE2QCCT2.js → chunk-BTBAHTQ5.js} +2 -2
  92. package/dist/{chunk-42TIIO2M.js → chunk-BTUIHRRR.js} +2 -2
  93. package/dist/chunk-CIO7GCWE.js +29 -0
  94. package/dist/chunk-CIO7GCWE.js.map +1 -0
  95. package/dist/{chunk-SNEUAZ6B.js → chunk-CK3DZ6OE.js} +2 -2
  96. package/dist/{chunk-AJRJDXYR.js → chunk-E7MYSCSL.js} +2 -2
  97. package/dist/{chunk-3T6HIIKA.js → chunk-EHC3FIJ4.js} +2 -2
  98. package/dist/{chunk-EDZNW3HE.js → chunk-EPRBTGLM.js} +6 -6
  99. package/dist/{chunk-YTXNDEUS.js → chunk-FEP45MYY.js} +4 -3
  100. package/dist/{chunk-YTXNDEUS.js.map → chunk-FEP45MYY.js.map} +1 -1
  101. package/dist/{chunk-KFB4YNXM.js → chunk-G5F4MXXC.js} +2 -2
  102. package/dist/{chunk-VANZKHTN.js → chunk-G5OB4XZX.js} +4 -4
  103. package/dist/{chunk-N7V3P4V5.js → chunk-H5VDBZLZ.js} +2 -2
  104. package/dist/{chunk-645WOU5I.js → chunk-H7BZBSP6.js} +4 -4
  105. package/dist/{chunk-SZ4HFZKB.js → chunk-HMKPFW7R.js} +2 -2
  106. package/dist/{chunk-VFZQXYN5.js → chunk-HZXO2CJ6.js} +2 -2
  107. package/dist/{chunk-KXWE62IH.js → chunk-IOE75NA4.js} +2 -2
  108. package/dist/{chunk-PQHNZ63P.js → chunk-JJ45UTNT.js} +18 -5
  109. package/dist/chunk-JJ45UTNT.js.map +1 -0
  110. package/dist/{chunk-5TF5STAV.js → chunk-K477BTF4.js} +4 -4
  111. package/dist/{chunk-ML3U4KPR.js → chunk-K547KS3X.js} +4 -4
  112. package/dist/{chunk-UHGBNIOS.js → chunk-KVDUKH5E.js} +7 -2
  113. package/dist/chunk-KVDUKH5E.js.map +1 -0
  114. package/dist/{chunk-XTMYB2HY.js → chunk-LJQGQUNS.js} +2 -2
  115. package/dist/{chunk-WAS4HV46.js → chunk-LNH76ZJX.js} +87 -3
  116. package/dist/chunk-LNH76ZJX.js.map +1 -0
  117. package/dist/{chunk-VYMICVRA.js → chunk-LQNBQEMC.js} +2 -2
  118. package/dist/{chunk-J6QIAYNR.js → chunk-LVXBC6YB.js} +7 -2
  119. package/dist/{chunk-J6QIAYNR.js.map → chunk-LVXBC6YB.js.map} +1 -1
  120. package/dist/{chunk-IVKIODHO.js → chunk-MB6GLPRY.js} +4 -4
  121. package/dist/{chunk-BPQ7L27U.js → chunk-MIM7QT6H.js} +16 -16
  122. package/dist/chunk-MKYRCCSN.js +145 -0
  123. package/dist/chunk-MKYRCCSN.js.map +1 -0
  124. package/dist/{chunk-WBPD6SBZ.js → chunk-MNI7KB4Q.js} +54 -54
  125. package/dist/{chunk-6433HV72.js → chunk-MVIYRRVJ.js} +5 -5
  126. package/dist/{chunk-BXLOS5AJ.js → chunk-OWHERGF2.js} +2 -2
  127. package/dist/{chunk-QQYHYW2N.js → chunk-PQODT53H.js} +3 -3
  128. package/dist/{chunk-PHKU6BZ2.js → chunk-R7FQQQ23.js} +2 -2
  129. package/dist/{chunk-TOP3FSDW.js → chunk-RFFCBYBD.js} +11 -11
  130. package/dist/{chunk-O52TB5SL.js → chunk-SAWGVTCE.js} +2 -2
  131. package/dist/{chunk-LTYH2L6E.js → chunk-SILX74CP.js} +9 -9
  132. package/dist/{chunk-MYI3RKI6.js → chunk-SYU5JOBQ.js} +2 -2
  133. package/dist/{chunk-SY5JUJ2X.js → chunk-U5XC6DIS.js} +39 -39
  134. package/dist/{chunk-JXS5PDQ7.js → chunk-UOBPK2OS.js} +25 -7
  135. package/dist/chunk-UOBPK2OS.js.map +1 -0
  136. package/dist/{chunk-BOSIHHOH.js → chunk-UUYQWKHO.js} +2 -2
  137. package/dist/{chunk-DQEMWVMT.js → chunk-UVYI6VIX.js} +1 -1
  138. package/dist/{chunk-M4AHBM72.js → chunk-VCBG52MM.js} +4 -4
  139. package/dist/{chunk-62Y5AGCM.js → chunk-VENMDW4U.js} +10 -10
  140. package/dist/{chunk-6NAPOLRO.js → chunk-VY47VI2T.js} +6 -4
  141. package/dist/chunk-VY47VI2T.js.map +1 -0
  142. package/dist/{chunk-QTXNS3HB.js → chunk-WCWIV2JH.js} +2 -2
  143. package/dist/{chunk-6UKSOXAO.js → chunk-WQ6TRWAE.js} +3 -3
  144. package/dist/{chunk-CBY54QYW.js → chunk-X6HNXVXS.js} +4 -4
  145. package/dist/{chunk-DGUVXXAU.js → chunk-XFJUPJD7.js} +2 -2
  146. package/dist/{chunk-JPWSYHLB.js → chunk-YGSDWO3U.js} +2 -2
  147. package/dist/{chunk-GBVRVYF4.js → chunk-YINSSARY.js} +1 -1
  148. package/dist/{chunk-Q6OL23WM.js → chunk-Z4UPRZR6.js} +2 -2
  149. package/dist/{chunk-4F67JJPG.js → chunk-ZPN7W3OP.js} +2 -2
  150. package/dist/{cli-D0tV7eeU.d.ts → cli-xoJTOdMQ.d.ts} +5 -5
  151. package/dist/cli.d.ts +13 -13
  152. package/dist/cli.js +55 -54
  153. package/dist/coding/pre-action-gate.d.ts +1 -1
  154. package/dist/compounding/engine.d.ts +2 -2
  155. package/dist/compounding/engine.js +9 -9
  156. package/dist/compounding/preference-consolidator.d.ts +1 -1
  157. package/dist/compression-optimizer.d.ts +1 -1
  158. package/dist/config.d.ts +1 -1
  159. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  160. package/dist/connectors/codex-materialize-runner.js +9 -9
  161. package/dist/connectors/codex-materialize.d.ts +1 -1
  162. package/dist/connectors/index.d.ts +1 -1
  163. package/dist/connectors/index.js +9 -9
  164. package/dist/consolidation-provenance-check.d.ts +2 -2
  165. package/dist/consolidation-undo.d.ts +2 -2
  166. package/dist/contradiction/index.d.ts +2 -2
  167. package/dist/contradiction/index.js +4 -4
  168. package/dist/converge-config.d.ts +1 -1
  169. package/dist/convergence-refresh.d.ts +2 -2
  170. package/dist/convergence-refresh.js +11 -11
  171. package/dist/conversation-index/backend.d.ts +1 -1
  172. package/dist/conversation-index/chunker.d.ts +1 -1
  173. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  174. package/dist/conversation-index/indexer.d.ts +1 -1
  175. package/dist/conversation-index/search.d.ts +1 -1
  176. package/dist/corpus-watermark.d.ts +1 -1
  177. package/dist/corpus-watermark.js +11 -11
  178. package/dist/day-summary.d.ts +1 -1
  179. package/dist/day-summary.js +1 -1
  180. package/dist/delinearize.d.ts +1 -1
  181. package/dist/dependency-propagation-config.d.ts +1 -1
  182. package/dist/{dependency-propagation-delivery-DiY5T63p.d.ts → dependency-propagation-delivery-Cph4PnBe.d.ts} +1 -1
  183. package/dist/direct-answer-wiring.d.ts +1 -1
  184. package/dist/direct-answer-wiring.js +2 -1
  185. package/dist/direct-answer.d.ts +1 -1
  186. package/dist/embedding-fallback.d.ts +1 -1
  187. package/dist/enrichment/index.d.ts +1 -1
  188. package/dist/entity-origin-fields.d.ts +1 -1
  189. package/dist/entity-retrieval-i18n.d.ts +34 -0
  190. package/dist/entity-retrieval-i18n.js +13 -0
  191. package/dist/entity-retrieval-i18n.js.map +1 -0
  192. package/dist/entity-retrieval.d.ts +2 -2
  193. package/dist/entity-retrieval.js +10 -9
  194. package/dist/entity-schema.d.ts +1 -1
  195. package/dist/episodic-context.d.ts +1 -1
  196. package/dist/event-order-recall.js +2 -2
  197. package/dist/explicit-capture.d.ts +9 -9
  198. package/dist/external-wiki-access.d.ts +11 -11
  199. package/dist/external-wiki-access.js +24 -24
  200. package/dist/external-wiki-collection-registration.d.ts +1 -1
  201. package/dist/external-wiki-collection.d.ts +1 -1
  202. package/dist/external-wiki-mcp-tools.d.ts +11 -11
  203. package/dist/extraction-error-classification.d.ts +1 -1
  204. package/dist/extraction-faithfulness.d.ts +1 -1
  205. package/dist/extraction-judge-telemetry.d.ts +1 -1
  206. package/dist/extraction-judge-training.d.ts +1 -1
  207. package/dist/extraction-judge.d.ts +1 -1
  208. package/dist/extraction-liveness.d.ts +1 -1
  209. package/dist/extraction-normalization.d.ts +1 -1
  210. package/dist/extraction-prompt.d.ts +1 -1
  211. package/dist/extraction-source-grounding-helpers.d.ts +10 -1
  212. package/dist/extraction-source-grounding-helpers.js +3 -1
  213. package/dist/extraction-source-grounding-rules.d.ts +1 -1
  214. package/dist/extraction-source-grounding-rules.js +2 -2
  215. package/dist/extraction-source-grounding.d.ts +1 -1
  216. package/dist/extraction-source-grounding.js +3 -3
  217. package/dist/extraction.d.ts +1 -1
  218. package/dist/extraction.js +18 -18
  219. package/dist/fallback-llm.d.ts +1 -1
  220. package/dist/graph-dashboard-diff.d.ts +1 -1
  221. package/dist/graph-dashboard-key.d.ts +1 -1
  222. package/dist/graph-dashboard-parser.d.ts +1 -1
  223. package/dist/graph-edge-reinforcement.d.ts +1 -1
  224. package/dist/graph-path-reconstruction.d.ts +1 -1
  225. package/dist/graph-path-scoring.d.ts +1 -1
  226. package/dist/graph-snapshot.d.ts +1 -1
  227. package/dist/graph.d.ts +1 -1
  228. package/dist/harmonic-retrieval.js +1 -1
  229. package/dist/importance.d.ts +1 -1
  230. package/dist/importance.js +2 -1
  231. package/dist/importers/index.d.ts +1 -1
  232. package/dist/in-flight-reads.d.ts +1 -1
  233. package/dist/index.d.ts +697 -697
  234. package/dist/index.js +98 -96
  235. package/dist/intent.d.ts +1 -1
  236. package/dist/lcm/engine.d.ts +1 -1
  237. package/dist/lcm/engine.js +2 -2
  238. package/dist/lcm/index.d.ts +1 -1
  239. package/dist/lcm/index.js +4 -4
  240. package/dist/lcm/tools.d.ts +1 -1
  241. package/dist/lifecycle.d.ts +1 -1
  242. package/dist/live-connectors-runner.d.ts +1 -1
  243. package/dist/local-llm.d.ts +1 -1
  244. package/dist/local-llm.js +2 -2
  245. package/dist/local-model-endpoint.d.ts +1 -1
  246. package/dist/maintenance/memory-governance.d.ts +1 -1
  247. package/dist/maintenance/memory-governance.js +9 -9
  248. package/dist/maintenance/rebuild-memory-lifecycle-ledger.d.ts +2 -2
  249. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +9 -9
  250. package/dist/maintenance/rebuild-memory-projection.d.ts +2 -2
  251. package/dist/maintenance/rebuild-memory-projection.js +10 -10
  252. package/dist/{maintenance-CaqA4z7V.d.ts → maintenance-BNq31xpo.d.ts} +3 -3
  253. package/dist/mcp-memory-inspector-app.d.ts +11 -11
  254. package/dist/memory-action-policy.d.ts +1 -1
  255. package/dist/memory-cache.d.ts +1 -1
  256. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  257. package/dist/memory-projection-store.d.ts +1 -1
  258. package/dist/memory-provenance.d.ts +1 -1
  259. package/dist/memory-snapshot.d.ts +1 -1
  260. package/dist/memory-worth-outcomes.d.ts +2 -2
  261. package/dist/models-json.d.ts +1 -1
  262. package/dist/namespaces/migrate.d.ts +3 -3
  263. package/dist/namespaces/migrate.js +10 -10
  264. package/dist/namespaces/principal.d.ts +1 -1
  265. package/dist/namespaces/search.d.ts +1 -1
  266. package/dist/namespaces/search.js +7 -7
  267. package/dist/namespaces/storage.d.ts +3 -3
  268. package/dist/namespaces/storage.js +9 -9
  269. package/dist/native-knowledge.d.ts +1 -1
  270. package/dist/offline-sync-impression-drain.d.ts +1 -1
  271. package/dist/operator-doctor-corpus.d.ts +1 -1
  272. package/dist/operator-doctor-corpus.js +12 -12
  273. package/dist/operator-doctor-replica.d.ts +1 -1
  274. package/dist/operator-toolkit.d.ts +3 -3
  275. package/dist/operator-toolkit.js +17 -17
  276. package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -2
  277. package/dist/orchestration/maintenance.d.ts +4 -4
  278. package/dist/orchestration/maintenance.js +15 -15
  279. package/dist/{orchestrator-Bay_AofR.d.ts → orchestrator-CBuUOP2J.d.ts} +8 -8
  280. package/dist/orchestrator.d.ts +9 -9
  281. package/dist/orchestrator.js +84 -82
  282. package/dist/patterns-cli.d.ts +1 -1
  283. package/dist/{pipeline-X606GdRJ.d.ts → pipeline-CW_Q4WvX.d.ts} +1 -1
  284. package/dist/policy-runtime.d.ts +1 -1
  285. package/dist/proactive-contention.d.ts +1 -1
  286. package/dist/provenance.d.ts +1 -1
  287. package/dist/{public-http-BtjiyKah.d.ts → public-http-DR3sHfwk.d.ts} +1 -1
  288. package/dist/qmd-preflight.d.ts +2 -2
  289. package/dist/{qmd-DCKeR-GX.d.ts → qmd-q-cAzYuC.d.ts} +1 -1
  290. package/dist/qmd-recall-cache.d.ts +1 -1
  291. package/dist/qmd.d.ts +2 -2
  292. package/dist/recall-concurrency-config.d.ts +1 -1
  293. package/dist/recall-disclosure-escalation.d.ts +1 -1
  294. package/dist/recall-explain-renderer.d.ts +1 -1
  295. package/dist/recall-memory-map.d.ts +1 -1
  296. package/dist/recall-planner-llm.d.ts +1 -1
  297. package/dist/recall-state.d.ts +1 -1
  298. package/dist/recall-tag-filter.d.ts +1 -1
  299. package/dist/recall-timings.d.ts +1 -1
  300. package/dist/recall-xray-cli.d.ts +1 -1
  301. package/dist/recall-xray-renderer.d.ts +1 -1
  302. package/dist/recall-xray.d.ts +1 -1
  303. package/dist/reconcile/cursor.d.ts +1 -1
  304. package/dist/reconcile/manifest.d.ts +1 -1
  305. package/dist/reconcile/plan.d.ts +1 -1
  306. package/dist/replay/normalizers/chatgpt.d.ts +1 -1
  307. package/dist/replay/normalizers/claude.d.ts +1 -1
  308. package/dist/replay/normalizers/openclaw.d.ts +1 -1
  309. package/dist/replay/normalizers/shared.d.ts +1 -1
  310. package/dist/replay/runner.d.ts +1 -1
  311. package/dist/replay/types.d.ts +1 -1
  312. package/dist/replica-divergence.d.ts +1 -1
  313. package/dist/replica-peers-config.d.ts +1 -1
  314. package/dist/resolve-auth-token.d.ts +1 -1
  315. package/dist/retrieval-agents.d.ts +2 -2
  316. package/dist/retrieval-tiers.d.ts +1 -1
  317. package/dist/routing/engine.d.ts +1 -1
  318. package/dist/routing/store.d.ts +1 -1
  319. package/dist/salvage-envelope.d.ts +1 -1
  320. package/dist/schemas.d.ts +108 -108
  321. package/dist/{scope-profiles-_Y_RHCeE.d.ts → scope-profiles-CIr4mXgp.d.ts} +1 -1
  322. package/dist/search/embed-helper.d.ts +1 -1
  323. package/dist/search/factory.d.ts +1 -1
  324. package/dist/search/factory.js +6 -6
  325. package/dist/search/index.d.ts +1 -1
  326. package/dist/search/index.js +11 -11
  327. package/dist/search/lancedb-backend.d.ts +1 -1
  328. package/dist/search/lancedb-backend.js +2 -2
  329. package/dist/search/meilisearch-backend.d.ts +1 -1
  330. package/dist/search/meilisearch-backend.js +2 -2
  331. package/dist/search/noop-backend.d.ts +1 -1
  332. package/dist/search/orama-backend.d.ts +1 -1
  333. package/dist/search/orama-backend.js +2 -2
  334. package/dist/search/port.d.ts +1 -1
  335. package/dist/search/remote-backend.d.ts +1 -1
  336. package/dist/{semantic-consolidation-DT2VSrU0.d.ts → semantic-consolidation-BZ6J46j-.d.ts} +1 -1
  337. package/dist/semantic-consolidation.d.ts +2 -2
  338. package/dist/semantic-consolidation.js +10 -10
  339. package/dist/semantic-rule-promotion.js +9 -9
  340. package/dist/semantic-rule-verifier.d.ts +1 -1
  341. package/dist/semantic-rule-verifier.js +9 -9
  342. package/dist/{service-BMo-gwDE.d.ts → service-CCl4iyyY.d.ts} +2 -2
  343. package/dist/session-observer-bands.d.ts +1 -1
  344. package/dist/session-observer-state.d.ts +1 -1
  345. package/dist/shared-context/manager.d.ts +9 -9
  346. package/dist/signal.d.ts +1 -1
  347. package/dist/source-agent-qualifier.d.ts +1 -1
  348. package/dist/source-agent-qualifier.js +13 -13
  349. package/dist/{storage-CGzJGUUu.d.ts → storage-BPXmJKIt.d.ts} +1 -1
  350. package/dist/storage.d.ts +2 -2
  351. package/dist/storage.js +8 -8
  352. package/dist/summarizer.d.ts +1 -1
  353. package/dist/summarizer.js +3 -3
  354. package/dist/summary-snapshot.d.ts +1 -1
  355. package/dist/support-passport/index.d.ts +14 -14
  356. package/dist/support-passport/index.js +26 -26
  357. package/dist/temporal-supersession.d.ts +2 -2
  358. package/dist/temporal-timeline-recall.d.ts +1 -1
  359. package/dist/temporal-validity.d.ts +1 -1
  360. package/dist/threading.d.ts +1 -1
  361. package/dist/tier-migration.d.ts +2 -2
  362. package/dist/tier-routing.d.ts +1 -1
  363. package/dist/topics.d.ts +1 -1
  364. package/dist/topics.js +2 -1
  365. package/dist/transcript.d.ts +1 -1
  366. package/dist/transfer/backup.js +2 -2
  367. package/dist/transfer/capsule-export.js +2 -2
  368. package/dist/transfer/capsule-import.js +2 -2
  369. package/dist/transfer/types.d.ts +66 -66
  370. package/dist/trust-score-stage.d.ts +1 -1
  371. package/dist/trust-score.d.ts +1 -1
  372. package/dist/{types-CBEAYU76.d.ts → types-CltSWcND.d.ts} +1 -1
  373. package/dist/types.d.ts +1 -1
  374. package/dist/utility-runtime.d.ts +1 -1
  375. package/dist/verified-recall.js +9 -9
  376. package/dist/write-envelope.d.ts +1 -1
  377. package/package.json +2 -2
  378. package/src/briefing.test.ts +50 -0
  379. package/src/briefing.ts +3 -2
  380. package/src/chat/chat-engine.test.ts +15 -0
  381. package/src/chat/chat-engine.ts +13 -2
  382. package/src/day-summary.test.ts +63 -0
  383. package/src/day-summary.ts +13 -1
  384. package/src/entity-retrieval-i18n.test.ts +115 -0
  385. package/src/entity-retrieval-i18n.ts +161 -0
  386. package/src/entity-retrieval.ts +34 -34
  387. package/src/extraction-source-grounding-helpers.ts +112 -2
  388. package/src/extraction-source-grounding-rules.ts +3 -1
  389. package/src/extraction-source-grounding.test.ts +52 -0
  390. package/src/importance.ts +32 -22
  391. package/src/taxonomy/resolver.ts +7 -7
  392. package/src/topics.ts +5 -2
  393. package/src/utils/script-aware-text.ts +52 -0
  394. package/src/write-classifiers-cjk.test.ts +115 -0
  395. package/dist/chunk-4POAMKV6.js.map +0 -1
  396. package/dist/chunk-6NAPOLRO.js.map +0 -1
  397. package/dist/chunk-JXS5PDQ7.js.map +0 -1
  398. package/dist/chunk-PQHNZ63P.js.map +0 -1
  399. package/dist/chunk-UHGBNIOS.js.map +0 -1
  400. package/dist/chunk-ULZFZL7K.js.map +0 -1
  401. package/dist/chunk-WAS4HV46.js.map +0 -1
  402. /package/dist/{capsule-crypto-YO5QJ6L3.js.map → capsule-crypto-GWVG7LGC.js.map} +0 -0
  403. /package/dist/{chunk-OQIRBGUU.js.map → chunk-2Q4UAPLD.js.map} +0 -0
  404. /package/dist/{chunk-3IMYRX3W.js.map → chunk-34E5NBQI.js.map} +0 -0
  405. /package/dist/{chunk-BRHKW7GY.js.map → chunk-4IIDTPSK.js.map} +0 -0
  406. /package/dist/{chunk-Q5XKKDFQ.js.map → chunk-5SZ6CLGJ.js.map} +0 -0
  407. /package/dist/{chunk-VDX2J7OX.js.map → chunk-5W7CTZ2E.js.map} +0 -0
  408. /package/dist/{chunk-EUYWQ7TS.js.map → chunk-652S5A5D.js.map} +0 -0
  409. /package/dist/{chunk-3TDAA7VA.js.map → chunk-6NMZXEJ7.js.map} +0 -0
  410. /package/dist/{chunk-ZOAAY2OE.js.map → chunk-77E7LLMV.js.map} +0 -0
  411. /package/dist/{chunk-MIUL6AUZ.js.map → chunk-7ML7STOD.js.map} +0 -0
  412. /package/dist/{chunk-5SCFDQEJ.js.map → chunk-BPLPGOUJ.js.map} +0 -0
  413. /package/dist/{chunk-RWMSMTQP.js.map → chunk-BS75WJBH.js.map} +0 -0
  414. /package/dist/{chunk-XE2QCCT2.js.map → chunk-BTBAHTQ5.js.map} +0 -0
  415. /package/dist/{chunk-42TIIO2M.js.map → chunk-BTUIHRRR.js.map} +0 -0
  416. /package/dist/{chunk-SNEUAZ6B.js.map → chunk-CK3DZ6OE.js.map} +0 -0
  417. /package/dist/{chunk-AJRJDXYR.js.map → chunk-E7MYSCSL.js.map} +0 -0
  418. /package/dist/{chunk-3T6HIIKA.js.map → chunk-EHC3FIJ4.js.map} +0 -0
  419. /package/dist/{chunk-EDZNW3HE.js.map → chunk-EPRBTGLM.js.map} +0 -0
  420. /package/dist/{chunk-KFB4YNXM.js.map → chunk-G5F4MXXC.js.map} +0 -0
  421. /package/dist/{chunk-VANZKHTN.js.map → chunk-G5OB4XZX.js.map} +0 -0
  422. /package/dist/{chunk-N7V3P4V5.js.map → chunk-H5VDBZLZ.js.map} +0 -0
  423. /package/dist/{chunk-645WOU5I.js.map → chunk-H7BZBSP6.js.map} +0 -0
  424. /package/dist/{chunk-SZ4HFZKB.js.map → chunk-HMKPFW7R.js.map} +0 -0
  425. /package/dist/{chunk-VFZQXYN5.js.map → chunk-HZXO2CJ6.js.map} +0 -0
  426. /package/dist/{chunk-KXWE62IH.js.map → chunk-IOE75NA4.js.map} +0 -0
  427. /package/dist/{chunk-5TF5STAV.js.map → chunk-K477BTF4.js.map} +0 -0
  428. /package/dist/{chunk-ML3U4KPR.js.map → chunk-K547KS3X.js.map} +0 -0
  429. /package/dist/{chunk-XTMYB2HY.js.map → chunk-LJQGQUNS.js.map} +0 -0
  430. /package/dist/{chunk-VYMICVRA.js.map → chunk-LQNBQEMC.js.map} +0 -0
  431. /package/dist/{chunk-IVKIODHO.js.map → chunk-MB6GLPRY.js.map} +0 -0
  432. /package/dist/{chunk-BPQ7L27U.js.map → chunk-MIM7QT6H.js.map} +0 -0
  433. /package/dist/{chunk-WBPD6SBZ.js.map → chunk-MNI7KB4Q.js.map} +0 -0
  434. /package/dist/{chunk-6433HV72.js.map → chunk-MVIYRRVJ.js.map} +0 -0
  435. /package/dist/{chunk-BXLOS5AJ.js.map → chunk-OWHERGF2.js.map} +0 -0
  436. /package/dist/{chunk-QQYHYW2N.js.map → chunk-PQODT53H.js.map} +0 -0
  437. /package/dist/{chunk-PHKU6BZ2.js.map → chunk-R7FQQQ23.js.map} +0 -0
  438. /package/dist/{chunk-TOP3FSDW.js.map → chunk-RFFCBYBD.js.map} +0 -0
  439. /package/dist/{chunk-O52TB5SL.js.map → chunk-SAWGVTCE.js.map} +0 -0
  440. /package/dist/{chunk-LTYH2L6E.js.map → chunk-SILX74CP.js.map} +0 -0
  441. /package/dist/{chunk-MYI3RKI6.js.map → chunk-SYU5JOBQ.js.map} +0 -0
  442. /package/dist/{chunk-SY5JUJ2X.js.map → chunk-U5XC6DIS.js.map} +0 -0
  443. /package/dist/{chunk-BOSIHHOH.js.map → chunk-UUYQWKHO.js.map} +0 -0
  444. /package/dist/{chunk-DQEMWVMT.js.map → chunk-UVYI6VIX.js.map} +0 -0
  445. /package/dist/{chunk-M4AHBM72.js.map → chunk-VCBG52MM.js.map} +0 -0
  446. /package/dist/{chunk-62Y5AGCM.js.map → chunk-VENMDW4U.js.map} +0 -0
  447. /package/dist/{chunk-QTXNS3HB.js.map → chunk-WCWIV2JH.js.map} +0 -0
  448. /package/dist/{chunk-6UKSOXAO.js.map → chunk-WQ6TRWAE.js.map} +0 -0
  449. /package/dist/{chunk-CBY54QYW.js.map → chunk-X6HNXVXS.js.map} +0 -0
  450. /package/dist/{chunk-DGUVXXAU.js.map → chunk-XFJUPJD7.js.map} +0 -0
  451. /package/dist/{chunk-JPWSYHLB.js.map → chunk-YGSDWO3U.js.map} +0 -0
  452. /package/dist/{chunk-GBVRVYF4.js.map → chunk-YINSSARY.js.map} +0 -0
  453. /package/dist/{chunk-Q6OL23WM.js.map → chunk-Z4UPRZR6.js.map} +0 -0
  454. /package/dist/{chunk-4F67JJPG.js.map → chunk-ZPN7W3OP.js.map} +0 -0
@@ -4,30 +4,30 @@ import {
4
4
  } from "./chunk-2PSX5BJU.js";
5
5
  import {
6
6
  buildExtensionsBlockForConsolidation
7
- } from "./chunk-42TIIO2M.js";
7
+ } from "./chunk-BTUIHRRR.js";
8
8
  import "./chunk-5JMAGU26.js";
9
9
  import "./chunk-B7RWBZXW.js";
10
10
  import {
11
11
  runPostConsolidationMaterialize
12
- } from "./chunk-BOSIHHOH.js";
12
+ } from "./chunk-UUYQWKHO.js";
13
13
  import "./chunk-RDFF2NAU.js";
14
14
  import {
15
15
  resolveCausalTrajectoryStoreDir
16
16
  } from "./chunk-GPFZFCRN.js";
17
- import "./chunk-Q5XKKDFQ.js";
17
+ import "./chunk-5SZ6CLGJ.js";
18
18
  import "./chunk-UHVXE24Y.js";
19
19
  import "./chunk-46WM6JX2.js";
20
20
  import "./chunk-SXIMQLGV.js";
21
- import "./chunk-AJRJDXYR.js";
22
- import "./chunk-62Y5AGCM.js";
23
- import "./chunk-OQIRBGUU.js";
24
- import "./chunk-VANZKHTN.js";
25
- import "./chunk-CYEPCZN5.js";
26
- import "./chunk-ML3U4KPR.js";
21
+ import "./chunk-E7MYSCSL.js";
22
+ import "./chunk-VENMDW4U.js";
27
23
  import "./chunk-VYISFWVX.js";
28
- import "./chunk-W7IGLX4G.js";
29
24
  import "./chunk-6KTXE6A3.js";
25
+ import "./chunk-2Q4UAPLD.js";
26
+ import "./chunk-G5OB4XZX.js";
27
+ import "./chunk-CYEPCZN5.js";
28
+ import "./chunk-K547KS3X.js";
30
29
  import "./chunk-GUMZC2BO.js";
30
+ import "./chunk-W7IGLX4G.js";
31
31
  import "./chunk-227UFSEQ.js";
32
32
  import "./chunk-ET356KSB.js";
33
33
  import "./chunk-72A4L5JJ.js";
@@ -1,7 +1,7 @@
1
1
  import { a as GraphEdge } from './graph-444E-DrF.js';
2
2
  import { CausalTrajectoryRecord } from './causal-trajectory.js';
3
3
  import './capabilities.js';
4
- import './types-CBEAYU76.js';
4
+ import './types-CltSWcND.js';
5
5
  import './message-parts/index.js';
6
6
  import './bounded-jsonl-state.js';
7
7
  import './operator-doctor-types.js';
@@ -17,11 +17,12 @@ import {
17
17
  normalizedGroundingAlignmentTokenSequence,
18
18
  normalizedGroundingTokenSequence,
19
19
  sourceSentences,
20
+ spacelessScriptGroundedTokenScore,
20
21
  splitGroundingClauses,
21
22
  stemToken,
22
23
  tokenSequence,
23
24
  tokenize
24
- } from "./chunk-WAS4HV46.js";
25
+ } from "./chunk-LNH76ZJX.js";
25
26
  import {
26
27
  anchorTemporalExpressions
27
28
  } from "./chunk-VEWZZM3H.js";
@@ -153,6 +154,8 @@ function omitsSourceDisjunction(candidate, source) {
153
154
  });
154
155
  }
155
156
  function groundedTokenScore(candidate, source, requireAlignedArguments = true, requireAllCandidateTokensGrounded = true) {
157
+ const scriptAwareScore = spacelessScriptGroundedTokenScore(candidate, source);
158
+ if (scriptAwareScore !== null) return scriptAwareScore;
156
159
  const candidateTokens = tokenize(candidate);
157
160
  if (candidateTokens.size === 0) return 0;
158
161
  const sourceTokens = tokenize(source);
@@ -798,4 +801,4 @@ export {
798
801
  applyExtractionSourceGrounding,
799
802
  filterExtractionResultBySource
800
803
  };
801
- //# sourceMappingURL=chunk-4POAMKV6.js.map
804
+ //# sourceMappingURL=chunk-27IOSH2W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/extraction-source-grounding-rules.ts"],"sourcesContent":["import type { ExtractionResult } from \"./types.js\";\nimport { anchorTemporalExpressions } from \"./delinearize.js\";\nimport {\n GROUNDING_AUXILIARY_TOKENS,\n GROUNDING_COPULAR_FORMS,\n GROUNDING_ENTITY_TYPE_PREFIXES,\n GROUNDING_MIN_COVERAGE,\n GROUNDING_MIN_SHARED_TOKENS,\n GROUNDING_STOPWORDS,\n areGroundingTokensCompatible,\n containsContiguousGroundingTokens,\n containsExactTokenSequence,\n groundingLexemes,\n groundingTokenSequence,\n hasContradictoryPolarity,\n hasExplicitRoleSubjectToken,\n isInterrogativeSourceSentence,\n normalizeForExactMatch,\n normalizedGroundingAlignmentTokenSequence,\n normalizedGroundingTokenSequence,\n sourceSentences,\n spacelessScriptGroundedTokenScore,\n splitGroundingClauses,\n stemToken,\n tokenize,\n tokenSequence,\n} from \"./extraction-source-grounding-helpers.js\";\n\nexport interface ExtractionSourceGroundingOptions {\n sourceGrounding: boolean;\n anchorTemporalExpressions: boolean;\n}\n\nexport function applyExtractionSourceGrounding(\n result: ExtractionResult,\n sourceText: string,\n assertionSourceText: string = sourceText,\n roleAssertionSources: ExtractionGroundingRoleSources | undefined,\n messageTimestamp: Date | undefined,\n options: ExtractionSourceGroundingOptions,\n): ExtractionResult {\n if (!options.sourceGrounding) return result;\n const anchorSource = (source: string): string =>\n options.anchorTemporalExpressions\n ? anchorTemporalExpressions(source, messageTimestamp ?? new Date())\n : source;\n const anchoredRoleSources = roleAssertionSources === undefined\n ? undefined\n : {\n profile: roleAssertionSources.profile === undefined\n ? undefined\n : anchorSource(roleAssertionSources.profile),\n identity: roleAssertionSources.identity === undefined\n ? undefined\n : anchorSource(roleAssertionSources.identity),\n };\n return filterExtractionResultBySource(\n result,\n anchorSource(sourceText),\n anchorSource(assertionSourceText),\n anchoredRoleSources,\n options.anchorTemporalExpressions ? anchorSource : undefined,\n );\n}\n\nexport interface ExtractionGroundingRoleSources {\n profile?: string;\n identity?: string;\n}\n\n\n\ninterface GroundingCopularClaim {\n subject: string;\n predicate: string;\n}\n\nfunction groundingCopularClaim(text: string): GroundingCopularClaim | undefined {\n const lexemes = groundingLexemes(text);\n const copulaIndex = lexemes.findIndex(({ token }) => GROUNDING_COPULAR_FORMS.has(token));\n if (copulaIndex <= 0) return undefined;\n\n let subjectIndex = copulaIndex - 1;\n while (\n subjectIndex >= 0\n && GROUNDING_AUXILIARY_TOKENS.has(lexemes[subjectIndex]!.token)\n ) {\n subjectIndex -= 1;\n }\n const subjectLexeme = lexemes[subjectIndex];\n const predicateLexeme = lexemes\n .slice(copulaIndex + 1)\n .find(({ token }) => GROUNDING_STOPWORDS[token] !== true);\n if (subjectLexeme === undefined || predicateLexeme === undefined) return undefined;\n\n return {\n subject: stemToken(subjectLexeme.token, subjectLexeme.preserveTerminalS, true),\n predicate: stemToken(predicateLexeme.token, predicateLexeme.preserveTerminalS, true),\n };\n}\n\nfunction hasCopularPredicateEvidence(candidate: string, source: string): boolean {\n const candidateClaim = groundingCopularClaim(candidate);\n if (candidateClaim === undefined) return true;\n const sourceClaim = groundingCopularClaim(source);\n return sourceClaim !== undefined\n && areGroundingTokensCompatible(candidateClaim.subject, sourceClaim.subject)\n && areGroundingTokensCompatible(candidateClaim.predicate, sourceClaim.predicate);\n}\nconst GROUNDING_ALIGNMENT_MODIFIERS = new Set([\n \"actively\",\n \"again\",\n \"already\",\n \"currently\",\n \"eventually\",\n \"finally\",\n \"generally\",\n \"mainly\",\n \"newly\",\n \"now\",\n \"often\",\n \"previously\",\n \"primarily\",\n \"quickly\",\n \"recently\",\n \"repeatedly\",\n \"simply\",\n \"slowly\",\n \"sometimes\",\n \"still\",\n \"successfully\",\n \"typically\",\n \"usually\",\n]);\n\nfunction isGroundingAlignmentModifier(token: string): boolean {\n return GROUNDING_ALIGNMENT_MODIFIERS.has(token);\n}\n\nfunction groundingSubjectTokenSequence(text: string): string[] {\n const lexemes = groundingLexemes(text)\n .filter(({ token }) => GROUNDING_STOPWORDS[token] !== true);\n const predicateIndex = lexemes.findIndex(({ isPredicate }) => isPredicate);\n if (predicateIndex < 1) return [];\n return lexemes\n .slice(0, predicateIndex)\n .filter(({ token }) => !isGroundingAlignmentModifier(token) && !token.endsWith(\"ly\"))\n .map(({ token, preserveTerminalS }) => stemToken(token, preserveTerminalS, true));\n}\n\n\nfunction hasAlignedSubjectPredicateOverlap(candidate: string, source: string): boolean {\n const candidateTokens = normalizedGroundingAlignmentTokenSequence(candidate);\n const sourceTokens = normalizedGroundingAlignmentTokenSequence(source);\n const candidateSubjectTokens = groundingSubjectTokenSequence(candidate);\n const sourceSubjectTokens = groundingSubjectTokenSequence(source);\n const hasCorrectionReordering = /\\b(?:rather\\s+than|instead\\s+of)\\b/iu.test(candidate)\n && /\\b(?:not|rather\\s+than|instead\\s+of)\\b/iu.test(source);\n if (\n candidateSubjectTokens.length > 0\n && sourceSubjectTokens.length > 0\n && !hasCorrectionReordering\n && (\n candidateSubjectTokens.length !== sourceSubjectTokens.length\n || candidateSubjectTokens.some(\n (token, index) => !areGroundingTokensCompatible(token, sourceSubjectTokens[index]!),\n )\n )\n ) {\n return false;\n }\n if (candidateTokens.length < 3 || sourceTokens.length < 3) {\n return hasCopularPredicateEvidence(candidate, source);\n }\n\n const candidateSubject = candidateTokens[0];\n if (candidateSubject === undefined) return false;\n for (let sourceSubjectIndex = 0; sourceSubjectIndex < sourceTokens.length; sourceSubjectIndex += 1) {\n if (!areGroundingTokensCompatible(candidateSubject, sourceTokens[sourceSubjectIndex]!)) continue;\n let sourceCursor = sourceSubjectIndex + 1;\n let foundAlignedToken = false;\n let aligned = true;\n for (let candidateIndex = 1; candidateIndex < candidateTokens.length; candidateIndex += 1) {\n const candidateToken = candidateTokens[candidateIndex]!;\n const sourceIndex = sourceTokens.findIndex(\n (sourceToken, index) =>\n index >= sourceCursor && areGroundingTokensCompatible(candidateToken, sourceToken),\n );\n if (sourceIndex === -1) {\n if (hasCorrectionReordering) continue;\n aligned = false;\n break;\n }\n foundAlignedToken = true;\n const candidateNext = candidateTokens[candidateIndex + 1];\n const sourceNext = sourceTokens[sourceIndex + 1];\n if (\n candidateNext !== undefined\n && sourceNext !== undefined\n && !hasCorrectionReordering\n && !areGroundingTokensCompatible(candidateNext, sourceNext)\n && !isGroundingAlignmentModifier(sourceNext)\n ) {\n aligned = false;\n break;\n }\n sourceCursor = sourceIndex + 1;\n }\n if (aligned && foundAlignedToken) return true;\n }\n return false;\n}\n\nfunction omitsSourceDisjunction(candidate: string, source: string): boolean {\n if (!/\\bor\\b/iu.test(source) || /\\bor\\b/iu.test(candidate)) return false;\n const candidateTokens = normalizedGroundingTokenSequence(candidate);\n return splitGroundingClauses([source], true).some((sourceSpan) => {\n const sourceSpanTokens = normalizedGroundingTokenSequence(sourceSpan);\n return candidateTokens.length === sourceSpanTokens.length\n && candidateTokens.every(\n (token, index) => areGroundingTokensCompatible(token, sourceSpanTokens[index]!),\n );\n });\n}\n\nfunction groundedTokenScore(\n candidate: string,\n source: string,\n requireAlignedArguments = true,\n requireAllCandidateTokensGrounded = true,\n): number {\n const scriptAwareScore = spacelessScriptGroundedTokenScore(candidate, source);\n if (scriptAwareScore !== null) return scriptAwareScore;\n const candidateTokens = tokenize(candidate);\n if (candidateTokens.size === 0) return 0;\n const sourceTokens = tokenize(source);\n const allowCorrectionReordering = /\\b(?:rather\\s+than|instead\\s+of)\\b/iu.test(candidate);\n let sharedTokens = 0;\n let allCandidateTokensGrounded = true;\n for (const token of candidateTokens) {\n if ([...sourceTokens].some((sourceToken) => areGroundingTokensCompatible(token, sourceToken))) {\n sharedTokens += 1;\n } else if (!allowCorrectionReordering && token !== \"rather\" && token !== \"instead\") {\n allCandidateTokensGrounded = false;\n }\n }\n if (\n (requireAllCandidateTokensGrounded && !allCandidateTokensGrounded)\n || sharedTokens < GROUNDING_MIN_SHARED_TOKENS\n || sharedTokens / candidateTokens.size < GROUNDING_MIN_COVERAGE\n ) {\n return 0;\n }\n if (requireAlignedArguments && !hasAlignedSubjectPredicateOverlap(candidate, source)) return 0;\n return sharedTokens / candidateTokens.size;\n}\n\nfunction candidateClauses(candidate: string): string[] {\n return sourceSentences(candidate).flatMap((sentence) =>\n /\\bor\\b/iu.test(sentence) ? [sentence] : splitGroundingClauses([sentence]));\n}\n\nfunction isSourceGroundedClause(\n candidate: string,\n source: string,\n includeInterrogativeSource = false,\n): boolean {\n let bestSupportedScore = 0;\n let bestContradictedScore = 0;\n const sentences = sourceSentences(source);\n for (let index = 0; index < sentences.length; index += 1) {\n const sentence = sentences[index];\n if (isYesNoAnswer(sentence)) {\n const precedingSentence = sentences[index - 1];\n const answerToken = tokenSequence(sentence)[0];\n const contradictoryPolarity = precedingSentence !== undefined\n ? hasContradictoryPolarity(candidate, precedingSentence)\n : false;\n if (\n precedingSentence !== undefined\n && isInterrogativeSourceSentence(precedingSentence)\n && !omitsSourceDisjunction(candidate, precedingSentence)\n && groundedTokenScore(candidate, precedingSentence) === 1\n && (\n (answerToken === \"yes\" && !contradictoryPolarity)\n || (answerToken === \"no\" && contradictoryPolarity)\n )\n ) {\n return true;\n }\n continue;\n }\n const sentenceText = normalizeForExactMatch(sentence);\n const isExplanatoryLabel = sentenceText.startsWith(`${normalizeForExactMatch(candidate)}:`)\n && !sentence.trim().endsWith(\"?\");\n if (!includeInterrogativeSource && isInterrogativeSourceSentence(sentence) && !isExplanatoryLabel) {\n continue;\n }\n if (omitsSourceDisjunction(candidate, sentence)) continue;\n const sourceSpans = /\\b(?:rather\\s+than|instead\\s+of)\\b/iu.test(candidate)\n ? [sentence]\n : splitGroundingClauses([sentence], true);\n for (const sourceSpan of sourceSpans) {\n const sourceSpanText = normalizeForExactMatch(sourceSpan);\n if (containsExactTokenSequence(candidate, sourceSpanText)) {\n if (!hasContradictoryPolarity(candidate, sourceSpan)) return true;\n bestContradictedScore = Math.max(bestContradictedScore, 1);\n continue;\n }\n const score = groundedTokenScore(\n candidate,\n sourceSpan,\n !includeInterrogativeSource,\n !includeInterrogativeSource,\n );\n if (score === 0) continue;\n if (hasContradictoryPolarity(candidate, sourceSpan)) {\n bestContradictedScore = Math.max(bestContradictedScore, score);\n } else {\n bestSupportedScore = Math.max(bestSupportedScore, score);\n }\n }\n }\n return bestSupportedScore > bestContradictedScore;\n}\nfunction isSourceGrounded(\n candidate: string,\n source: string,\n includeInterrogativeSource = false,\n): boolean {\n const candidateText = normalizeForExactMatch(candidate);\n const sourceText = source.normalize(\"NFKC\").trim();\n if (candidateText.length === 0 || sourceText.length === 0) return false;\n const hasSupportedExactMatch = sourceSentences(sourceText).some((sentence) => {\n const sentenceText = normalizeForExactMatch(sentence);\n const isExplanatoryLabel = sentenceText.startsWith(`${candidateText}:`)\n && !sentence.trim().endsWith(\"?\");\n if (!includeInterrogativeSource && isInterrogativeSourceSentence(sentence) && !isExplanatoryLabel) return false;\n if (omitsSourceDisjunction(candidateText, sentenceText)) return false;\n return containsExactTokenSequence(candidateText, sentenceText)\n && !hasContradictoryPolarity(candidateText, sentenceText);\n });\n if (hasSupportedExactMatch) return true;\n\n const clauses = candidateClauses(candidate);\n if (clauses.length > 1) {\n return clauses.every((clause) =>\n isSourceGroundedClause(clause, sourceText, includeInterrogativeSource));\n }\n return isSourceGroundedClause(candidate, sourceText, includeInterrogativeSource);\n}\n\nfunction normalizedEntityIdentifierTokens(name: string): string[] {\n const identifier = normalizeForExactMatch(name).replace(/[-_]+/gu, \" \");\n const tokens = groundingLexemes(identifier)\n .filter(({ token }) => GROUNDING_STOPWORDS[token] !== true)\n .map(({ token }) => stemToken(token, true));\n return tokens.length > 1 && GROUNDING_ENTITY_TYPE_PREFIXES.has(tokens[0] ?? \"\")\n ? tokens.slice(1)\n : tokens;\n}\n\nfunction isGroundedEntityName(name: string, source: string): boolean {\n const nameTokens = normalizedEntityIdentifierTokens(name);\n return nameTokens.length > 0 && sourceSentences(source).some((sentence) => {\n const sentenceTokens = groundingLexemes(sentence)\n .filter(({ token }) => GROUNDING_STOPWORDS[token] !== true)\n .map(({ token, preserveTerminalS }) => stemToken(token, preserveTerminalS));\n return containsContiguousGroundingTokens(nameTokens, sentenceTokens);\n });\n}\nfunction buildEntitySupportSource(name: string, source: string): string {\n const nameTokens = normalizedEntityIdentifierTokens(name);\n if (nameTokens.length === 0) return \"\";\n return sourceSentences(source)\n .filter((sentence) => {\n const sentenceTokens = groundingLexemes(sentence)\n .filter(({ token }) => GROUNDING_STOPWORDS[token] !== true)\n .map(({ token, preserveTerminalS }) => stemToken(token, preserveTerminalS));\n return containsContiguousGroundingTokens(nameTokens, sentenceTokens);\n })\n .join(\" \");\n}\n\nfunction hasGroundedPredicateAnchor(candidate: string, sentence: string): boolean {\n const candidateTokens = normalizedGroundingTokenSequence(candidate);\n const sourceTokens = normalizedGroundingTokenSequence(sentence);\n const comparableCandidateTokens = GROUNDING_ROLE_SUBJECT_TOKENS.has(\n (candidateTokens[0] ?? \"\").replace(/^[\\u0000\\u0001]/u, \"\"),\n )\n ? candidateTokens.slice(1)\n : candidateTokens;\n if (comparableCandidateTokens.length < 2) return false;\n const subjectToken = comparableCandidateTokens[0];\n if (\n subjectToken === undefined\n || !sourceTokens.some((sourceToken) => areGroundingTokensCompatible(subjectToken, sourceToken))\n ) {\n return false;\n }\n const candidatePredicateTokens = comparableCandidateTokens.slice(1);\n const sharedPredicateTokens = candidatePredicateTokens.filter((token) =>\n sourceTokens.some((sourceToken) => areGroundingTokensCompatible(token, sourceToken)));\n const requiredSharedTokens = Math.min(2, candidatePredicateTokens.length);\n return sharedPredicateTokens.length >= requiredSharedTokens;\n}\nfunction hasGroundingAnchor(\n candidate: string,\n assertionSource: string,\n includeInterrogativeSource = false,\n requirePredicateSupport = false,\n): boolean {\n return sourceSentences(assertionSource).some((sentence) => {\n if (!includeInterrogativeSource && isInterrogativeSourceSentence(sentence)) return false;\n if (omitsSourceDisjunction(candidate, sentence)) return false;\n const sourceSpans = /\\b(?:rather\\s+than|instead\\s+of)\\b/iu.test(candidate)\n ? [sentence]\n : splitGroundingClauses([sentence], true);\n return sourceSpans.some((sourceSpan) => {\n const exactMatch = containsExactTokenSequence(candidate, sourceSpan)\n && !hasContradictoryPolarity(candidate, sourceSpan);\n if (exactMatch) return true;\n if (requirePredicateSupport && !hasGroundedPredicateAnchor(candidate, sourceSpan)) return false;\n return groundedTokenScore(candidate, sourceSpan) > 0\n || hasRoleNormalizedGrounding(candidate, sourceSpan);\n });\n });\n}\n\nfunction hasAnswerSupport(\n candidate: string,\n source: string,\n assertionSource: string,\n): boolean {\n const assertedAnswerSentences = new Set(\n sourceSentences(assertionSource)\n .filter((sentence) => {\n const answerToken = tokenSequence(sentence)[0];\n return answerToken === \"yes\" || answerToken === \"no\";\n })\n .map((sentence) => normalizeForExactMatch(sentence)),\n );\n if (assertedAnswerSentences.size === 0) return false;\n const sentences = sourceSentences(source);\n return sentences.some((sentence, index) => {\n const answerToken = tokenSequence(sentence)[0];\n if (answerToken !== \"yes\" && answerToken !== \"no\") return false;\n if (!assertedAnswerSentences.has(normalizeForExactMatch(sentence))) return false;\n const precedingSentence = sentences[index - 1];\n if (\n precedingSentence === undefined\n || !isInterrogativeSourceSentence(precedingSentence)\n || omitsSourceDisjunction(candidate, precedingSentence)\n || groundedTokenScore(candidate, precedingSentence) !== 1\n ) {\n return false;\n }\n const contradictoryPolarity = hasContradictoryPolarity(candidate, precedingSentence);\n return answerToken === \"yes\" ? !contradictoryPolarity : contradictoryPolarity;\n });\n}\n\nconst GROUNDING_ROLE_SUBJECT_TOKENS = new Set([\"assistant\", \"user\"]);\n\nfunction hasRoleNormalizedGrounding(candidate: string, source: string): boolean {\n const candidateTokens = groundingTokenSequence(candidate);\n if (!GROUNDING_ROLE_SUBJECT_TOKENS.has(\n (candidateTokens[0] ?? \"\").replace(/^[\\u0000\\u0001]/u, \"\"),\n )) return false;\n const claimTokens = candidateTokens.slice(1);\n if (claimTokens.length === 0) return false;\n\n return sourceSentences(source).some((sentence) => {\n if (isInterrogativeSourceSentence(sentence)) return false;\n const sourceTokens = groundingTokenSequence(sentence);\n const requiredSharedTokens = Math.min(GROUNDING_MIN_SHARED_TOKENS, claimTokens.length);\n let sourceIndex = 0;\n let sharedTokens = 0;\n for (const claimToken of claimTokens) {\n const matchingIndex = sourceTokens.findIndex(\n (sourceToken, index) =>\n index >= sourceIndex && areGroundingTokensCompatible(claimToken, sourceToken),\n );\n if (matchingIndex === -1) continue;\n sharedTokens += 1;\n sourceIndex = matchingIndex + 1;\n }\n return sharedTokens >= requiredSharedTokens\n && !hasContradictoryPolarity(candidate, sentence);\n });\n}\n\ninterface GroundingContext {\n source: string;\n assertionSource: string | undefined;\n allowRoleNormalization: boolean;\n fallbackSource?: string;\n fallbackAssertionSource?: string;\n}\n\nfunction resolveGroundingContext(\n candidate: string,\n source: string,\n assertionSource: string | undefined,\n roleAssertionSources: ExtractionGroundingRoleSources | undefined,\n): GroundingContext {\n const candidateRole = (groundingTokenSequence(candidate)[0] ?? \"\")\n .replace(/^[\\u0000\\u0001]/u, \"\");\n if (!GROUNDING_ROLE_SUBJECT_TOKENS.has(candidateRole)) {\n return { source, assertionSource, allowRoleNormalization: false };\n }\n if (roleAssertionSources === undefined) {\n return { source, assertionSource, allowRoleNormalization: true };\n }\n const roleSource = candidateRole === \"user\"\n ? roleAssertionSources.profile\n : roleAssertionSources.identity;\n if (roleSource === undefined) {\n return { source, assertionSource, allowRoleNormalization: true };\n }\n return {\n source: roleSource,\n assertionSource: roleSource,\n allowRoleNormalization: true,\n fallbackSource: source,\n fallbackAssertionSource: assertionSource,\n };\n}\n\nfunction selectGroundingContext(candidate: string, context: GroundingContext): GroundingContext {\n if (isGroundedCandidate(\n candidate,\n context.source,\n context.assertionSource,\n false,\n context.allowRoleNormalization,\n )) {\n return context;\n }\n if (\n context.fallbackSource === undefined\n || !hasExplicitRoleSubjectToken(\n (groundingTokenSequence(candidate)[0] ?? \"\").replace(/^[\\u0000\\u0001]/u, \"\"),\n sourceSentences(context.fallbackSource).map((sentence) => groundingTokenSequence(sentence)),\n )\n ) return context;\n const fallbackContext: GroundingContext = {\n source: context.fallbackSource,\n assertionSource: context.fallbackAssertionSource,\n allowRoleNormalization: false,\n };\n return isGroundedCandidate(\n candidate,\n fallbackContext.source,\n fallbackContext.assertionSource,\n false,\n fallbackContext.allowRoleNormalization,\n )\n ? fallbackContext\n : context;\n}\n\nfunction isGroundedCandidate(\n candidate: string,\n source: string,\n assertionSource: string | undefined,\n includeInterrogativeSource = false,\n allowRoleNormalization = false,\n): boolean {\n const allowInterrogativeSource = includeInterrogativeSource\n || (\n assertionSource !== undefined\n && normalizeForExactMatch(assertionSource) !== normalizeForExactMatch(source)\n );\n const sourceGrounded = isSourceGrounded(candidate, source, allowInterrogativeSource);\n const roleGrounded = allowRoleNormalization && hasRoleNormalizedGrounding(candidate, source);\n const candidateTokens = groundingTokenSequence(candidate);\n const roleNormalizedCandidate = allowRoleNormalization\n && GROUNDING_ROLE_SUBJECT_TOKENS.has(\n (candidateTokens[0] ?? \"\").replace(/^[\\u0000\\u0001]/u, \"\"),\n );\n if (roleNormalizedCandidate && !roleGrounded) return false;\n if (!sourceGrounded && !roleGrounded) return false;\n if (assertionSource === undefined) return true;\n const clauses = candidateClauses(candidate);\n const requirePredicateSupport = !includeInterrogativeSource\n && assertionSource !== undefined\n && normalizeForExactMatch(assertionSource) !== normalizeForExactMatch(source);\n return clauses.length > 0\n && (\n clauses.every((clause) =>\n hasGroundingAnchor(clause, assertionSource, includeInterrogativeSource, requirePredicateSupport))\n || hasAnswerSupport(candidate, source, assertionSource)\n );\n}\n\nfunction buildFactSupportSource(\n source: string,\n supportingSentences: ReadonlyArray<string>,\n): string {\n const sentences = sourceSentences(source);\n const selectedIndices = new Set<number>();\n for (const supportingSentence of supportingSentences) {\n const supportIndex = sentences.indexOf(supportingSentence);\n if (supportIndex < 0) continue;\n let endIndex = supportIndex;\n while (\n endIndex < sentences.length - 1\n && sentences[endIndex]!.trimEnd().endsWith(\";\")\n && /^(?:its|their|this|that|these|those)\\b/iu.test(\n sentences[endIndex + 1]!.trimStart(),\n )\n ) {\n endIndex += 1;\n }\n for (let index = supportIndex; index <= endIndex; index += 1) {\n selectedIndices.add(index);\n }\n }\n return [...selectedIndices]\n .sort((left, right) => left - right)\n .map((index) => sentences[index]!)\n .join(\" \");\n}\nfunction buildProcedureSupportSource(\n fact: ExtractionResult[\"facts\"][number],\n source: string,\n factSupportSource: string,\n): string {\n if (fact.category !== \"procedure\" || fact.procedureSteps === undefined) return factSupportSource;\n const parentSupportSentences = new Set(\n sourceSentences(factSupportSource).map((sentence) => normalizeForExactMatch(sentence)),\n );\n const parentGroundedSteps = fact.procedureSteps.filter((step) =>\n isGroundedCandidate(step.intent, factSupportSource, undefined, false),\n );\n if (parentGroundedSteps.length === 0) return factSupportSource;\n return sourceSentences(source)\n .filter((sentence) => {\n if (parentSupportSentences.has(normalizeForExactMatch(sentence))) return true;\n const sentenceTokens = tokenize(sentence);\n return parentGroundedSteps.some((step) =>\n [...tokenize(step.intent)].some((token) =>\n [...sentenceTokens].some((sourceToken) => areGroundingTokensCompatible(token, sourceToken)),\n ),\n );\n })\n .join(\" \");\n}\nfunction filterGroundedFact(\n fact: ExtractionResult[\"facts\"][number],\n source: string,\n assertionSource: string | undefined,\n roleAssertionSources: ExtractionGroundingRoleSources | undefined,\n eventTimeNormalizer: ((eventTime: string) => string) | undefined,\n): ExtractionResult[\"facts\"][number] | undefined {\n const factContext = selectGroundingContext(\n fact.content,\n resolveGroundingContext(fact.content, source, assertionSource, roleAssertionSources),\n );\n if (!isGroundedCandidate(\n fact.content,\n factContext.source,\n factContext.assertionSource,\n false,\n factContext.allowRoleNormalization,\n )) return undefined;\n const factEventTime = fact.eventTime;\n const groundedFactEventTime = factEventTime === undefined\n ? undefined\n : eventTimeNormalizer?.(factEventTime) ?? factEventTime;\n const factSupportingSentences = sourceSentences(factContext.assertionSource ?? factContext.source).filter(\n (sentence) =>\n isGroundedCandidate(\n fact.content,\n sentence,\n undefined,\n false,\n factContext.allowRoleNormalization,\n ),\n );\n const factSupportingSource = factEventTime === undefined\n ? factSupportingSentences[0]\n : factSupportingSentences.find((sentence) =>\n isGroundedCandidate(\n groundedFactEventTime ?? factEventTime,\n sentence,\n undefined,\n false,\n factContext.allowRoleNormalization,\n ),\n ) ?? factSupportingSentences[0];\n const eventTimeSource = factSupportingSource ?? factContext.source;\n const eventTimeAssertionSource = factSupportingSource === undefined\n ? factContext.assertionSource\n : undefined;\n\n const factSupportSource = buildFactSupportSource(\n factContext.assertionSource ?? factContext.source,\n factSupportingSentences,\n );\n const groundedAttributes = fact.structuredAttributes\n ? Object.fromEntries(\n Object.entries(fact.structuredAttributes)\n .filter(([key, value]) =>\n isGroundedCandidate(\n `${key}: ${value}`,\n factSupportSource,\n undefined,\n false,\n factContext.allowRoleNormalization,\n ),\n ),\n )\n : undefined;\n const procedureGroundingSource = buildProcedureSupportSource(\n fact,\n factContext.assertionSource ?? factContext.source,\n factSupportSource,\n );\n const groundedProcedureSteps = fact.procedureSteps\n ? fact.procedureSteps.flatMap((step) => {\n if (!isGroundedCandidate(step.intent, procedureGroundingSource, undefined, false)) return [];\n const expectedOutcome = step.expectedOutcome\n && isGroundedCandidate(step.expectedOutcome, procedureGroundingSource, undefined, false)\n ? step.expectedOutcome\n : undefined;\n const toolCall = step.toolCall\n && isGroundedCandidate(step.toolCall.signature, procedureGroundingSource, undefined, false)\n ? step.toolCall\n : undefined;\n const {\n expectedOutcome: _expectedOutcome,\n toolCall: _toolCall,\n ...stepWithoutOptionalFields\n } = step;\n return [{\n ...stepWithoutOptionalFields,\n ...(expectedOutcome !== undefined ? { expectedOutcome } : {}),\n ...(toolCall !== undefined ? { toolCall } : {}),\n }];\n })\n : undefined;\n const groundedReasoningTrace = fact.reasoningTrace\n && fact.reasoningTrace.steps.length > 0\n && isGroundedCandidate(\n fact.reasoningTrace.finalAnswer,\n factContext.source,\n factContext.assertionSource,\n false,\n factContext.allowRoleNormalization,\n )\n && fact.reasoningTrace.steps.every((step) =>\n isGroundedCandidate(\n step.description,\n factContext.source,\n factContext.assertionSource,\n false,\n factContext.allowRoleNormalization,\n ),\n )\n ? {\n steps: fact.reasoningTrace.steps,\n finalAnswer: fact.reasoningTrace.finalAnswer,\n ...(fact.reasoningTrace.observedOutcome\n && isGroundedCandidate(\n fact.reasoningTrace.observedOutcome,\n factContext.source,\n factContext.assertionSource,\n false,\n factContext.allowRoleNormalization,\n )\n ? { observedOutcome: fact.reasoningTrace.observedOutcome }\n : {}),\n }\n : undefined;\n const groundedEventTime = groundedFactEventTime\n && isGroundedCandidate(groundedFactEventTime, eventTimeSource, eventTimeAssertionSource)\n ? factEventTime\n : undefined;\n const groundedEntityRef = fact.entityRef !== undefined\n && isGroundedEntityName(fact.entityRef, factSupportSource)\n ? fact.entityRef\n : undefined;\n const {\n entityRef: _entityRef,\n structuredAttributes: _structuredAttributes,\n procedureSteps: _procedureSteps,\n reasoningTrace: _reasoningTrace,\n eventTime: _eventTime,\n ...factWithoutGroundingFields\n } = fact;\n return {\n ...factWithoutGroundingFields,\n ...(groundedEntityRef !== undefined ? { entityRef: groundedEntityRef } : {}),\n ...(groundedAttributes && Object.keys(groundedAttributes).length > 0\n ? { structuredAttributes: groundedAttributes }\n : {}),\n ...(groundedProcedureSteps && groundedProcedureSteps.length > 0\n ? { procedureSteps: groundedProcedureSteps }\n : {}),\n ...(groundedReasoningTrace !== undefined ? { reasoningTrace: groundedReasoningTrace } : {}),\n ...(groundedEventTime !== undefined ? { eventTime: groundedEventTime } : {}),\n };\n}\n\nfunction filterGroundedEntity(\n entity: ExtractionResult[\"entities\"][number],\n source: string,\n assertionSource: string | undefined,\n): ExtractionResult[\"entities\"][number] | undefined {\n if (!isGroundedEntityName(entity.name, source)) return undefined;\n const entitySource = buildEntitySupportSource(entity.name, source);\n const entityAssertionSource = assertionSource === undefined\n ? undefined\n : buildEntitySupportSource(entity.name, assertionSource);\n const facts = entity.facts.filter((fact) =>\n isGroundedCandidate(fact, entitySource, entityAssertionSource),\n );\n const structuredSections = entity.structuredSections\n ?.flatMap((section) => {\n const groundedFacts = section.facts.filter((fact) =>\n isGroundedCandidate(fact, entitySource, entityAssertionSource),\n );\n return groundedFacts.length > 0\n ? [{ ...section, facts: groundedFacts }]\n : [];\n });\n if (facts.length === 0 && (structuredSections === undefined || structuredSections.length === 0)) {\n return undefined;\n }\n const { structuredSections: _structuredSections, ...entityWithoutSections } = entity;\n return {\n ...entityWithoutSections,\n facts,\n ...(structuredSections && structuredSections.length > 0 ? { structuredSections } : {}),\n };\n}\n\nfunction normalizedEntitySourceText(name: string): string {\n return normalizedEntityIdentifierTokens(name).join(\" \");\n}\n\nfunction isGroundedRelationship(\n relationship: NonNullable<ExtractionResult[\"relationships\"]>[number],\n source: string,\n assertionSource: string | undefined,\n): boolean {\n const sourceName = normalizedEntitySourceText(relationship.source);\n const targetName = normalizedEntitySourceText(relationship.target);\n const labelTokens = tokenize(relationship.label);\n if (sourceName.length === 0 || targetName.length === 0 || labelTokens.size === 0) return false;\n const relationText = `${sourceName} ${relationship.label} ${targetName}`;\n const hasCoherentSourceSpan = sourceSentences(source).some((sentence) => {\n if (isInterrogativeSourceSentence(sentence)) return false;\n return groundedTokenScore(relationText, sentence) === 1\n && !hasContradictoryPolarity(relationText, sentence);\n });\n return hasCoherentSourceSpan\n && isGroundedCandidate(relationText, source, assertionSource);\n}\nconst GROUNDING_TEMPORAL_WORDS = new Set([\n \"today\",\n \"yesterday\",\n \"tomorrow\",\n \"now\",\n \"recently\",\n \"earlier\",\n \"later\",\n \"soon\",\n \"morning\",\n \"afternoon\",\n \"evening\",\n \"tonight\",\n \"night\",\n \"noon\",\n \"midnight\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n \"sunday\",\n \"january\",\n \"february\",\n \"march\",\n \"april\",\n \"may\",\n \"june\",\n \"july\",\n \"august\",\n \"september\",\n \"october\",\n \"november\",\n \"december\",\n \"q1\",\n \"q2\",\n \"q3\",\n \"q4\",\n]);\nconst GROUNDING_TEMPORAL_CLOCK_PATTERN = /\\b\\d{1,2}:\\d{2}(?:\\s*[ap]\\.?m\\.?)?\\b/iu;\nconst GROUNDING_TEMPORAL_DURATION_PATTERN = new RegExp(\n \"\\\\b(?:\\\\d+|one|two|three|four|five|six|seven|eight|nine|ten)\\\\s+\"\n + \"(?:seconds?|minutes?|hours?|days?|weeks?|months?|quarters?|years?)\\\\b\",\n \"iu\",\n);\n\nfunction isWhenQuestion(question: string): boolean {\n return /^(?:when|what\\s+(?:time|date)|which\\s+day)\\b/iu.test(question.trim());\n}\nfunction isWhyQuestion(question: string): boolean {\n return /^why\\b/iu.test(question.trim());\n}\n\nfunction hasCausalAnswerEvidence(question: string, sentence: string): boolean {\n if (!isWhyQuestion(question)) return true;\n return /\\b(?:because|since|due\\s+to|owing\\s+to|thanks\\s+to|therefore|thus|hence|so)\\b/iu.test(\n sentence,\n );\n}\n\nfunction hasTemporalAnswerEvidence(question: string, sentence: string): boolean {\n if (!isWhenQuestion(question)) return true;\n return groundingLexemes(sentence).some(({ token }) =>\n GROUNDING_TEMPORAL_WORDS.has(token) || /^(?:19|20)\\d{2}$/u.test(token),\n )\n || GROUNDING_TEMPORAL_CLOCK_PATTERN.test(sentence)\n || GROUNDING_TEMPORAL_DURATION_PATTERN.test(sentence);\n}\n\n\nfunction isUnknownAnswerSentence(sentence: string): boolean {\n return /\\b(?:unknown|unclear|unsure|unresolved|unanswered|not\\s+(?:known|sure|available)|don't\\s+know|do\\s+not\\s+know|no\\s+idea|pending)\\b/iu\n .test(sentence);\n}\n\nfunction isYesNoAnswer(sentence: string): boolean {\n return /^(?:yes|no)(?:[.!?]|,\\s*(?:absolutely|definitely|indeed|exactly|correct|of\\s+course|use\\s+that|do\\s+that)[.!?]?)?$/iu\n .test(sentence.trim());\n}\n\nconst GROUNDING_WH_OBJECT_QUESTION_PATTERN = new RegExp(\n \"^(?:(?:what|which)(?:\\\\s+.+?)?|who|whom)\\\\s+\"\n + \"(?:is|are|was|were|do|does|did|can|could|will|would|should|has|have|had)\\\\s+\"\n + \"(.+?)\\\\??$\",\n \"iu\",\n);\n\nfunction hasWhAnswerRoleAlignment(question: string, sentence: string): boolean {\n const normalizedQuestion = question.trim();\n const objectQuestionMatch = GROUNDING_WH_OBJECT_QUESTION_PATTERN.exec(normalizedQuestion);\n const sourceTokens = normalizedGroundingTokenSequence(sentence);\n if (objectQuestionMatch !== null) {\n const questionBodyLexemes = groundingLexemes(objectQuestionMatch[1] ?? \"\");\n const predicateIndex = questionBodyLexemes.findIndex(({ isPredicate }) => isPredicate);\n if (predicateIndex < 1) return false;\n const subjectTokens = groundingTokenSequence(\n questionBodyLexemes.slice(0, predicateIndex).map(({ surface }) => surface).join(\" \"),\n );\n const predicateTokens = groundingTokenSequence(\n questionBodyLexemes.slice(predicateIndex).map(({ surface }) => surface).join(\" \"),\n );\n if (subjectTokens.length === 0 || predicateTokens.length === 0) return false;\n let sourceIndex = 0;\n for (const token of [...subjectTokens, ...predicateTokens]) {\n const matchedIndex = sourceTokens.findIndex(\n (sourceToken, index) =>\n index >= sourceIndex && areGroundingTokensCompatible(token, sourceToken),\n );\n if (matchedIndex === -1) return false;\n sourceIndex = matchedIndex + 1;\n }\n return true;\n }\n\n const subjectQuestionMatch = /^(?:who|what)\\s+([^\\s?]+)\\s+(.+?)\\??$/iu.exec(normalizedQuestion);\n if (subjectQuestionMatch === null) return true;\n const predicateTokens = groundingTokenSequence(subjectQuestionMatch[1] ?? \"\");\n const objectTokens = groundingTokenSequence(subjectQuestionMatch[2] ?? \"\");\n if (predicateTokens.length === 0 || objectTokens.length === 0) return true;\n const predicateStart = sourceTokens.findIndex((sourceToken) =>\n areGroundingTokensCompatible(predicateTokens[0]!, sourceToken));\n if (predicateStart === -1) return false;\n let sourceIndex = predicateStart + predicateTokens.length;\n for (const objectToken of objectTokens) {\n const objectIndex = sourceTokens.findIndex(\n (sourceToken, index) =>\n index >= sourceIndex && areGroundingTokensCompatible(objectToken, sourceToken),\n );\n if (objectIndex === -1) return false;\n sourceIndex = objectIndex + 1;\n }\n return true;\n}\n\nfunction isQuestionAnsweredBySource(\n question: string,\n source: string,\n assertionSource: string | undefined,\n): boolean {\n const questionTokens = tokenize(question);\n if (questionTokens.size === 0) return false;\n const isYesNoQuestion = /^(?:is|are|am|was|were|do|does|did|can|could|will|would|should|has|have|had)\\b/iu\n .test(question.trim());\n const assertedSentences = new Set(sourceSentences(assertionSource ?? source).map((sentence) => normalizeForExactMatch(sentence)));\n const sentences = sourceSentences(source);\n return sentences.some((sentence, index) => {\n if (!assertedSentences.has(normalizeForExactMatch(sentence))) return false;\n if (isInterrogativeSourceSentence(sentence)) return false;\n if (isYesNoAnswer(sentence)) {\n const precedingSentence = sentences[index - 1];\n return precedingSentence !== undefined\n && isInterrogativeSourceSentence(precedingSentence)\n && groundedTokenScore(question, precedingSentence) === 1;\n }\n if (isUnknownAnswerSentence(sentence)) return false;\n const score = groundedTokenScore(question, sentence, false);\n if (score !== 1) return false;\n const sentenceTokens = tokenize(sentence);\n const hasAnswerToken = [...sentenceTokens].some((token) => !questionTokens.has(token));\n return (isYesNoQuestion || hasAnswerToken)\n && hasTemporalAnswerEvidence(question, sentence)\n && hasCausalAnswerEvidence(question, sentence)\n && hasWhAnswerRoleAlignment(question, sentence);\n });\n}\n\nfunction groundQuestion(\n question: ExtractionResult[\"questions\"][number],\n source: string,\n assertionSource: string | undefined,\n): ExtractionResult[\"questions\"][number] | undefined {\n if (isQuestionAnsweredBySource(question.question, source, assertionSource)) return undefined;\n if (!isGroundedCandidate(question.question, source, assertionSource, true)) return undefined;\n const normalizedContext = question.context.trim();\n if (\n normalizedContext.length > 0\n && !isGroundedCandidate(normalizedContext, assertionSource ?? source, undefined, false)\n ) {\n return { ...question, context: \"\" };\n }\n return question;\n}\n\nfunction isRoleGroundedCandidate(\n candidate: string,\n source: string,\n assertionSource: string | undefined,\n roleAssertionSources: ExtractionGroundingRoleSources | undefined,\n): boolean {\n const context = selectGroundingContext(\n candidate,\n resolveGroundingContext(candidate, source, assertionSource, roleAssertionSources),\n );\n return isGroundedCandidate(\n candidate,\n context.source,\n context.assertionSource,\n false,\n context.allowRoleNormalization,\n );\n}\n\nexport function filterExtractionResultBySource(\n result: ExtractionResult,\n source: string,\n assertionSource?: string,\n roleAssertionSources?: ExtractionGroundingRoleSources,\n eventTimeNormalizer?: (eventTime: string) => string,\n): ExtractionResult {\n if (source.trim().length === 0) {\n return {\n ...result,\n facts: [],\n profileUpdates: [],\n entities: [],\n questions: [],\n ...(result.relationships !== undefined ? { relationships: [] } : {}),\n identityReflection: undefined,\n };\n }\n\n const facts = result.facts.flatMap((fact) => {\n const grounded = filterGroundedFact(\n fact,\n source,\n assertionSource,\n roleAssertionSources,\n eventTimeNormalizer,\n );\n return grounded === undefined ? [] : [grounded];\n });\n const profileUpdates = result.profileUpdates.filter((update) =>\n isRoleGroundedCandidate(update, source, assertionSource, roleAssertionSources),\n );\n const entities = result.entities.flatMap((entity) => {\n const grounded = filterGroundedEntity(entity, source, assertionSource);\n return grounded === undefined ? [] : [grounded];\n });\n const questions = result.questions.flatMap((question) => {\n const grounded = groundQuestion(question, source, assertionSource);\n return grounded === undefined ? [] : [grounded];\n });\n const relationships = result.relationships?.filter((relationship) =>\n isGroundedRelationship(relationship, source, assertionSource),\n );\n const identityReflection = result.identityReflection\n && isRoleGroundedCandidate(\n result.identityReflection,\n source,\n assertionSource,\n roleAssertionSources,\n )\n ? result.identityReflection\n : undefined;\n\n return {\n ...result,\n facts,\n profileUpdates,\n entities,\n questions,\n ...(result.relationships !== undefined ? { relationships } : {}),\n ...(identityReflection !== undefined ? { identityReflection } : { identityReflection: undefined }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCO,SAAS,+BACd,QACA,YACA,sBAA8B,YAC9B,sBACA,kBACA,SACkB;AAClB,MAAI,CAAC,QAAQ,gBAAiB,QAAO;AACrC,QAAM,eAAe,CAAC,WACpB,QAAQ,4B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ourceIndex"]}
@@ -1,10 +1,10 @@
1
- import {
2
- scanMemoryDir
3
- } from "./chunk-W7IGLX4G.js";
4
1
  import {
5
2
  isSearchAborted,
6
3
  throwIfSearchAborted
7
4
  } from "./chunk-GUMZC2BO.js";
5
+ import {
6
+ scanMemoryDir
7
+ } from "./chunk-W7IGLX4G.js";
8
8
  import {
9
9
  reportSearchDegradation,
10
10
  resolveEnsureCollectionArgs
@@ -508,4 +508,4 @@ function isMissingVectorProviderColumnError(err) {
508
508
  export {
509
509
  LanceDbBackend
510
510
  };
511
- //# sourceMappingURL=chunk-OQIRBGUU.js.map
511
+ //# sourceMappingURL=chunk-2Q4UAPLD.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SUPPORT_PASSPORT_DRAFT_MAX_CONTENT_CHARACTERS,
3
3
  SUPPORT_PASSPORT_DRAFT_MAX_MEMORIES
4
- } from "./chunk-BPQ7L27U.js";
4
+ } from "./chunk-MIM7QT6H.js";
5
5
  import {
6
6
  SUPPORT_PASSPORT_SOURCE_MEMORY_ID_MAX_LENGTH
7
7
  } from "./chunk-XDL5CYZN.js";
@@ -343,4 +343,4 @@ export {
343
343
  parseSupportPassportModelJob,
344
344
  SupportPassportModelBridge
345
345
  };
346
- //# sourceMappingURL=chunk-3IMYRX3W.js.map
346
+ //# sourceMappingURL=chunk-34E5NBQI.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  StorageManager
3
- } from "./chunk-Q5XKKDFQ.js";
3
+ } from "./chunk-5SZ6CLGJ.js";
4
4
  import {
5
5
  composeMemoryEnvelope
6
6
  } from "./chunk-LCU5R6TQ.js";
@@ -546,4 +546,4 @@ export {
546
546
  setSemanticRulePromotionTestHooks,
547
547
  promoteSemanticRuleFromMemory
548
548
  };
549
- //# sourceMappingURL=chunk-BRHKW7GY.js.map
549
+ //# sourceMappingURL=chunk-4IIDTPSK.js.map
@@ -17,7 +17,7 @@ import {
17
17
  } from "./chunk-46WM6JX2.js";
18
18
  import {
19
19
  normalizeQmdResultPath
20
- } from "./chunk-AJRJDXYR.js";
20
+ } from "./chunk-E7MYSCSL.js";
21
21
  import {
22
22
  withholdToolScopedFromSharedNamespace
23
23
  } from "./chunk-S2V7RUCL.js";
@@ -11175,4 +11175,4 @@ export {
11175
11175
  isValidBufferSurpriseEvent,
11176
11176
  StorageManager3 as StorageManager
11177
11177
  };
11178
- //# sourceMappingURL=chunk-Q5XKKDFQ.js.map
11178
+ //# sourceMappingURL=chunk-5SZ6CLGJ.js.map
@@ -1,12 +1,12 @@
1
+ import {
2
+ encryptCapsuleFile
3
+ } from "./chunk-UVYI6VIX.js";
1
4
  import {
2
5
  CAPSULE_ID_PATTERN,
3
6
  CapsuleBlockSchema,
4
7
  ExportBundleV2Schema,
5
8
  ExportManifestV2Schema
6
9
  } from "./chunk-WEHSQBFR.js";
7
- import {
8
- encryptCapsuleFile
9
- } from "./chunk-DQEMWVMT.js";
10
10
  import {
11
11
  CAPSULE_SCHEMA_VERSION,
12
12
  EXPORT_FORMAT
@@ -261,4 +261,4 @@ export {
261
261
  exportCapsule,
262
262
  isValidCapsuleSince
263
263
  };
264
- //# sourceMappingURL=chunk-VDX2J7OX.js.map
264
+ //# sourceMappingURL=chunk-5W7CTZ2E.js.map
@@ -11,7 +11,7 @@ import {
11
11
  } from "./chunk-S4DDLTPX.js";
12
12
  import {
13
13
  LocalLlmClient
14
- } from "./chunk-IVKIODHO.js";
14
+ } from "./chunk-MB6GLPRY.js";
15
15
  import {
16
16
  FallbackLlmClient,
17
17
  fallbackLlmRuntimeContextFromConfig,
@@ -690,4 +690,4 @@ ${truncatedConversation}`;
690
690
  export {
691
691
  HourlySummarizer
692
692
  };
693
- //# sourceMappingURL=chunk-EUYWQ7TS.js.map
693
+ //# sourceMappingURL=chunk-652S5A5D.js.map
@@ -11,6 +11,10 @@ import {
11
11
  import {
12
12
  containsPhrase
13
13
  } from "./chunk-SVH57F5Z.js";
14
+ import {
15
+ detectEntityQueryMode,
16
+ isStructuralEntityFollowUpQuery
17
+ } from "./chunk-MKYRCCSN.js";
14
18
  import {
15
19
  collectNativeKnowledgeChunks
16
20
  } from "./chunk-2DQ2XREU.js";
@@ -19,7 +23,7 @@ import {
19
23
  } from "./chunk-7ZNJN5WZ.js";
20
24
  import {
21
25
  compareEntityTimestamps
22
- } from "./chunk-Q5XKKDFQ.js";
26
+ } from "./chunk-5SZ6CLGJ.js";
23
27
  import {
24
28
  normalizeEntityName
25
29
  } from "./chunk-YXZG5TVN.js";
@@ -45,7 +49,6 @@ var ENTITY_INDEX_VERSION = 3;
45
49
  var RECENT_TRANSCRIPT_LOOKBACK_HOURS = 24;
46
50
  var INSTRUCTION_LIKE_RE = /\b(always|never|must|should|remember to|do not|don't|process|workflow|template|checklist|instruction)\b/i;
47
51
  var METADATA_WRAPPER_RE = /^(source|context|metadata|notes?):/i;
48
- var ENTITY_PRONOUN_RE = /\b(he|him|his|she|her|they|them|their|it|its)\b/i;
49
52
  var BELIEF_LEDGER_SECTION_KEY = "belief_ledger";
50
53
  var BELIEF_LEDGER_FACT_RE = /^claim=([^;]+);\s*status=([^;]+);\s*updatedAt=([^;]+);\s*(.+)$/;
51
54
  function tokenize(value) {
@@ -120,28 +123,6 @@ function relationLine(entry, relationship) {
120
123
  if (normalizedLabel.length === 0) return `${entry.name} is connected to ${relationship.target}`;
121
124
  return `${entry.name} ${normalizedLabel} ${relationship.target}`;
122
125
  }
123
- function detectEntityQueryMode(query) {
124
- const normalized = normalizeEntityText(query);
125
- if (!normalized) return null;
126
- if (/^(what about|and what about|how about|what happened (with|to) (he|him|his|she|her|they|them|their|it|its)|did (he|she|they|it)|is (he|she|they|it)|was (he|she|they|it))\b/.test(normalized)) {
127
- return "follow_up";
128
- }
129
- if (/^(who is|who s|what do we know about|what does|tell me about|what can you tell me about|what s new with|what happened with|what happened to|status of|where is|how is)\b/.test(normalized)) {
130
- if (/^what does\b/.test(normalized)) {
131
- if (/^what does (?:this|that|it|the|a|an|my|our|your|their)\b/.test(normalized)) {
132
- return null;
133
- }
134
- if (/^what does [a-z0-9-]+ (?:error|warning|exception|failure|stack|trace|code|message|log)\b/.test(normalized) && /\b(mean|means|indicate|indicates|imply|implies)\b/.test(normalized)) {
135
- return null;
136
- }
137
- }
138
- return /what happened|what s new|status of|how is|where is/.test(normalized) ? "timeline" : "direct";
139
- }
140
- if (ENTITY_PRONOUN_RE.test(normalized) && normalized.split(/\s+/).length <= 8) {
141
- return "follow_up";
142
- }
143
- return null;
144
- }
145
126
  function scoreAliasMatch(query, alias) {
146
127
  const normalizedQuery = normalizeEntityText(query);
147
128
  const normalizedAlias = normalizeEntityText(alias);
@@ -824,7 +805,12 @@ function formatEntityHintSection(candidates, queryTokens, mode, maxRelatedEntiti
824
805
  async function buildEntityRecallSection(options) {
825
806
  checkEntityRecallAbort(options.abortSignal);
826
807
  const prefixedMode = detectEntityQueryMode(options.query);
827
- const persistedIndex = prefixedMode ? null : await readCurrentPersistedEntityIndex(
808
+ const structuralFollowUp = prefixedMode === null && isStructuralEntityFollowUpQuery(
809
+ options.query,
810
+ options.recentTurns > 0 && options.transcriptEntries.length > 0
811
+ );
812
+ const earlyMode = prefixedMode ?? (structuralFollowUp ? "follow_up" : null);
813
+ const persistedIndex = earlyMode ? null : await readCurrentPersistedEntityIndex(
828
814
  options.storage,
829
815
  options.config,
830
816
  options.recallNamespaces,
@@ -832,7 +818,7 @@ async function buildEntityRecallSection(options) {
832
818
  );
833
819
  checkEntityRecallAbort(options.abortSignal);
834
820
  let nativeChunks;
835
- if (!prefixedMode && persistedIndex && resolveLanguageIndependentExplicitCandidates(persistedIndex, options.query).length === 0) {
821
+ if (!earlyMode && persistedIndex && resolveLanguageIndependentExplicitCandidates(persistedIndex, options.query).length === 0) {
836
822
  nativeChunks = await readNativeChunks(options.config, options.recallNamespaces);
837
823
  if (!hasFreshNativeExplicitMention(persistedIndex, nativeChunks, options.query)) {
838
824
  return entityRecallSectionAbsent(options.abortSignal);
@@ -871,7 +857,10 @@ async function buildEntityRecallSection(options) {
871
857
  const explicitCandidates = resolveExplicitCandidates(index, options.query);
872
858
  await yieldEntityRecallScan(options.abortSignal);
873
859
  const queryCandidates = prefixedMode ? explicitCandidates : resolveLanguageIndependentExplicitCandidates(index, options.query);
874
- const mode = prefixedMode ?? (queryCandidates.length > 0 ? "direct" : null);
860
+ if (queryCandidates.length === 0 && /^what does (?:this|that|it|the|a|an|my|our|your|their)\b/i.test(normalizeEntityText(options.query))) {
861
+ return entityRecallSectionAbsent(options.abortSignal);
862
+ }
863
+ const mode = prefixedMode ?? (queryCandidates.length > 0 ? "direct" : structuralFollowUp ? "follow_up" : null);
875
864
  if (!mode) return entityRecallSectionAbsent(options.abortSignal);
876
865
  const candidates = queryCandidates.length > 0 ? queryCandidates : resolveRecentTurnCandidates(index, options.transcriptEntries, options.recentTurns);
877
866
  if (candidates.length === 0) return entityRecallSectionAbsent(options.abortSignal);
@@ -929,4 +918,4 @@ export {
929
918
  entityIndexVersion,
930
919
  entityRecentTranscriptLookbackHours
931
920
  };
932
- //# sourceMappingURL=chunk-ULZFZL7K.js.map
921
+ //# sourceMappingURL=chunk-6IKXAAJI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/entity-retrieval.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { renderAuthorityBoundContent } from \"./recall-context-composition.js\";\nimport { createHash } from \"node:crypto\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collectNativeKnowledgeChunks, type NativeKnowledgeChunk } from \"./native-knowledge.js\";\nimport { compareEntityTimestamps, normalizeEntityName, type StorageManager } from \"./storage.js\";\nimport { normalizeEntityText, resolveRequestedEntitySectionKeys } from \"./entity-schema.js\";\nimport type { EntityStructuredSection, MemoryFile, PluginConfig, TranscriptEntry } from \"./types.js\";\nimport { truncateGraphemeSafe } from \"./whitespace.js\";\nimport { containsPhrase } from \"./entity-retrieval-boundaries.js\";\nimport {\n detectEntityQueryMode,\n isStructuralEntityFollowUpQuery,\n type EntityQueryMode,\n} from \"./entity-retrieval-i18n.js\";\nimport { buildOriginStructuredSections, sanitizeOriginatedFacts, type EntityOriginStructuredSection } from \"./entity-origin-fields.js\";\nimport {\n checkEntityRecallAbort,\n entityRecallSectionAbsent,\n yieldEntityRecallScan,\n yieldEntityRecallScanEvery,\n} from \"./entity-recall-cancellation.js\";\nconst ENTITY_INDEX_VERSION = 3;\nconst RECENT_TRANSCRIPT_LOOKBACK_HOURS = 24;\nconst INSTRUCTION_LIKE_RE = /\\b(always|never|must|should|remember to|do not|don't|process|workflow|template|checklist|instruction)\\b/i;\nconst METADATA_WRAPPER_RE = /^(source|context|metadata|notes?):/i;\nconst BELIEF_LEDGER_SECTION_KEY = \"belief_ledger\";\nconst BELIEF_LEDGER_FACT_RE = /^claim=([^;]+);\\s*status=([^;]+);\\s*updatedAt=([^;]+);\\s*(.+)$/;\ntype EntityMentionIndexEntry = {\n canonicalId: string;\n name: string;\n type: string;\n summary?: string;\n aliases: string[];\n facts: string[];\n timelineFacts: string[];\n timelineFactOrigins?: Array<string | undefined>;\n structuredSections: EntityOriginStructuredSection[];\n timeline: Array<{\n timestamp: string;\n text: string;\n source?: string;\n sessionKey?: string;\n principal?: string;\n origin?: string;\n }>;\n relationships: Array<{ target: string; label: string }>;\n activity: Array<{ date: string; note: string }>;\n factCount: number;\n memorySnippets: string[]; memorySnippetOrigins?: Array<string | undefined>;\n nativeChunks: Array<{\n chunkId: string;\n title: string;\n sourceKind: NativeKnowledgeChunk[\"sourceKind\"];\n sourcePath: string;\n snippet: string;\n derivedDate?: string;\n }>;\n};\ntype EntityMentionIndex = {\n version: number;\n updatedAt: string;\n entityStatusVersion?: number;\n entities: EntityMentionIndexEntry[];\n};\ntype EntityCandidate = {\n entry: EntityMentionIndexEntry;\n alias: string;\n score: number;\n source: \"query\" | \"recent_turn\";\n};\ntype EntityHintSnippet = {\n text: string;\n score: number;\n kind: \"summary\" | \"fact\" | \"section\" | \"relationship\" | \"activity\" | \"memory\" | \"native\"; origin?: string;\n};\nexport interface BuildEntityRecallSectionOptions {\n config: PluginConfig;\n storage: StorageManager;\n namespaceStorage?: (namespace: string) => Promise<StorageManager>;\n query: string;\n recallNamespaces?: string[];\n recentTurns: number;\n maxHints: number;\n maxSupportingFacts: number;\n maxRelatedEntities: number;\n maxChars: number;\n transcriptEntries: TranscriptEntry[];\n originAuthorityEnabled?: boolean; untrustedOrigins?: readonly string[];\n /**\n * Cancels the build at its next checkpoint (issue #2291). Entity recall reads\n * every entity and memory file across the recalled namespaces, which is\n * minutes of work on a large or slow store; without this the scan kept running\n * after the recall that asked for it had been abandoned.\n */\n abortSignal?: AbortSignal;\n}\nfunction tokenize(value: string): string[] {\n return normalizeEntityText(value).split(/\\s+/).filter((token) => token.length >= 2);\n}\nfunction uniqueStrings(values: string[]): string[] {\n return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];\n}\nfunction compactLine(value: string, maxLength: number = 220): string {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= maxLength) return normalized;\n return `${truncateGraphemeSafe(normalized, maxLength - 1).trimEnd()}…`;\n}\nfunction dedupeHintSnippetsByText(snippets: EntityHintSnippet[]): EntityHintSnippet[] {\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const key = normalizeEntityText(snippet.text);\n const existing = deduped.get(key);\n if (!existing) {\n deduped.set(key, snippet);\n continue;\n }\n if (existing.origin !== snippet.origin) {\n existing.origin = undefined;\n }\n }\n return [...deduped.values()];\n}\nfunction isBeliefLedgerSection(section: Pick<EntityStructuredSection, \"key\">): boolean {\n return normalizeEntityText(section.key).replace(/\\s+/g, \"_\") === BELIEF_LEDGER_SECTION_KEY;\n}\nfunction beliefLedgerFactKeys(sections: EntityStructuredSection[]): Set<string> {\n const keys = new Set<string>();\n for (const section of sections) {\n if (!isBeliefLedgerSection(section)) continue;\n for (const fact of section.facts) {\n keys.add(normalizeEntityText(fact));\n }\n }\n return keys;\n}\ntype RecalledEntityFact = { text: string; sourceIndex: number };\nfunction recallFactsForStructuredSection(section: EntityStructuredSection): RecalledEntityFact[] {\n if (!isBeliefLedgerSection(section)) {\n return section.facts.map((text, sourceIndex) => ({ text, sourceIndex }));\n }\n return currentActiveBeliefLedgerFactTexts(section.facts);\n}\nfunction currentActiveBeliefLedgerFactTexts(facts: string[]): RecalledEntityFact[] {\n const byClaim = new Map<string, { status: string; updatedAtMs: number; texts: RecalledEntityFact[] }>();\n for (const [sourceIndex, fact] of facts.entries()) {\n const match = BELIEF_LEDGER_FACT_RE.exec(fact.trim());\n if (!match) continue;\n const [, claimId, status, updatedAt, text] = match;\n const updatedAtMs = Date.parse(updatedAt);\n if (!claimId?.trim() || !status?.trim() || !Number.isFinite(updatedAtMs) || !text?.trim()) continue;\n const normalizedStatus = status.trim().toLowerCase();\n const normalizedClaimId = claimId.trim();\n const current = byClaim.get(normalizedClaimId);\n const inactiveTieWins =\n current &&\n updatedAtMs === current.updatedAtMs &&\n current.status === \"active\" &&\n normalizedStatus !== \"active\";\n if (!current || updatedAtMs > current.updatedAtMs || inactiveTieWins) {\n byClaim.set(normalizedClaimId, { status: normalizedStatus, updatedAtMs, texts: [{ text: text.trim(), sourceIndex }] });\n continue;\n }\n if (updatedAtMs === current.updatedAtMs && current.status === normalizedStatus) {\n current.texts.push({ text: text.trim(), sourceIndex });\n }\n }\n return [...byClaim.values()].flatMap((current) => current.status === \"active\" ? current.texts : []);\n}\nfunction relationLine(entry: EntityMentionIndexEntry, relationship: { target: string; label: string }): string {\n const normalizedLabel = relationship.label.replace(/\\s+/g, \" \").trim();\n if (normalizedLabel.length === 0) return `${entry.name} is connected to ${relationship.target}`;\n return `${entry.name} ${normalizedLabel} ${relationship.target}`;\n}\nfunction scoreAliasMatch(query: string, alias: string): number {\n const normalizedQuery = normalizeEntityText(query);\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) return 0;\n if (normalizedQuery === normalizedAlias) return 10;\n if (containsPhrase(normalizedQuery, normalizedAlias)) return 8 + Math.min(normalizedAlias.split(/\\s+/).length, 3);\n const queryTokens = new Set(tokenize(normalizedQuery));\n const aliasTokens = tokenize(normalizedAlias);\n if (aliasTokens.length === 0) return 0;\n const overlap = aliasTokens.filter((token) => queryTokens.has(token)).length;\n if (overlap === 0) return 0;\n // Cross-entity contamination guard (#682 PR 2/3 R-2). For multi-token\n // aliases, partial-token overlap that hits ONLY shared common tokens\n // (like \"person\" in \"Person-A1\" / \"Person-B1\") would surface every\n // similarly-prefixed entity for a query that named only one. Require\n // that the overlap include at least one DISTINCTIVE alias token —\n // i.e. a token that does not also appear in any other entity's\n // alias-token vocabulary. Since this function is pure / per-pair, we\n // approximate \"distinctive\" by requiring the overlap to include at\n // least one token that is not a substring-of common identifier\n // affixes. The aliasTokens with length > 1 must contribute at least\n // one non-affix overlap. \"Alice Example\" ([\"alice\", \"example\"])\n // matched by query \"Tell me about Alice\" → overlap = 1 on \"alice\",\n // and \"alice\" is not an affix → score = 1. \"Person-A1\" tokens\n // [\"person\", \"a1\"] matched by query \"Who is Person-B1?\" → overlap =\n // 1 on \"person\", and \"person\" IS an affix → score = 0.\n if (aliasTokens.length > 1) {\n const nonAffixOverlap = aliasTokens.filter(\n (token) => queryTokens.has(token) && !isAliasAffixToken(token),\n ).length;\n if (nonAffixOverlap === 0) return 0;\n }\n return overlap;\n}\n/**\n * Tokens that look like type prefixes / generic role identifiers and\n * therefore should not, on their own, count as evidence that a\n * multi-token alias matches a query (#682 PR 2/3 R-2).\n *\n * Kept as a small explicit list rather than a regex so additions are\n * deliberate. The list mirrors the entity types listed in\n * `entity-schema.ts` plus the most common generic role identifiers\n * that frequently appear as the leading token of a display name.\n */\nconst ALIAS_AFFIX_TOKENS = new Set<string>([\n \"person\", \"people\", \"user\", \"users\", \"team\", \"teams\",\n \"project\", \"projects\", \"topic\", \"topics\",\n \"org\", \"orgs\", \"organization\", \"organizations\", \"company\", \"companies\",\n \"place\", \"places\", \"tool\", \"tools\", \"service\", \"services\",\n \"system\", \"systems\", \"agent\", \"agents\", \"bot\", \"bots\",\n]);\nfunction isAliasAffixToken(token: string): boolean {\n return ALIAS_AFFIX_TOKENS.has(token);\n}\nfunction isLikelyInstructionLike(value: string): boolean {\n return INSTRUCTION_LIKE_RE.test(value) || METADATA_WRAPPER_RE.test(value);\n}\nfunction sanitizeEntityFact(fact: string): string {\n const sanitized = sanitizeMemoryContent(fact);\n const clean = sanitized.text.trim();\n if (!clean) return \"\";\n if (INSTRUCTION_LIKE_RE.test(clean) && clean.length > 100) return \"\";\n return clean;\n}\nfunction scoreHintSnippet(snippet: EntityHintSnippet, queryTokens: string[]): EntityHintSnippet | null {\n const normalized = normalizeEntityText(snippet.text);\n if (!normalized) return null;\n const scored = { ...snippet };\n if (isLikelyInstructionLike(scored.text) && scored.kind !== \"summary\") {\n scored.score -= 3;\n }\n const overlap = queryTokens.filter((token) => normalized.includes(token)).length;\n scored.score += overlap * 2;\n if (METADATA_WRAPPER_RE.test(scored.text)) scored.score -= 2;\n if (scored.text.length <= 160) scored.score += 1;\n return scored.score > 0 ? scored : null;\n}\nfunction sortTimelineEntriesDesc(\n left: EntityMentionIndexEntry[\"timeline\"][number],\n right: EntityMentionIndexEntry[\"timeline\"][number],\n): number {\n const timestampOrder = compareEntityTimestamps(right.timestamp, left.timestamp);\n if (timestampOrder !== 0) {\n return timestampOrder;\n }\n return right.text.localeCompare(left.text);\n}\nfunction jaccardSimilarity(a: string, b: string): number {\n const aTokens = new Set(tokenize(a));\n const bTokens = new Set(tokenize(b));\n if (aTokens.size === 0 || bTokens.size === 0) return 0;\n let intersection = 0;\n for (const token of aTokens) {\n if (bTokens.has(token)) intersection += 1;\n }\n const union = new Set([...aTokens, ...bTokens]).size;\n return union === 0 ? 0 : intersection / union;\n}\nfunction buildAliasIndex(entries: EntityMentionIndexEntry[]): Map<string, EntityMentionIndexEntry[]> {\n const index = new Map<string, EntityMentionIndexEntry[]>();\n for (const entry of entries) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]).map(normalizeEntityText).filter(Boolean);\n for (const alias of aliases) {\n const existing = index.get(alias) ?? [];\n existing.push(entry);\n index.set(alias, existing);\n }\n }\n return index;\n}\nasync function readNativeChunks(\n config: PluginConfig,\n recallNamespaces?: string[],\n): Promise<NativeKnowledgeChunk[]> {\n if (!config.nativeKnowledge?.enabled) return [];\n return collectNativeKnowledgeChunks({\n workspaceDir: config.workspaceDir,\n memoryDir: config.memoryDir,\n config: config.nativeKnowledge,\n recallNamespaces: resolveNamespaceCapabilities(config).namespaces ? recallNamespaces : undefined,\n defaultNamespace: config.defaultNamespace,\n }).catch(() => []);\n}\nasync function resolveEntityIndexStorages(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<StorageManager[]> {\n if (\n !resolveNamespaceCapabilities(config).namespaces ||\n !namespaceStorage ||\n !recallNamespaces ||\n recallNamespaces.length === 0\n ) {\n return [storage];\n }\n const storages: StorageManager[] = [];\n const seenDirs = new Set<string>();\n for (const namespace of uniqueStrings(recallNamespaces)) {\n try {\n const scopedStorage = await namespaceStorage(namespace);\n const storageDir = path.resolve(scopedStorage.dir);\n if (seenDirs.has(storageDir)) continue;\n seenDirs.add(storageDir);\n storages.push(scopedStorage);\n } catch {\n continue;\n }\n }\n return storages.length > 0 ? storages : [storage];\n}\nfunction entityIndexStatePath(storage: StorageManager): string {\n return path.join(storage.dir, \"state\", \"entity-mention-index.json\");\n}\n\nasync function readEntityIndexState(storage: StorageManager): Promise<EntityMentionIndex | null> {\n const raw = await readFile(entityIndexStatePath(storage), \"utf-8\").catch(() => \"\");\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<EntityMentionIndex>;\n if (parsed.version !== ENTITY_INDEX_VERSION || !Array.isArray(parsed.entities)) return null;\n return parsed as EntityMentionIndex;\n } catch {\n return null;\n }\n}\nasync function readCurrentPersistedEntityIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<EntityMentionIndex | null> {\n if (\n resolveNamespaceCapabilities(config).namespaces &&\n namespaceStorage &&\n recallNamespaces &&\n recallNamespaces.length > 0\n ) {\n return null;\n }\n const index = await readEntityIndexState(storage);\n if (!index || index.entityStatusVersion !== storage.getMemoryStatusVersion()) {\n return null;\n }\n return index;\n}\nconst namespaceEntityIndexCache = new Map<string, EntityMentionIndex>();\nconst MAX_NAMESPACE_ENTITY_INDEX_CACHE_ENTRIES = 32;\n\nfunction nativeEntityIndexRevision(chunks: NativeKnowledgeChunk[]): string {\n const projection = chunks.map((chunk) => [\n chunk.chunkId,\n chunk.sourcePath,\n chunk.title,\n chunk.sourceKind,\n uniqueStrings(chunk.aliases ?? []),\n compactLine(chunk.content, 180),\n chunk.derivedDate ?? null,\n ]);\n return createHash(\"sha256\").update(JSON.stringify(projection)).digest(\"hex\");\n}\nfunction namespaceEntityIndexCacheKey(\n storages: StorageManager[],\n recallNamespaces: string[],\n nativeRevision: string,\n): string {\n const namespaceKey = uniqueStrings(recallNamespaces).join(\"\\u001f\");\n const storageKey = storages\n .map((scopedStorage) => {\n const aliases = Object.entries(scopedStorage.entityAliases)\n .sort(([left], [right]) => left.localeCompare(right));\n return (\n `${path.resolve(scopedStorage.dir)}@${scopedStorage.getMemoryStatusVersion()}` +\n `:${scopedStorage.getMemoryCorpusVersion()}:${scopedStorage.getEntityMutationVersion()}` +\n `:${scopedStorage.hotCacheKeyId()}:${JSON.stringify(aliases)}`\n );\n })\n .join(\"\\u001f\");\n return `${namespaceKey}\\u001e${storageKey}\\u001e${nativeRevision}`;\n}\nfunction rememberNamespaceEntityIndex(key: string, index: EntityMentionIndex): void {\n if (namespaceEntityIndexCache.size >= MAX_NAMESPACE_ENTITY_INDEX_CACHE_ENTRIES) {\n const oldestKey = namespaceEntityIndexCache.keys().next().value;\n if (typeof oldestKey === \"string\") namespaceEntityIndexCache.delete(oldestKey);\n }\n namespaceEntityIndexCache.set(key, index);\n}\n\nasync function writeEntityIndexState(storage: StorageManager, index: EntityMentionIndex): Promise<void> {\n const statePath = entityIndexStatePath(storage);\n await mkdir(path.dirname(statePath), { recursive: true });\n const nextContent = JSON.stringify(index, null, 2) + \"\\n\";\n const currentContent = await readFile(statePath, \"utf-8\").catch(() => \"\");\n if (currentContent === nextContent) return;\n await writeFile(statePath, nextContent, \"utf-8\");\n}\n\nfunction nativePseudoCanonicalId(chunk: NativeKnowledgeChunk): string {\n return `native:${createHash(\"sha256\").update(chunk.sourcePath).digest(\"hex\").slice(0, 12)}`;\n}\n\nfunction createPseudoNativeEntry(chunk: NativeKnowledgeChunk): EntityMentionIndexEntry {\n const canonicalId = nativePseudoCanonicalId(chunk);\n return {\n canonicalId,\n name: chunk.title,\n type: chunk.sourceKind,\n aliases: uniqueStrings(chunk.aliases ?? []),\n facts: [],\n structuredSections: [],\n timelineFacts: [],\n timeline: [],\n relationships: [],\n activity: [],\n factCount: 0,\n memorySnippets: [],\n nativeChunks: [\n {\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n },\n ],\n };\n}\n\nfunction mergeNativeChunk(entry: EntityMentionIndexEntry, chunk: NativeKnowledgeChunk): void {\n const existing = entry.nativeChunks.find((item) => item.chunkId === chunk.chunkId);\n if (existing) return;\n entry.nativeChunks.push({\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n });\n entry.aliases = uniqueStrings([...entry.aliases, ...(chunk.aliases ?? [])]);\n}\n\nfunction hasFreshNativeExplicitMention(\n index: EntityMentionIndex,\n nativeChunks: NativeKnowledgeChunk[],\n query: string,\n): boolean {\n if (nativeChunks.length === 0) return false;\n const nativeCanonicalIds = new Set(nativeChunks.map(nativePseudoCanonicalId));\n const freshNativeIndex: EntityMentionIndex = {\n ...index,\n entities: [\n ...index.entities.filter((entry) => !nativeCanonicalIds.has(entry.canonicalId)),\n ...nativeChunks.map(createPseudoNativeEntry),\n ],\n };\n return resolveLanguageIndependentExplicitCandidates(freshNativeIndex, query).length > 0;\n}\n\nasync function buildEntityMentionIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n nativeChunksOverride?: NativeKnowledgeChunk[],\n resolvedStorages?: StorageManager[],\n abortSignal?: AbortSignal,\n): Promise<EntityMentionIndex> {\n checkEntityRecallAbort(abortSignal);\n const storages = resolvedStorages ?? await resolveEntityIndexStorages(\n storage,\n config,\n recallNamespaces,\n namespaceStorage,\n );\n const shouldPersistIndex =\n storages.length === 1 && path.resolve(storages[0]!.dir) === path.resolve(storage.dir);\n const entityStatusVersionBefore = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const [previousIndex, entityFileSets, memorySets, nativeChunks] = await Promise.all([\n shouldPersistIndex ? readEntityIndexState(storage) : Promise.resolve(null),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllEntityFiles({ abortSignal }))),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllMemories({ abortSignal }))),\n nativeChunksOverride ? Promise.resolve(nativeChunksOverride) : readNativeChunks(config, recallNamespaces),\n ]);\n // The bulk reads now stop at their own scan boundaries (issue #2307); this\n // checkpoint still guards the (larger) indexing pass over their results.\n checkEntityRecallAbort(abortSignal);\n // Pair each entity with the storage that owns it (#1534): canonical ids must\n // reflect that store's aliases and historical migration mappings, never another\n // namespace's.\n const entityRecords = entityFileSets.flatMap((set, index) =>\n set.map((entity) => ({ entity, storage: storages[index]! })),\n );\n const memories = memorySets.flat();\n\n // The two passes over the corpus below never await real I/O, so without an\n // explicit yield they hold the event loop and no recall section deadline can\n // fire during them (issue #2291).\n let scanned = 0;\n const entities = new Map<string, EntityMentionIndexEntry>();\n for (const { entity, storage: entityStorage } of entityRecords) {\n scanned += 1;\n await yieldEntityRecallScanEvery(scanned, abortSignal);\n const canonicalId =\n typeof entityStorage.normalizeEntityName === \"function\"\n ? entityStorage.normalizeEntityName(entity.name, entity.type)\n : normalizeEntityName(entity.name, entity.type, entityStorage.entityAliases);\n const rawStructuredSections = entity.structuredSections ?? [];\n const rawBeliefLedgerFactKeys = beliefLedgerFactKeys(rawStructuredSections);\n const sanitizedFacts = entity.facts\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .filter((fact) => !rawBeliefLedgerFactKeys.has(normalizeEntityText(fact)))\n .map((fact) => compactLine(fact, 180));\n const { facts: timelineFacts, origins: timelineFactOrigins } = sanitizeOriginatedFacts(\n entity.timeline,\n sanitizeEntityFact,\n compactLine,\n true,\n );\n const structuredSections = buildOriginStructuredSections(\n rawStructuredSections,\n recallFactsForStructuredSection,\n sanitizeEntityFact,\n compactLine,\n );\n entities.set(canonicalId, {\n canonicalId,\n name: entity.name,\n type: entity.type,\n aliases: uniqueStrings(entity.aliases),\n summary: entity.synthesis?.trim() || entity.summary?.trim() || undefined,\n facts: sanitizedFacts,\n timelineFacts,\n ...(timelineFactOrigins.some((origin) => origin !== undefined) ? { timelineFactOrigins } : {}),\n structuredSections,\n timeline: entity.timeline.map((entry) => ({ ...entry })),\n relationships: entity.relationships.map((relationship) => ({ ...relationship })),\n activity: entity.activity.map((activity) => ({ ...activity })),\n factCount: sanitizedFacts.length,\n memorySnippets: [],\n nativeChunks: [],\n });\n }\n\n scanned = 0;\n for (const memory of memories) {\n scanned += 1;\n await yieldEntityRecallScanEvery(scanned, abortSignal);\n const entry = typeof memory.frontmatter.entityRef === \"string\" ? entities.get(memory.frontmatter.entityRef) : undefined;\n if (!entry) continue;\n const snippet = await readMemorySnippet(memory);\n if (entry.memorySnippets.includes(snippet)) continue;\n entry.memorySnippets.push(snippet);\n entry.memorySnippetOrigins = [...(entry.memorySnippetOrigins ?? []), memory.frontmatter.origin];\n }\n // Each remaining phase is another synchronous pass over the whole index\n // (alias map, native-chunk merge, sort, two full serializations). Yield between\n // them so a section deadline can fire between passes instead of only after all\n // of them (issue #2291).\n await yieldEntityRecallScan(abortSignal);\n const aliasIndex = buildAliasIndex([...entities.values()]);\n for (const chunk of nativeChunks) {\n const existingPseudo = entities.get(nativePseudoCanonicalId(chunk));\n if (existingPseudo) {\n mergeNativeChunk(existingPseudo, chunk);\n continue;\n }\n const candidateAliases = uniqueStrings([chunk.title, ...(chunk.aliases ?? [])]).map(normalizeEntityText).filter(Boolean);\n let matched = false;\n for (const alias of candidateAliases) {\n for (const entry of aliasIndex.get(alias) ?? []) {\n mergeNativeChunk(entry, chunk);\n matched = true;\n }\n }\n if (matched) continue;\n const pseudoEntry = createPseudoNativeEntry(chunk);\n entities.set(pseudoEntry.canonicalId, pseudoEntry);\n }\n\n await yieldEntityRecallScan(abortSignal);\n const sortedEntities = [...entities.values()].sort((left, right) => left.name.localeCompare(right.name));\n await yieldEntityRecallScan(abortSignal);\n const previousEntities = previousIndex ? JSON.stringify(previousIndex.entities) : \"\";\n await yieldEntityRecallScan(abortSignal);\n const nextEntities = JSON.stringify(sortedEntities);\n const entityStatusVersionAfter = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const canPersistIndex = shouldPersistIndex && entityStatusVersionBefore === entityStatusVersionAfter;\n const index: EntityMentionIndex = {\n version: ENTITY_INDEX_VERSION,\n updatedAt:\n previousIndex && previousEntities === nextEntities\n ? previousIndex.updatedAt\n : new Date().toISOString(),\n entityStatusVersion: canPersistIndex ? entityStatusVersionAfter : undefined,\n entities: sortedEntities,\n };\n if (canPersistIndex) {\n // A build the caller has abandoned must not leave a persisted index behind:\n // the write is I/O the timed-out recall no longer needs, and the next recall\n // is already competing for the same disk.\n checkEntityRecallAbort(abortSignal);\n await writeEntityIndexState(storage, index);\n }\n return index;\n}\n\nfunction resolveExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of aliases) {\n const score = scoreAliasMatch(query, alias);\n if (score > bestScore) {\n bestAlias = alias;\n bestScore = score;\n }\n }\n if (bestScore <= 0) continue;\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n return candidates.sort((left, right) => right.score - left.score);\n}\n\nconst EXPLICIT_ENTITY_MENTION_SCORE = 9;\n\nconst IMPLICIT_ENTITY_STOP_WORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"by\",\n \"can\",\n \"do\",\n \"for\",\n \"from\",\n \"has\",\n \"how\",\n \"i\",\n \"if\",\n \"in\",\n \"is\",\n \"it\",\n \"me\",\n \"my\",\n \"of\",\n \"on\",\n \"or\",\n \"the\",\n \"to\",\n \"was\",\n \"what\",\n \"when\",\n \"where\",\n \"who\",\n \"why\",\n \"with\",\n \"you\",\n \"your\",\n]);\n\nfunction isDistinctiveImplicitAlias(normalizedAlias: string): boolean {\n const tokens = normalizedAlias.split(/\\s+/).filter(Boolean);\n if (tokens.length > 1 && tokens.every((token) => IMPLICIT_ENTITY_STOP_WORDS.has(token))) return false;\n if (tokens.length !== 1) return true;\n const token = tokens[0]!;\n return Array.from(token).length > 1 && !IMPLICIT_ENTITY_STOP_WORDS.has(token);\n}\n\nfunction isShortLatinAlias(alias: string): boolean {\n return /^[A-Za-z]{2,3}$/.test(alias.trim());\n}\n\nfunction hasStrongShortLatinAliasMention(query: string, alias: string): boolean {\n const normalizedAlias = alias.trim();\n const titleCaseAlias = `${normalizedAlias[0]!.toUpperCase()}${normalizedAlias.slice(1).toLowerCase()}`;\n const forms = new Set([normalizedAlias, normalizedAlias.toUpperCase(), titleCaseAlias]);\n return [...forms].some((form) => {\n if (form === form.toLowerCase()) return false;\n const escaped = form.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(?:^|[^A-Za-z0-9])${escaped}(?:$|[^A-Za-z0-9])`).test(query);\n });\n}\n\nfunction resolveLanguageIndependentExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const canonicalIdsByAlias = new Map<string, Set<string>>();\n for (const entry of index.entities) {\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) continue;\n const canonicalIds = canonicalIdsByAlias.get(normalizedAlias) ?? new Set<string>();\n canonicalIds.add(entry.canonicalId);\n canonicalIdsByAlias.set(normalizedAlias, canonicalIds);\n }\n }\n\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n const score = scoreAliasMatch(query, alias);\n if (\n !normalizedAlias ||\n !isDistinctiveImplicitAlias(normalizedAlias) ||\n (isShortLatinAlias(alias) && !hasStrongShortLatinAliasMention(query, alias)) ||\n canonicalIdsByAlias.get(normalizedAlias)?.size !== 1 ||\n score < EXPLICIT_ENTITY_MENTION_SCORE ||\n score <= bestScore\n ) {\n continue;\n }\n bestAlias = alias;\n bestScore = score;\n }\n if (bestAlias) {\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n }\n\n return candidates.sort(\n (left, right) => right.score - left.score || left.entry.name.localeCompare(right.entry.name),\n );\n}\n\nfunction resolveRecentTurnCandidates(\n index: EntityMentionIndex,\n transcriptEntries: TranscriptEntry[],\n recentTurns: number,\n): EntityCandidate[] {\n if (recentTurns <= 0 || transcriptEntries.length === 0) return [];\n const recentEntries = transcriptEntries.slice(-recentTurns);\n const candidates = new Map<string, EntityCandidate>();\n for (let indexOffset = recentEntries.length - 1; indexOffset >= 0; indexOffset -= 1) {\n const turn = recentEntries[indexOffset];\n const recencyBoost = recentEntries.length - indexOffset;\n const roleWeight = turn.role === \"user\" ? 2 : turn.role === \"assistant\" ? -1 : 0;\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n for (const alias of aliases) {\n const score = scoreAliasMatch(turn.content, alias);\n if (score <= 0) continue;\n const current = candidates.get(entry.canonicalId);\n const weightedScore = score + Math.max(0, 6 - recencyBoost) + roleWeight;\n if (!current || weightedScore > current.score) {\n candidates.set(entry.canonicalId, {\n entry,\n alias,\n score: weightedScore,\n source: \"recent_turn\",\n });\n }\n }\n }\n }\n return [...candidates.values()].sort((left, right) => right.score - left.score);\n}\n\nasync function readMemorySnippet(memory: MemoryFile): Promise<string> {\n const content = memory.content.replace(/\\s+/g, \" \").trim();\n return compactLine(content, 180);\n}\n\nasync function buildHintSnippets(\n entry: EntityMentionIndexEntry,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxSupportingFacts: number,\n requestedSectionKeys: Set<string>,\n): Promise<EntityHintSnippet[]> {\n const snippets: EntityHintSnippet[] = [];\n const aliasTokens = new Set(tokenize(uniqueStrings([entry.name, ...entry.aliases]).join(\" \")));\n if (entry.summary) {\n snippets.push({ text: compactLine(entry.summary, 180), score: 10, kind: \"summary\" });\n }\n if (requestedSectionKeys.size > 0) {\n for (const section of entry.structuredSections) {\n if (!requestedSectionKeys.has(normalizeEntityText(section.key).replace(/\\s+/g, \"_\"))) continue;\n for (const [index, fact] of section.facts.entries()) {\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 8 : 9,\n kind: \"section\",\n origin: section.factOrigins?.[index],\n });\n }\n }\n } else {\n for (const [index, fact] of entry.timelineFacts.entries()) {\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 6 : 7,\n kind: \"fact\",\n origin: entry.timelineFactOrigins?.[index],\n });\n }\n for (const section of entry.structuredSections) {\n for (const [index, fact] of section.facts.entries()) {\n const normalizedFact = normalizeEntityText(fact);\n const hasNonAliasQueryOverlap = queryTokens.some((token) =>\n !aliasTokens.has(token) && normalizedFact.includes(token)\n );\n if (entry.timelineFacts.length > 0 && !hasNonAliasQueryOverlap) {\n continue;\n }\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 6 : 7,\n kind: \"fact\",\n origin: section.factOrigins?.[index],\n });\n }\n }\n if (entry.timelineFacts.length === 0 && entry.structuredSections.length === 0) {\n for (const fact of entry.facts) {\n if (!fact.trim()) continue;\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n }\n\n if (requestedSectionKeys.size === 0) {\n for (const relationship of entry.relationships) {\n snippets.push({\n text: compactLine(relationLine(entry, relationship), 180),\n score: mode === \"direct\" && entry.type.toLowerCase() === \"person\" ? 6 : 4,\n kind: \"relationship\",\n });\n }\n\n for (const activity of entry.activity) {\n snippets.push({\n text: compactLine(`${activity.date}: ${activity.note}`, 180),\n score: 4,\n kind: \"activity\",\n });\n }\n\n for (const [index, memorySnippet] of entry.memorySnippets.slice(0, Math.min(maxSupportingFacts, 4)).entries()) {\n snippets.push({ text: memorySnippet, score: 5, kind: \"memory\", origin: entry.memorySnippetOrigins?.[index] });\n }\n\n for (const chunk of entry.nativeChunks) {\n snippets.push({\n text: compactLine(chunk.snippet, 180),\n score: 3,\n kind: \"native\",\n });\n }\n }\n\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const scored = scoreHintSnippet(snippet, queryTokens);\n if (!scored) continue;\n const normalized = normalizeEntityText(scored.text);\n const existing = deduped.get(normalized);\n if (!existing) {\n deduped.set(normalized, scored);\n } else if (existing.origin !== scored.origin) {\n deduped.set(normalized, { ...(scored.score > existing.score ? scored : existing), origin: undefined });\n } else if (scored.score > existing.score) {\n deduped.set(normalized, scored);\n }\n }\n\n return [...deduped.values()]\n .filter((snippet) => snippet.score > 0)\n .sort((left, right) => right.score - left.score)\n .slice(0, maxSupportingFacts);\n}\n\nfunction summarizeUncertainty(snippets: EntityHintSnippet[]): string | null {\n const direct = snippets.filter((snippet) =>\n snippet.kind === \"summary\"\n || snippet.kind === \"fact\"\n || snippet.kind === \"section\"\n || snippet.kind === \"memory\"\n );\n if (direct.length < 2) return null;\n for (let index = 0; index < direct.length; index += 1) {\n for (let compare = index + 1; compare < direct.length; compare += 1) {\n if (jaccardSimilarity(direct[index].text, direct[compare].text) < 0.2) {\n return \"Evidence is mixed across stored facts; treat the hints below as partial and verify before answering definitively.\";\n }\n }\n }\n return null;\n}\n\nfunction formatEntityHintSection(\n candidates: Array<{\n candidate: EntityCandidate;\n snippets: EntityHintSnippet[];\n uncertainty: string | null;\n }>,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxRelatedEntities: number,\n maxChars: number,\n originAuthorityEnabled: boolean, untrustedOrigins: readonly string[],\n): string | null {\n if (candidates.length === 0) return null;\n const lines: string[] = [\"## entity_answer_hints\", \"\"];\n // #1955 review: non-native snippet kinds may embed extraction-written content\n // without per-field origin — fence as unknown (least privilege; plumbing #2397).\n const renderSnippet = (snippet: EntityHintSnippet): string => snippet.kind !== \"native\"\n ? renderAuthorityBoundContent(snippet.text, snippet.origin, { enabled: originAuthorityEnabled, untrustedOrigins }) : snippet.text;\n // (see comment above)\n // #1955 review: inline fields (names/types/aliases/targets) cannot carry the\n // multi-line block fence without collapsing the hint list structure —\n // per-field origin plumbing is tracked in #2397.\n for (const { candidate, snippets, uncertainty } of candidates) {\n const hasSummary = Boolean(candidate.entry.summary?.trim());\n const preferredTopSnippets = hasSummary\n ? snippets.filter((snippet) => snippet.kind !== \"fact\")\n : snippets;\n let topSnippets = (\n preferredTopSnippets.length > 0 ? preferredTopSnippets : snippets\n ).slice(0, 3);\n const buildTimelineSnippets = (seedExcludedTexts: Set<string>): EntityHintSnippet[] => {\n const explicitTimelinePool = dedupeHintSnippetsByText(\n (candidate.entry.timeline ?? [])\n .slice()\n .sort(sortTimelineEntriesDesc)\n .map((entry) => {\n const text = sanitizeEntityFact(entry.text);\n return text\n ? scoreHintSnippet({\n text: compactLine(text, 180),\n score: 7,\n kind: \"activity\" as const,\n origin: entry.origin,\n }, queryTokens)\n : null;\n })\n .filter((snippet): snippet is EntityHintSnippet => snippet !== null)\n .filter((snippet) => !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n const activityTimelinePool = dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"activity\" || snippet.kind === \"memory\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n return explicitTimelinePool.length > 0\n ? explicitTimelinePool\n : activityTimelinePool.length > 0\n ? activityTimelinePool\n : dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"fact\" || snippet.kind === \"summary\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n };\n const baseTopSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n const timelinePool = mode !== \"direct\" ? buildTimelineSnippets(baseTopSnippetTexts) : [];\n if (mode !== \"direct\" && hasSummary && topSnippets.length < 2) {\n if (timelinePool.length > 0) {\n topSnippets = [...topSnippets, timelinePool[0]!].slice(0, 3);\n }\n }\n const topSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n lines.push(`- target: ${candidate.entry.name} (${candidate.entry.type})`);\n lines.push(`- resolution: ${candidate.source === \"recent_turn\" ? \"carried forward from recent turns via alias\" : \"matched alias\"} \"${candidate.alias}\"${candidate.source === \"recent_turn\" ? \"\" : \" in the query\"}`);\n if (uncertainty) lines.push(`- uncertainty: ${uncertainty}`);\n if (topSnippets.length > 0) {\n lines.push(\"- likely answer:\");\n for (const snippet of topSnippets) {\n lines.push(` - ${renderSnippet(snippet)}`);\n }\n }\n if (mode !== \"direct\") {\n const fallbackTimeline = timelinePool.filter(\n (snippet) => !topSnippetTexts.has(normalizeEntityText(snippet.text)),\n );\n if (fallbackTimeline.length > 0) {\n lines.push(\"- recent timeline:\");\n for (const snippet of fallbackTimeline) {\n lines.push(` - ${renderSnippet(snippet)}`);\n }\n }\n }\n const related = candidate.entry.relationships.slice(0, maxRelatedEntities).map((relationship) => relationship.target);\n if (related.length > 0) {\n lines.push(`- related entities: ${related.join(\", \")}`);\n }\n lines.push(`- support counts: facts=${candidate.entry.factCount}, memories=${candidate.entry.memorySnippets.length}, native=${candidate.entry.nativeChunks.length}`);\n lines.push(\"\");\n }\n\n let result = lines.join(\"\\n\");\n if (result.length > maxChars) {\n result = `${truncateGraphemeSafe(result, Math.max(0, maxChars - 15)).trimEnd()}\\n\\n...(trimmed)\\n`;\n }\n return result.trim().length > 0 ? result.trimEnd() : null;\n}\n\nexport async function buildEntityRecallSection(options: BuildEntityRecallSectionOptions): Promise<string | null> {\n // Checkpoints sit at the real I/O boundaries below (persisted-index read,\n // native-chunk read, storage resolution, index build). The per-candidate\n // formatting that follows never awaits real I/O, so a deadline that fires\n // during a scan is observed here (issue #2291).\n checkEntityRecallAbort(options.abortSignal);\n const prefixedMode = detectEntityQueryMode(options.query);\n // #2193: in zero-pronoun scripts a short question with no entity name\n // never trips a pronoun word list, so the structural signal routes it\n // into the same coreference path as an English \"what about him?\".\n // Latin-script queries stay on the cue tables / English rules so the\n // generic technical-question guard keeps working. Resolution gates.\n const structuralFollowUp = prefixedMode === null\n && isStructuralEntityFollowUpQuery(\n options.query,\n options.recentTurns > 0 && options.transcriptEntries.length > 0,\n );\n const earlyMode = prefixedMode ?? (structuralFollowUp ? \"follow_up\" : null);\n const persistedIndex = earlyMode\n ? null\n : await readCurrentPersistedEntityIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n );\n checkEntityRecallAbort(options.abortSignal);\n let nativeChunks: NativeKnowledgeChunk[] | undefined;\n if (\n !earlyMode &&\n persistedIndex &&\n resolveLanguageIndependentExplicitCandidates(persistedIndex, options.query).length === 0\n ) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces);\n if (!hasFreshNativeExplicitMention(persistedIndex, nativeChunks, options.query)) {\n return entityRecallSectionAbsent(options.abortSignal);\n }\n }\n const namespaceScoped =\n resolveNamespaceCapabilities(options.config).namespaces &&\n options.namespaceStorage !== undefined &&\n (options.recallNamespaces?.length ?? 0) > 0;\n if (namespaceScoped) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces);\n }\n const resolvedStorages = namespaceScoped\n ? await resolveEntityIndexStorages(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n )\n : undefined;\n const namespaceCacheKey =\n resolvedStorages && options.recallNamespaces && nativeChunks\n ? namespaceEntityIndexCacheKey(\n resolvedStorages,\n options.recallNamespaces,\n nativeEntityIndexRevision(nativeChunks),\n )\n : undefined;\n let index: EntityMentionIndex | undefined = namespaceCacheKey\n ? namespaceEntityIndexCache.get(namespaceCacheKey)\n : undefined;\n checkEntityRecallAbort(options.abortSignal);\n if (!index) {\n index = await buildEntityMentionIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n nativeChunks,\n resolvedStorages,\n options.abortSignal,\n );\n if (namespaceCacheKey) rememberNamespaceEntityIndex(namespaceCacheKey, index);\n }\n // Candidate resolution is another synchronous pass over every entity and alias,\n // reached even on a cache hit that did no I/O at all — so yield here too, or a\n // cached corpus could still hold the loop past the section budget (issue #2291).\n await yieldEntityRecallScan(options.abortSignal);\n const explicitCandidates = resolveExplicitCandidates(index, options.query);\n await yieldEntityRecallScan(options.abortSignal);\n const queryCandidates = prefixedMode\n ? explicitCandidates\n : resolveLanguageIndependentExplicitCandidates(index, options.query);\n if (\n queryCandidates.length === 0\n && /^what does (?:this|that|it|the|a|an|my|our|your|their)\\b/i.test(normalizeEntityText(options.query))\n ) {\n return entityRecallSectionAbsent(options.abortSignal);\n }\n\n // Explicit mentions keep #2161 behavior (direct mode) even when the\n // structural follow-up signal also fired; only name-less short questions\n // fall through to coreference.\n const mode = prefixedMode\n ?? (queryCandidates.length > 0\n ? \"direct\"\n : structuralFollowUp\n ? \"follow_up\"\n : null);\n if (!mode) return entityRecallSectionAbsent(options.abortSignal);\n\n const candidates = queryCandidates.length > 0\n ? queryCandidates\n : resolveRecentTurnCandidates(index, options.transcriptEntries, options.recentTurns);\n\n if (candidates.length === 0) return entityRecallSectionAbsent(options.abortSignal);\n\n const queryTokens = tokenize(options.query);\n const candidateLimit = queryCandidates.length === 0 && mode === \"follow_up\"\n ? 1\n : options.maxHints;\n const rankedCandidates = candidates.slice(0, candidateLimit);\n const enriched = await Promise.all(\n rankedCandidates.map(async (candidate) => {\n const requestedSectionKeys = new Set(\n resolveRequestedEntitySectionKeys(\n options.query,\n candidate.entry.type,\n candidate.entry.structuredSections,\n options.config.entitySchemas,\n ),\n );\n const snippets = await buildHintSnippets(\n candidate.entry,\n queryTokens,\n mode,\n options.maxSupportingFacts,\n requestedSectionKeys,\n );\n return {\n candidate,\n snippets,\n uncertainty: summarizeUncertainty(snippets),\n };\n }),\n );\n\n const section = formatEntityHintSection(\n enriched,\n queryTokens,\n mode,\n options.maxRelatedEntities,\n options.maxChars,\n options.originAuthorityEnabled === true,\n options.untrustedOrigins ?? [],\n );\n // `entityRecallSectionAbsent` so a cancelled build is not recorded as a\n // successful section that simply found no entities.\n if (!section) return entityRecallSectionAbsent(options.abortSignal);\n return section;\n}\n\nexport async function readRecentEntityTranscriptEntries(\n transcriptEntriesPromise: Promise<TranscriptEntry[]>,\n recentTurns: number,\n): Promise<TranscriptEntry[]> {\n if (recentTurns <= 0) return [];\n const transcriptEntries = await transcriptEntriesPromise.catch(() => []);\n if (transcriptEntries.length === 0) return [];\n return transcriptEntries.slice(-Math.max(1, recentTurns * 2));\n}\n\nexport const entityIndexVersion = ENTITY_INDEX_VERSION;\nexport const entityRecentTranscriptLookbackHours = RECENT_TRANSCRIPT_LOOKBACK_HOURS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,kBAAkB;AAE3B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