dsh-memu-memory 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
package/lib/graph.js CHANGED
@@ -1,1193 +1,1193 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
- import { indexDir, readJsonStrict, writeJson, withFileLock, stamp, warn } from './paths.js'
4
- import { loadPrivateIndex, updatePrivateIndex, newMemoryId, listLibraries } from './state.js'
5
- import { resolveLibrary, sessionIdOf, visibleToSession, isMemoryEligible, decayStrength } from './memory.js'
6
- import { record } from './activity-log.js'
7
- // Entity merge suggestions reuse the exact folding rule auto-linking already
8
- // uses (NFKC / case / whitespace / punctuation). This is a deliberate module
9
- // cycle: private-links.js imports the entity writers from here, but both sides
10
- // only touch each other's bindings in function bodies, and ESM hoists the
11
- // function declarations before either module body runs.
12
- import { normalizeEntityName } from './private-links.js'
13
- import { refreshEntityMentions } from './auto-link/apply.js'
14
- import { addSuppression, suppressionSet } from './auto-link/suppression.js'
15
- import { ENTITY_STATUS } from './auto-link/policy.js'
16
-
17
- export const LINK_KINDS = ['relation', 'commitment', 'event', 'person', 'conflict', 'supersede']
18
- const ENTITY_KINDS = ['person', 'place', 'thing', 'org']
19
- // Relationship revisions are audit history, not an ever-growing data store. A
20
- // long-lived role-play can update one relation hundreds of times; keeping all of
21
- // it made every recall re-parse a multi-MB sidecar. The current state and its
22
- // evidence stay intact; only the old snapshots are capped.
23
- const RELATIONSHIP_HISTORY_LIMIT = 50
24
- // Relationship retention is metadata, not structure: the edge stays, only its
25
- // confidence in the sidebar/recall can fade, freeze or revive. Parameters follow
26
- // the local, wall-clock policy used by the audit comparison; no LLM, no text.
27
- const RELATIONSHIP_HALF_LIFE_HOURS = 24
28
- const RELATIONSHIP_ACCESS_ALPHA = 0.05
29
- const RELATIONSHIP_ACCESS_COOLDOWN_MS = 3_600_000
30
-
31
- function hoursBetween(from, to) {
32
- const start = Date.parse(String(from || ''))
33
- const end = Date.parse(String(to || ''))
34
- if (!Number.isFinite(start) || !Number.isFinite(end)) return 0
35
- return Math.max(0, (end - start) / 3_600_000)
36
- }
37
-
38
- /** Exponential retention at a wall-clock instant; clock rollback never boosts it. */
39
- export function relationshipRetentionAt(strength, elapsedHours, halfLifeHours = RELATIONSHIP_HALF_LIFE_HOURS) {
40
- const base = Number(strength)
41
- const hours = Number(elapsedHours)
42
- const halfLife = Number(halfLifeHours)
43
- if (!Number.isFinite(base) || base <= 0) return 0
44
- if (!Number.isFinite(hours) || hours <= 0 || !Number.isFinite(halfLife) || halfLife <= 0) return Math.min(1, base)
45
- return Math.min(1, base * Math.pow(0.5, hours / halfLife))
46
- }
47
-
48
- /** A recall/access reinforces without jumping to 1. */
49
- export function accessRelationship(strength, { cooldownMs = RELATIONSHIP_ACCESS_COOLDOWN_MS, lastAccessAt = null, now = Date.now() } = {}) {
50
- const base = Math.min(1, Math.max(0, Number(strength) || 0))
51
- const last = Date.parse(String(lastAccessAt || ''))
52
- if (Number.isFinite(last) && Number(now) - last < cooldownMs) return base
53
- return Math.min(1, base + (1 - base) * RELATIONSHIP_ACCESS_ALPHA)
54
- }
55
-
56
- function entitiesPath(libraryId) { return path.join(indexDir(), `${libraryId}.entities.json`) }
57
-
58
- function readEntities(libraryId) {
59
- const result = readJsonStrict(entitiesPath(libraryId))
60
- if (result.ok) {
61
- if (!result.value?.entities || typeof result.value.entities !== 'object' || Array.isArray(result.value.entities)) throw new Error('invalid entity store')
62
- return { relationships: {}, ...result.value }
63
- }
64
- if (result.missing) return { version: 1, entities: {}, relationships: {} }
65
- throw new Error(`cannot read entity store: ${result.error?.message || 'invalid data'}`)
66
- }
67
-
68
- function scopeFor(args) { return resolveLibrary({ ...args, readOnly: true }) }
69
- function allowed(entry, exec) {
70
- return !sessionIdOf(exec) || (isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, sessionIdOf(exec)))
71
- }
72
-
73
- /**
74
- * Entity listing with the derived `linked` flag (§6.4 包 D). The visibility rule
75
- * is unchanged: without a session every entity comes back (GraphPanel calls it
76
- * exactly that way), with a session only entities reachable from visible memory
77
- * links are listed. What is new is the classification:
78
- * * `linked` = referenced by an entry's links[] OR by a relationship snapshot.
79
- * A snapshot counts — an entity with only a relationship and no memory link
80
- * is history, not an orphan, and must not be misjudged as one.
81
- * * With a session, a snapshot only counts when its evidenceIds include a
82
- * memory visible in this conversation; without a session every snapshot
83
- * counts (there is nobody to hide it from).
84
- * `linked` is derived on the fly and never written back to the entities file —
85
- * the startup prune (pruneOrphanEntitiesAll) stays the sole collector.
86
- */
87
- export function listEntities(args) {
88
- const scope = scopeFor(args)
89
- const store = readEntities(scope.libraryId)
90
- const index = loadPrivateIndex(scope.libraryId)
91
- const sessionId = sessionIdOf(args.exec)
92
- const linked = new Set()
93
- for (const entry of Object.values(index.entries)) {
94
- if (!allowed(entry, args.exec)) continue
95
- for (const link of entry.links || []) linked.add(link.to)
96
- }
97
- for (const rel of Object.values(store.relationships || {})) {
98
- if (sessionId) {
99
- const evidenceVisible = (Array.isArray(rel?.evidenceIds) ? rel.evidenceIds : [])
100
- .some(id => { const entry = index.entries[id]; return Boolean(entry) && allowed(entry, args.exec) })
101
- if (!evidenceVisible) continue
102
- }
103
- if (rel?.fromId) linked.add(rel.fromId)
104
- if (rel?.toId) linked.add(rel.toId)
105
- }
106
- const items = Object.values(store.entities)
107
- .filter(entity => !sessionId || linked.has(entity.id))
108
- .map(entity => ({
109
- ...entity,
110
- // Legacy rows have no status; they read as provisional, never confirmed.
111
- status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional',
112
- linked: linked.has(entity.id),
113
- }))
114
- return { items, total: items.length }
115
- }
116
-
117
- export function graphExport(libraryId) {
118
- const scope = scopeFor({ libraryId })
119
- return readEntities(scope.libraryId)
120
- }
121
-
122
- /**
123
- * Rebuild the entity/relationship store a memory package came with.
124
- *
125
- * Returns the ids of entities this call actually created, tagged with `origin` (the
126
- * import batch). A revert needs that list: it is the difference between "remove what
127
- * the package brought" and "remove a person the user already knew".
128
- */
129
- export function restoreGraphData(libraryId, data, memoryIdMap, { origin = null } = {}) {
130
- if (!data?.entities) return { createdEntityIds: [] }
131
- const scope = scopeFor({ libraryId })
132
- const entityMap = {}
133
- const createdEntityIds = []
134
- for (const [oldId, entity] of Object.entries(data.entities).slice(0, 2000)) {
135
- if (!/^ent[-_][a-z0-9_-]+$/i.test(oldId)) continue
136
- // An import is a user action: rows without a status come back confirmed, and
137
- // an explicit status travels with the backup unchanged.
138
- const restored = createEntity({
139
- libraryId: scope.libraryId, name: entity.name, kind: entity.kind, aliases: entity.aliases || [], origin,
140
- status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'confirmed',
141
- confirmedBy: entity.confirmedBy || 'user',
142
- })
143
- entityMap[oldId] = restored.id
144
- if (origin && restored.origin === origin) createdEntityIds.push(restored.id)
145
- }
146
- const remap = { ...entityMap, ...memoryIdMap }
147
- updatePrivateIndex(libraryId, index => {
148
- for (const id of Object.values(memoryIdMap)) {
149
- const entry = index.entries[id]
150
- if (!entry) continue
151
- entry.links = (entry.links || []).map(link => ({ ...link, to: remap[link.to] || link.to }))
152
- }
153
- })
154
- for (const relationship of Object.values(data.relationships || {})) {
155
- if (!entityMap[relationship.fromId] || !entityMap[relationship.toId]) continue
156
- const evidenceIds = (relationship.evidenceIds || []).map(id => memoryIdMap[id]).filter(Boolean)
157
- if (!evidenceIds.length) continue
158
- updateRelationship({ libraryId, fromId: entityMap[relationship.fromId], toId: entityMap[relationship.toId], state: relationship.state, evidenceIds, reason: relationship.reason || 'Imported relationship with explicit evidence.' })
159
- }
160
- // A backup carries the whole entity store, but only the memories that made it
161
- // through the export/import mapping come back, so entities nothing points at
162
- // any more would sit in the file forever as invisible weight. Collect them
163
- // once the remap is done; a prune failure must not fail a restore that
164
- // already succeeded, and the startup sweep would catch it on the next launch.
165
- try {
166
- pruneOrphanEntities(scope.libraryId)
167
- } catch (error) {
168
- warn(`orphan entity prune after graph restore skipped: ${error?.message || error}`)
169
- }
170
- return { createdEntityIds }
171
- }
172
-
173
- /**
174
- * Undo `restoreGraphData` for one import batch: delete exactly the entities that call
175
- * created. Relationships hang off those entities, so `deleteEntity` cascades them; an
176
- * entity the user already had is untagged and therefore untouched. A failure is
177
- * reported per id rather than thrown, because a revert that removed the memories has
178
- * already done its job and half a graph is still better than an exception the caller
179
- * cannot act on.
180
- */
181
- export function revertGraphData({ libraryId, entityIds = [] }) {
182
- const removed = []
183
- const failed = []
184
- for (const entityId of entityIds) {
185
- try {
186
- deleteEntity({ libraryId, entityId, force: true })
187
- removed.push(entityId)
188
- } catch (error) {
189
- failed.push({ entityId, error: String(error?.message || error) })
190
- }
191
- }
192
- return { removed, failed }
193
- }
194
-
195
- /**
196
- * `origin` tags an entity that somebody else created on this user's behalf — an
197
- * imported memory package, say. It exists so the import can be undone: an entity
198
- * that already existed before the import is returned as-is and stays untagged, so a
199
- * revert can never delete a person the user had added themselves.
200
- *
201
- * `status` is the auto-link assertion state (DESIGN §6.1). The default is
202
- * `provisional`: creation alone never proves a name is real, so a new row
203
- * produces no mention edges until a user / agent / worker confirms it. Explicit
204
- * creation paths (UI, import) pass `confirmed`; worker tools keep provisional
205
- * and let the review queue decide.
206
- */
207
- export function createEntity({ exec, libraryId, name, kind = 'person', aliases = [], origin = null, status = 'provisional', confirmedBy = null }) {
208
- const scope = scopeFor({ exec, libraryId })
209
- if (!ENTITY_KINDS.includes(kind)) throw new Error(`entity kind must be ${ENTITY_KINDS.join(', ')}`)
210
- if (!ENTITY_STATUS.includes(status)) throw new Error(`entity status must be ${ENTITY_STATUS.join(', ')}`)
211
- const clean = String(name || '').trim()
212
- if (!clean || clean.length > 120) throw new Error('entity name must contain 1-120 characters')
213
- const file = entitiesPath(scope.libraryId)
214
- return withFileLock(file, () => {
215
- const store = readEntities(scope.libraryId)
216
- const existing = Object.values(store.entities).find(entity => entity.name === clean && entity.kind === kind)
217
- if (existing) return existing
218
- const id = newMemoryId('ent')
219
- const at = stamp()
220
- const entity = {
221
- id, name: clean, kind, aliases: normalizeAliases(aliases), status,
222
- createdAt: at, updatedAt: at,
223
- ...(origin ? { origin: String(origin) } : {}),
224
- ...(status === 'confirmed' ? { confirmedAt: at, confirmedBy: String(confirmedBy || 'user') } : {}),
225
- }
226
- store.entities[id] = entity
227
- writeJson(file, store)
228
- return entity
229
- })
230
- }
231
-
232
- /**
233
- * Explicit confirmation is the only way an entity becomes `confirmed`. The write
234
- * is followed by one incremental mention pass for that entity, so existing
235
- * memories gain their edges immediately instead of waiting for the next
236
- * consolidation.
237
- */
238
- export function confirmEntities({ exec, libraryId, entityIds, by = 'user' }) {
239
- const scope = scopeFor({ exec, libraryId })
240
- const ids = [...new Set((Array.isArray(entityIds) ? entityIds : []).map(id => String(id || '').trim()).filter(Boolean))]
241
- if (!ids.length) throw new Error('entityIds must name at least one entity')
242
- if (!['user', 'agent', 'worker'].includes(by)) throw new Error('confirmation actor must be user, agent or worker')
243
- const file = entitiesPath(scope.libraryId)
244
- const confirmed = []
245
- // Already-confirmed rows are refreshed too: if they were confirmed while the
246
- // mode was 'off', status changed but no edge was written. Re-confirming (or the
247
- // deterministic switch below) must be able to backfill, idempotently.
248
- const refreshTargets = []
249
- withFileLock(file, () => {
250
- const store = readEntities(scope.libraryId)
251
- const at = stamp()
252
- for (const id of ids) {
253
- const entity = store.entities[id]
254
- if (!entity || typeof entity !== 'object') throw new Error(`unknown entity: ${id}`)
255
- if (entity.status === 'archived') continue
256
- if (entity.status === 'confirmed') { refreshTargets.push(entity); continue }
257
- entity.status = 'confirmed'
258
- entity.origin = by
259
- entity.confirmedAt = at
260
- entity.confirmedBy = by
261
- entity.updatedAt = at
262
- confirmed.push(entity)
263
- refreshTargets.push(entity)
264
- }
265
- if (confirmed.length) writeJson(file, store)
266
- })
267
- let suppression = null
268
- try { suppression = suppressionSet(scope.libraryId) } catch {}
269
- let entities = 0
270
- for (const entity of refreshTargets) {
271
- try {
272
- const result = refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression })
273
- entities += result.added + result.updated
274
- } catch (error) {
275
- warn(`mention refresh after entity confirmation skipped: ${error?.message || error}`)
276
- }
277
- }
278
- return { confirmed: confirmed.map(entity => entity.id), skipped: ids.length - confirmed.length, entities }
279
- }
280
-
281
- /**
282
- * One-time grading of pre-status entity rows (DESIGN §9.3). It never confirms on
283
- * statistical evidence: an old row is `confirmed` only when somebody had already
284
- * asserted it (origin user/agent/worker, or a non-auto link points at it), and
285
- * everything else becomes `provisional`. Callers pass `apply:false` for dry runs.
286
- */
287
- export function gradeLegacyEntities({ libraryId, apply = false } = {}) {
288
- const scope = scopeFor({ libraryId })
289
- const file = entitiesPath(scope.libraryId)
290
- return withFileLock(file, () => {
291
- const store = readEntities(scope.libraryId)
292
- const asserted = new Set()
293
- try {
294
- for (const entry of Object.values(loadPrivateIndex(scope.libraryId).entries || {})) {
295
- for (const link of entry.links || []) {
296
- if (link?.to && link.source !== 'auto') asserted.add(link.to)
297
- }
298
- }
299
- } catch {}
300
- const result = { scanned: 0, changed: 0, provisional: 0, confirmed: 0, applied: apply === true }
301
- const at = stamp()
302
- for (const entity of Object.values(store.entities || {})) {
303
- result.scanned += 1
304
- if (!ENTITY_STATUS.includes(entity.status)) {
305
- const protectedRow = ['user', 'agent', 'worker'].includes(entity.origin) || asserted.has(entity.id)
306
- const status = protectedRow ? 'confirmed' : 'provisional'
307
- result[status] += 1
308
- if (apply) {
309
- entity.status = status
310
- if (status === 'confirmed') {
311
- entity.confirmedAt = entity.confirmedAt || at
312
- entity.confirmedBy = entity.confirmedBy || (['user', 'agent', 'worker'].includes(entity.origin) ? entity.origin : 'user')
313
- }
314
- entity.updatedAt = at
315
- result.changed += 1
316
- }
317
- continue
318
- }
319
- if (entity.status === 'confirmed') result.confirmed += 1
320
- if (entity.status === 'provisional') result.provisional += 1
321
- }
322
- if (apply && result.changed) writeJson(file, store)
323
- return result
324
- })
325
- }
326
-
327
- function normalizeAliases(aliases) {
328
- if (!Array.isArray(aliases) || aliases.some(alias => typeof alias !== 'string')) throw new Error('aliases must be an array of strings')
329
- return [...new Set(aliases.map(alias => alias.trim()).filter(Boolean))].slice(0, 30).map(alias => alias.slice(0, 120))
330
- }
331
-
332
- export function renameEntity({ libraryId, entityId, name, aliases = [] }) {
333
- const scope = scopeFor({ libraryId })
334
- const clean = String(name || '').trim()
335
- if (!clean || clean.length > 120) throw new Error('entity name must contain 1-120 characters')
336
- const file = entitiesPath(scope.libraryId)
337
- const entity = withFileLock(file, () => {
338
- const store = readEntities(scope.libraryId)
339
- const row = store.entities[entityId]
340
- if (!row) throw new Error('unknown entity')
341
- row.name = clean
342
- row.aliases = normalizeAliases(aliases)
343
- row.updatedAt = stamp()
344
- writeJson(file, store)
345
- return row
346
- })
347
- // A confirmed entity's mention edges cite surfaces by name; rename/alias edits
348
- // must collect the stale ones and attach the new ones immediately.
349
- if (entity.status === 'confirmed') {
350
- let suppression = null
351
- try { suppression = suppressionSet(scope.libraryId) } catch {}
352
- try {
353
- refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression, operation: 'auto-link-rename' })
354
- } catch (error) {
355
- warn(`mention refresh after entity rename skipped: ${error?.message || error}`)
356
- }
357
- }
358
- return entity
359
- }
360
-
361
- // What keeps an entity alive. Edges only live in one direction: an entry's
362
- // links[] names the entity, the entity stores nothing back. On top of that,
363
- // relationship snapshots (same file, keyed by the endpoint pair) describe the
364
- // pair with history and evidence that outlive the individual entries — deleting
365
- // an endpoint would leave a snapshot whose endpoints no longer resolve, so a
366
- // snapshot counts as a reference too. An entity referenced by neither is an
367
- // *orphan*: unreachable except as a graph placeholder, and safe to collect.
368
- // Orphans come from old builds whose permanent delete dropped the memory row
369
- // without cascading, and from partial backups.
370
-
371
- /**
372
- * Remove every entity in one library that no entry links to and no relationship
373
- * snapshot references. Idempotent: on healthy data it writes nothing. Returns
374
- * `{ removed, total }` with the removed entity ids.
375
- *
376
- * `keep` names ids that must survive even while unreferenced — a merge passes
377
- * its target, because folding sources into a row and then collecting that row
378
- * would silently undo the merge when the pair had no edges yet.
379
- */
380
- export function pruneOrphanEntities(libraryId, keep = []) {
381
- const scope = scopeFor({ libraryId })
382
- const file = entitiesPath(scope.libraryId)
383
- const protectedIds = new Set(Array.isArray(keep) ? keep : [])
384
- return withFileLock(file, () => {
385
- const store = readEntities(scope.libraryId)
386
- const ids = Object.keys(store.entities)
387
- if (!ids.length) return { removed: [], total: 0 }
388
- const referenced = new Set()
389
- for (const entry of Object.values(loadPrivateIndex(scope.libraryId).entries || {})) {
390
- for (const link of entry.links || []) referenced.add(link.to)
391
- }
392
- for (const relationship of Object.values(store.relationships || {})) {
393
- referenced.add(relationship.fromId)
394
- referenced.add(relationship.toId)
395
- }
396
- const removed = ids.filter(id => !referenced.has(id) && !protectedIds.has(id))
397
- // Write only when something actually goes, so the common case never touches
398
- // the file (mtime-based caches, backups and concurrent readers all benefit).
399
- if (removed.length) {
400
- for (const id of removed) delete store.entities[id]
401
- writeJson(file, store)
402
- }
403
- return { removed, total: ids.length }
404
- })
405
- }
406
-
407
- /**
408
- * The startup sweep: run pruneOrphanEntities over every active library. One
409
- * corrupt store must not stop the rest, so per-library failures are collected
410
- * instead of thrown; the caller decides how to log them. Archived libraries are
411
- * deliberately left alone (frozen user data — restoring one runs the prune via
412
- * restoreGraphData anyway). Returns `{ scanned, removed, failed }`.
413
- */
414
- export function pruneOrphanEntitiesAll() {
415
- const libraries = listLibraries()
416
- const result = { scanned: libraries.length, removed: 0, failed: [] }
417
- for (const library of libraries) {
418
- try {
419
- result.removed += pruneOrphanEntities(library.id).removed.length
420
- } catch (error) {
421
- result.failed.push({ libraryId: library.id, error: String(error?.message || error) })
422
- }
423
- }
424
- return result
425
- }
426
-
427
- /**
428
- * Delete an entity. This is graph bookkeeping, not a memory write: the entity
429
- * row goes, no memory text is touched. An entity still referenced by links or
430
- * relationship snapshots is refused by default — silently deleting it would
431
- * turn every one of those edges into a `[deleted]` placeholder and rewrite what
432
- * those memories are *about*. `force` deletes through that: inbound links are
433
- * removed from every entry (not session-filtered — a link left behind in an
434
- * entry this conversation cannot see would dangle exactly the way this guard
435
- * exists to prevent, and the entry text itself is untouched) and relationship
436
- * snapshots on the endpoints are dropped with their history, which is the loss
437
- * `force` is asking for. Index links are cleaned before the entity row so a
438
- * crash between the two writes leaves at worst a collectable orphan, never a
439
- * link to an entity that is already gone.
440
- */
441
- export function deleteEntity({ exec, libraryId, entityId, force = false }) {
442
- const scope = scopeFor({ exec, libraryId })
443
- if (!entityId || typeof entityId !== 'string') throw new Error('entityId is required')
444
- const file = entitiesPath(scope.libraryId)
445
- const removedAuto = []
446
- const result = withFileLock(file, () => {
447
- const store = readEntities(scope.libraryId)
448
- if (!store.entities[entityId]) throw new Error('unknown entity')
449
- const index = loadPrivateIndex(scope.libraryId)
450
- let inbound = 0
451
- for (const entry of Object.values(index.entries || {})) {
452
- for (const link of entry.links || []) if (link.to === entityId) inbound += 1
453
- }
454
- // 关系快照的 key 是 JSON.stringify([fromId, toId])。旧数据、备份恢复或手写
455
- // 导入都可能带非 JSON key——这里必须和 mergeEntities 同口径地跳过损坏 key,
456
- // 否则一个坏 key 会让整次删除抛 SyntaxError(RPC 直接失败),而它本来只是
457
- // 一条读不懂的历史。跳过 = 保留:损坏 key 不参与删除,也就不会被静默丢掉。
458
- const relationshipKeys = Object.keys(store.relationships || {})
459
- .filter(key => {
460
- let endpoints
461
- try { endpoints = JSON.parse(key) } catch { return false }
462
- if (!Array.isArray(endpoints) || endpoints.length !== 2) return false
463
- const [from, to] = endpoints
464
- return from === entityId || to === entityId
465
- })
466
- if ((inbound || relationshipKeys.length) && !force) {
467
- const parts = []
468
- if (inbound) parts.push(`${inbound} link(s) point at it`)
469
- if (relationshipKeys.length) parts.push(`${relationshipKeys.length} relationship snapshot(s) reference it`)
470
- throw new Error(`entity is still referenced: ${parts.join(' and ')}; remove the links first or pass force to delete the entity with them`)
471
- }
472
- let removedLinks = 0
473
- if (inbound) {
474
- updatePrivateIndex(scope.libraryId, fresh => {
475
- for (const [fromId, entry] of Object.entries(fresh.entries)) {
476
- if (!Array.isArray(entry.links) || !entry.links.some(link => link.to === entityId)) continue
477
- const kept = entry.links.filter(link => {
478
- if (link.to !== entityId) return true
479
- if (link.source === 'auto') {
480
- removedAuto.push({
481
- from: fromId, to: entityId, kind: link.kind,
482
- rule: link.evidence?.rule || 'auto',
483
- })
484
- }
485
- return false
486
- })
487
- removedLinks += entry.links.length - kept.length
488
- entry.links = kept
489
- }
490
- })
491
- }
492
- for (const key of relationshipKeys) delete store.relationships[key]
493
- delete store.entities[entityId]
494
- writeJson(file, store)
495
- return { entityId, deleted: true, removedLinks, removedRelationships: relationshipKeys.length }
496
- })
497
- // Revoking an entity must not let the next consolidation resurrect its auto
498
- // edges; the exact edge keys go into the suppression table.
499
- if (removedAuto.length) {
500
- try { addSuppression(scope.libraryId, removedAuto, { by: 'user' }) } catch (error) {
501
- warn(`link suppression after entity delete skipped: ${error?.message || error}`)
502
- }
503
- }
504
- return result
505
- }
506
-
507
- /**
508
- * Merge one or more source entities into a target entity inside the same
509
- * library. This is graph bookkeeping, not a memory write: no memory text or
510
- * vector is touched, links only change the entity id they point at.
511
- *
512
- * Lock order follows deleteEntity exactly: the entity file lock is taken first
513
- * and the private index lock is nested inside it (withFileLock is re-entrant,
514
- * and no path takes the index lock before the entity lock, so this order cannot
515
- * deadlock). The index remap is written *before* the source rows are deleted:
516
- * a crash between the two writes leaves at worst collectable entities behind,
517
- * never a surviving link that points at an entity that is already gone.
518
- *
519
- * Dedupe after remapping keeps the edge that already pointed at the target (or,
520
- * with no such edge, the first remapped one), and carries an `auto` marker over
521
- * from a dropped duplicate so the graph view keeps its badge. Relationship
522
- * snapshots are re-keyed on the target; an existing target-side snapshot wins
523
- * and the discarded source key is reported in `relationships.conflicts`.
524
- */
525
- export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
526
- const scope = scopeFor({ exec, libraryId })
527
- if (typeof targetId !== 'string' || !targetId.trim()) throw new Error('targetId is required')
528
- const target = targetId.trim()
529
- if (!Array.isArray(sourceIds) || !sourceIds.length) throw new Error('sourceIds must be a non-empty array of entity ids')
530
- const sources = []
531
- const seen = new Set()
532
- for (const raw of sourceIds) {
533
- if (typeof raw !== 'string' || !raw.trim()) throw new Error('sourceIds must contain entity ids')
534
- const id = raw.trim()
535
- if (id === target) throw new Error('target entity cannot be one of its own sources')
536
- if (seen.has(id)) continue
537
- seen.add(id)
538
- sources.push(id)
539
- }
540
- if (!sources.length) throw new Error('sourceIds must name at least one entity')
541
- const file = entitiesPath(scope.libraryId)
542
- let targetName = target
543
- let mergedEntity = null
544
- const result = withFileLock(file, () => {
545
- const store = readEntities(scope.libraryId)
546
- const targetEntity = store.entities[target]
547
- if (!targetEntity || typeof targetEntity !== 'object') throw new Error(`unknown entity: ${target}`)
548
- targetName = String(targetEntity.name || target)
549
- const sourceEntities = []
550
- for (const id of sources) {
551
- const entity = store.entities[id]
552
- if (!entity || typeof entity !== 'object') throw new Error(`unknown entity: ${id}`)
553
- if (entity.kind !== targetEntity.kind) {
554
- throw new Error(`cannot merge entities of different kinds: ${targetEntity.kind || 'unknown'} vs ${entity.kind || 'unknown'}`)
555
- }
556
- sourceEntities.push(entity)
557
- }
558
-
559
- // Union of names: the target's own name stays the display name, every
560
- // source name becomes an alias, and the shared normalizer trims, dedupes
561
- // and caps at 30. Anything beyond the cap is reported, not silently lost.
562
- const rawAliases = [
563
- ...(Array.isArray(targetEntity.aliases) ? targetEntity.aliases : []),
564
- ...sourceEntities.flatMap(entity => [entity.name, ...(Array.isArray(entity.aliases) ? entity.aliases : [])]),
565
- ].filter(alias => typeof alias === 'string')
566
- const aliasUnion = [...new Set(rawAliases.map(alias => alias.trim()).filter(Boolean))]
567
- const aliases = normalizeAliases(aliasUnion)
568
- const droppedAliases = aliasUnion.slice(aliases.length)
569
-
570
- const sourceSet = new Set(sources)
571
- let remappedLinks = 0
572
- let duplicateLinks = 0
573
- updatePrivateIndex(scope.libraryId, index => {
574
- for (const entry of Object.values(index.entries || {})) {
575
- const links = Array.isArray(entry.links) ? entry.links : null
576
- if (!links || !links.some(link => link && sourceSet.has(link.to))) continue
577
- // Kinds already present on the target win the dedupe; every remapped
578
- // edge of such a kind is a duplicate, and an `auto` marker survives on
579
- // the retained edge even when the dropped copy was the auto one.
580
- const targetKinds = new Set()
581
- for (const link of links) if (link && link.to === target) targetKinds.add(link.kind)
582
- const autoKinds = new Set()
583
- const nextLinks = []
584
- for (const link of links) {
585
- if (!link || !sourceSet.has(link.to)) { nextLinks.push(link); continue }
586
- remappedLinks += 1
587
- if (targetKinds.has(link.kind)) {
588
- duplicateLinks += 1
589
- if (link.source === 'auto') autoKinds.add(link.kind)
590
- continue
591
- }
592
- targetKinds.add(link.kind)
593
- // An auto mention edge cites the entity it was built for; the merged
594
- // row inherits those citations so a later refresh can find them.
595
- const remapped = { ...link, to: target }
596
- if (remapped.evidence && sourceSet.has(remapped.evidence.entityId)) {
597
- remapped.evidence = { ...remapped.evidence, entityId: target }
598
- }
599
- nextLinks.push(remapped)
600
- }
601
- for (const kind of autoKinds) {
602
- const at = nextLinks.findIndex(item => item && item.to === target && item.kind === kind)
603
- if (at >= 0 && !nextLinks[at].source) nextLinks[at] = { ...nextLinks[at], source: 'auto' }
604
- }
605
- entry.links = nextLinks
606
- }
607
- })
608
-
609
- // Re-key snapshots: replace source endpoints with the target, keep an
610
- // existing target-side snapshot untouched (it is the history written under
611
- // the real pair), and drop self-loops a merge would create. The whole
612
- // snapshot object, history included, moves unchanged.
613
- const relationships = { moved: 0, conflicts: [] }
614
- for (const key of Object.keys(store.relationships || {})) {
615
- const snapshot = store.relationships[key]
616
- if (!snapshot || typeof snapshot !== 'object') continue
617
- let endpoints
618
- try { endpoints = JSON.parse(key) } catch { continue }
619
- if (!Array.isArray(endpoints) || endpoints.length !== 2) continue
620
- const [fromId, toId] = endpoints
621
- if (!sourceSet.has(fromId) && !sourceSet.has(toId)) continue
622
- const nextFrom = sourceSet.has(fromId) ? target : fromId
623
- const nextTo = sourceSet.has(toId) ? target : toId
624
- delete store.relationships[key]
625
- if (nextFrom === nextTo) {
626
- relationships.conflicts.push({ key, reason: 'self' })
627
- continue
628
- }
629
- const nextKey = JSON.stringify([nextFrom, nextTo])
630
- if (store.relationships[nextKey]) {
631
- relationships.conflicts.push({ key, reason: 'existing-target', keptKey: nextKey })
632
- continue
633
- }
634
- store.relationships[nextKey] = { ...snapshot, fromId: nextFrom, toId: nextTo }
635
- relationships.moved += 1
636
- }
637
-
638
- targetEntity.aliases = aliases
639
- // A merge is an assertion union: folding a confirmed source into a
640
- // provisional target confirms the surviving row. An archived target keeps
641
- // its archived state — the user retired that identity on purpose.
642
- const confirmedSource = sourceEntities.find(entity => entity.status === 'confirmed')
643
- if (confirmedSource && (!targetEntity.status || targetEntity.status === 'provisional')) {
644
- targetEntity.status = 'confirmed'
645
- targetEntity.confirmedAt = confirmedSource.confirmedAt || stamp()
646
- targetEntity.confirmedBy = confirmedSource.confirmedBy || 'user'
647
- if (!targetEntity.origin) targetEntity.origin = confirmedSource.origin || 'user'
648
- } else if (!ENTITY_STATUS.includes(targetEntity.status)) {
649
- targetEntity.status = 'provisional'
650
- }
651
- targetEntity.updatedAt = stamp()
652
- for (const id of sources) delete store.entities[id]
653
- writeJson(file, store)
654
- // Safety net: a source may have been kept alive only by a snapshot that the
655
- // merge dropped. The same lock is re-entered, so this cannot race the write
656
- // above; a prune failure must not turn a completed merge into an error. The
657
- // target is protected — an unreferenced pair is still a legitimate merge and
658
- // collecting the row it just merged into would undo it.
659
- try { pruneOrphanEntities(scope.libraryId, [target]) } catch (error) {
660
- warn(`orphan entity prune after entity merge skipped: ${error?.message || error}`)
661
- }
662
- mergedEntity = targetEntity
663
- return { targetId: target, merged: sources, aliases, droppedAliases, remappedLinks, duplicateLinks, relationships }
664
- })
665
-
666
- // The merged row now owns the union of names; recompute its mention edges so
667
- // citations point at the surviving entity and new aliases take effect.
668
- if (mergedEntity?.status === 'confirmed') {
669
- let suppression = null
670
- try { suppression = suppressionSet(scope.libraryId) } catch {}
671
- try {
672
- result.mentionRefresh = refreshEntityMentions({
673
- libraryId: scope.libraryId, entity: mergedEntity, suppression, operation: 'auto-link-merge',
674
- })
675
- } catch (error) {
676
- warn(`mention refresh after entity merge skipped: ${error?.message || error}`)
677
- }
678
- }
679
- // The merge is already durable; the activity log is diagnostics and is
680
- // fail-open by design, so it must never decide the result.
681
- try {
682
- record({
683
- kind: 'write', scope: 'private', libraryId: scope.libraryId, ok: true,
684
- message: `实体合并:「${targetName}」并入完成(${sources.length} 个来源)`,
685
- detail: {
686
- op: 'entity-merge', targetId: target, merged: sources,
687
- remappedLinks: result.remappedLinks, duplicateLinks: result.duplicateLinks,
688
- movedRelationships: result.relationships.moved,
689
- relationshipConflicts: result.relationships.conflicts.length,
690
- aliases: result.aliases.length, droppedAliases: result.droppedAliases.length,
691
- },
692
- refs: [target, ...sources],
693
- })
694
- } catch {}
695
- return result
696
- }
697
-
698
- const SUGGEST_LIMIT = 20
699
-
700
- function compareText(a, b) { return a < b ? -1 : a > b ? 1 : 0 }
701
-
702
- // Bounded Levenshtein. Row minima never decrease, so once a row's best cell is
703
- // already above the budget the remaining rows cannot recover; scanning stops.
704
- function withinEditDistance(a, b, max) {
705
- if (a === b) return true
706
- if (Math.abs(a.length - b.length) > max) return false
707
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index)
708
- for (let i = 1; i <= a.length; i += 1) {
709
- const current = [i]
710
- let best = i
711
- for (let j = 1; j <= b.length; j += 1) {
712
- const cost = a[i - 1] === b[j - 1] ? 0 : 1
713
- const value = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost)
714
- current[j] = value
715
- if (value < best) best = value
716
- }
717
- if (best > max) return false
718
- previous = current
719
- }
720
- return previous[b.length] <= max
721
- }
722
-
723
- /** Pure-read helper: does this CJK pair look like one name written two ways? */
724
- // 同一个人常被写成全称、昵称和单字称呼(顾清欢 / 欢欢 / 晴),三种表面互不包含、
725
- // 编辑距离又太远,于是各自成节点。只在「一端收尾、另一端起头」的共享字串上提议合并,
726
- // 并要求较长一侧去掉重叠后还剩两个字——空气/气候这种共用一个字的词对不提议。
727
- // 永远是候选,由用户点两次确认,绝不自动合并。
728
- function isNameCorePair(shorter, longer) {
729
- const cjkOnly = value => /^[\u3400-\u9fff\uf900-\ufaff]+$/u.test(value)
730
- if (!cjkOnly(shorter) || !cjkOnly(longer)) return false
731
- if (longer.length > 5) return false
732
- if (shorter.length === 1) return longer.includes(shorter)
733
- const overlap = (first, second) => {
734
- for (let size = Math.min(first.length, second.length); size >= 1; size -= 1) {
735
- if (first.slice(-size) === second.slice(0, size)) return size
736
- }
737
- return 0
738
- }
739
- const shared = Math.max(overlap(shorter, longer), overlap(longer, shorter))
740
- return shared >= 1 && longer.length - shared >= 2
741
- }
742
-
743
- const MERGE_REASON_ORDER = { containment: 0, 'edit-distance': 1, 'name-core': 2 }
744
-
745
- /**
746
- * Pure read: candidate entity merges inside one library. Never writes and never
747
- * merges — the caller shows the pair and the user confirms.
748
- * Names are folded with normalizeEntityName (NFKC / case / whitespace /
749
- * punctuation), identical folded names are skipped (that duplicate is handled by
750
- * createEntity or an explicit merge), and only same-kind pairs qualify. A pair
751
- * is a candidate when the shorter normalized name is contained in the longer one
752
- * and has >= 2 characters, when both names have >= 3 characters and sit at most
753
- * 2 edits apart, or (CJK only) when they look like the same name written in full
754
- * and in short — see isNameCorePair. The longer name is the target (the hub the
755
- * shorter one folds into); on equal length the older id wins, which keeps the
756
- * direction stable across calls. Results are sorted by reason then names then ids,
757
- * and capped at 20.
758
- */
759
- export function suggestEntityMerges({ libraryId } = {}) {
760
- const scope = scopeFor({ libraryId })
761
- const store = readEntities(scope.libraryId)
762
- const rows = Object.values(store.entities || {})
763
- .filter(entity => entity && typeof entity === 'object' && entity.id)
764
- .map(entity => ({ id: String(entity.id), kind: String(entity.kind || ''), key: normalizeEntityName(entity.name) }))
765
- .filter(row => row.key)
766
- const found = []
767
- for (let i = 0; i < rows.length; i += 1) {
768
- for (let j = i + 1; j < rows.length; j += 1) {
769
- const a = rows[i]
770
- const b = rows[j]
771
- if (a.kind !== b.kind || a.key === b.key) continue
772
- const aIsLonger = a.key.length > b.key.length || (a.key.length === b.key.length && a.id < b.id)
773
- const longer = aIsLonger ? a : b
774
- const shorter = aIsLonger ? b : a
775
- let reason = null
776
- if (shorter.key.length >= 2 && longer.key.includes(shorter.key)) reason = 'containment'
777
- else if (shorter.key.length >= 3
778
- && longer.key.length - shorter.key.length <= 2
779
- && withinEditDistance(shorter.key, longer.key, 2)) reason = 'edit-distance'
780
- else if (isNameCorePair(shorter.key, longer.key)) reason = 'name-core'
781
- if (!reason) continue
782
- found.push({ sourceId: shorter.id, targetId: longer.id, reason, sourceKey: shorter.key, targetKey: longer.key })
783
- }
784
- }
785
- found.sort((x, y) => (MERGE_REASON_ORDER[x.reason] - MERGE_REASON_ORDER[y.reason])
786
- || compareText(x.targetKey, y.targetKey)
787
- || compareText(x.sourceKey, y.sourceKey)
788
- || compareText(x.targetId, y.targetId)
789
- || compareText(x.sourceId, y.sourceId))
790
- return { items: found.slice(0, SUGGEST_LIMIT).map(item => ({ sourceId: item.sourceId, targetId: item.targetId, reason: item.reason })) }
791
- }
792
-
793
- // Unknown names need a complete source surface. Existing, asserted entities use
794
- // the broader mention matcher; guessing Chinese word boundaries here would turn
795
- // title n-grams into identities again. An evidence note is not source evidence.
796
- function hasCompleteEntityName(name, text) {
797
- const term = String(name || '').normalize('NFKC').toLowerCase().trim()
798
- const source = String(text || '').normalize('NFKC').toLowerCase()
799
- if (!term) return false
800
- const quoted = /「([^」\n]+)」|『([^』\n]+)』|“([^”\n]+)”|‘([^’\n]+)’|"([^"\n]+)"|'([^'\n]+)'|《([^》\n]+)》/gu
801
- for (const match of source.matchAll(quoted)) {
802
- if (match.slice(1).some(value => value !== undefined && value.trim() === term)) return true
803
- }
804
- const word = /[\p{L}\p{N}\p{M}_.’'-]/u
805
- for (let at = source.indexOf(term); at !== -1; at = source.indexOf(term, at + term.length)) {
806
- const left = source.slice(0, at)
807
- const right = source.slice(at + term.length)
808
- const rightBoundary = !right || !word.test([...right][0])
809
- const leftBoundary = !left || !word.test([...left].at(-1))
810
- if (leftBoundary && rightBoundary) return true
811
- if (rightBoundary && /(?:名叫|名字(?:是|叫|为)?|称呼(?:是|叫|为)?|自称|叫|username|nickname)\s*[::=]?\s*$/u.test(left)) return true
812
- }
813
- return false
814
- }
815
-
816
- function validateLinkArguments(kind, note, confidence) {
817
- if (!LINK_KINDS.includes(kind)) throw new Error(`link kind must be ${LINK_KINDS.join(', ')}`)
818
- const reason = String(note || '').trim()
819
- if (reason.replace(/\s/g, '').length < 8 || reason.length > 500) throw new Error('link note must contain 8-500 characters explaining the evidence')
820
- if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) throw new Error('link confidence must be between 0 and 1')
821
- return reason
822
- }
823
-
824
- /** Model-named entities stay provisional; manual UI creation is unchanged. */
825
- export function linkNamedEntity({ exec, libraryId, fromId, entity, kind, note, confidence = 0.7 }) {
826
- const scope = scopeFor({ exec, libraryId })
827
- validateLinkArguments(kind, note, confidence)
828
- const name = String(entity?.name || '').trim()
829
- const entityKind = entity?.kind || 'person'
830
- if (!ENTITY_KINDS.includes(entityKind)) throw new Error('invalid entity kind')
831
- if (!name || name.length > 120 || !normalizeEntityName(name)) throw new Error('entity name must contain 1-120 identifying characters')
832
- const origin = loadPrivateIndex(scope.libraryId).entries[fromId]
833
- if (!origin || !allowed(origin, exec)) throw new Error('unknown or inaccessible memory')
834
- const normalized = normalizeEntityName(name)
835
- const existing = listEntities({ exec, libraryId: scope.libraryId }).items.find(item => normalizeEntityName(item.name) === normalized
836
- || (Array.isArray(item.aliases) && item.aliases.some(alias => normalizeEntityName(alias) === normalized)))
837
- if (existing && existing.kind !== entityKind) throw new Error('entity already exists with a different kind')
838
- if (kind === 'person' && entityKind !== 'person') throw new Error('person links must target a person entity')
839
- if (!existing) {
840
- if ((origin.links || []).length >= 100) throw new Error('memory already has 100 links; review the existing connections first')
841
- if (!hasCompleteEntityName(name, origin.title) && !hasCompleteEntityName(name, origin.content)) {
842
- throw new Error('新实体需要来源记忆中的完整名称(complete name);不能用词语碎片、代词推测或关联理由代替。请引用完整称呼,或在界面中手动确认实体。')
843
- }
844
- }
845
- const target = existing || createEntity({ exec, libraryId: scope.libraryId, name, kind: entityKind, status: 'provisional', origin: 'worker' })
846
- return linkEntries({ exec, libraryId: scope.libraryId, fromId, toId: target.id, kind, note, confidence })
847
- }
848
-
849
- /**
850
- * Write one directed link from a memory to a memory or entity.
851
- *
852
- * `source` records who made the edge: 'auto' (private auto-association / entity
853
- * hub, §5.3–5.5) or 'user'. Anything else is omitted rather than stored, so the
854
- * field never turns into a free-form label and an old link without it keeps
855
- * reading as a model/user link. Replacement stays idempotent: the same
856
- * (to, kind) pair is overwritten in place instead of appended.
857
- */
858
- export function linkEntries({ exec, libraryId, fromId, toId, kind, note, confidence = 0.7, source }) {
859
- const scope = scopeFor({ exec, libraryId })
860
- const reason = validateLinkArguments(kind, note, confidence)
861
- if (fromId === toId) throw new Error('a memory cannot link to itself')
862
- const linkSource = source === 'auto' || source === 'user' ? source : null
863
- const entities = readEntities(scope.libraryId).entities
864
- let result
865
- updatePrivateIndex(scope.libraryId, index => {
866
- const origin = index.entries[fromId]
867
- const target = index.entries[toId]
868
- if (!origin || !allowed(origin, exec) || target && !allowed(target, exec)) throw new Error('unknown or inaccessible memory')
869
- if (!target && !entities[toId]) throw new Error('link target must be an existing memory or entity')
870
- if (kind === 'person' && entities[toId]?.kind !== 'person') throw new Error('person links must target a person entity')
871
- const links = Array.isArray(origin.links) ? origin.links : []
872
- result = { to: toId, kind, note: reason, confidence, createdAt: stamp() }
873
- if (linkSource) result.source = linkSource
874
- const found = links.findIndex(link => link.to === toId && link.kind === kind)
875
- if (found >= 0) links[found] = result
876
- else {
877
- if (links.length >= 100) throw new Error('memory already has 100 links; review the existing connections first')
878
- links.push(result)
879
- }
880
- origin.links = links
881
- })
882
- return { from: fromId, ...result }
883
- }
884
-
885
- /**
886
- * Remove every automatic edge in one library. Manual / worker edges are kept
887
- * byte-for-byte, and each removed (from,to,kind) is suppressed so the
888
- * deterministic layer cannot recreate it (P6). Used by the graph page's
889
- * "remove all auto edges" action and by operators cleaning a legacy library.
890
- */
891
- export function purgeAutoLinks({ libraryId } = {}) {
892
- const scope = scopeFor({ libraryId })
893
- const removed = []
894
- updatePrivateIndex(scope.libraryId, index => {
895
- for (const [fromId, entry] of Object.entries(index.entries || {})) {
896
- if (!Array.isArray(entry.links)) continue
897
- const kept = []
898
- for (const link of entry.links) {
899
- if (link && link.source === 'auto') {
900
- removed.push({ from: fromId, to: link.to, kind: link.kind, rule: link.evidence?.rule || 'auto' })
901
- continue
902
- }
903
- kept.push(link)
904
- }
905
- if (kept.length !== entry.links.length) entry.links = kept
906
- }
907
- })
908
- if (removed.length) {
909
- try { addSuppression(scope.libraryId, removed, { by: 'user' }) } catch (error) {
910
- warn(`link suppression after auto purge skipped: ${error?.message || error}`)
911
- }
912
- }
913
- try {
914
- record({
915
- kind: 'write', scope: 'private', libraryId: scope.libraryId, ok: true,
916
- message: `批量删除自动边:${removed.length} 条`,
917
- detail: { op: 'auto-link-purge', removed: removed.length },
918
- refs: [...new Set(removed.map(edge => edge.from))].slice(0, 20),
919
- })
920
- } catch {}
921
- return { removed: removed.length }
922
- }
923
-
924
- export function unlinkEntry({ libraryId, fromId, toId, kind }) {
925
- const scope = scopeFor({ libraryId })
926
- let removed = 0
927
- const removedAuto = []
928
- updatePrivateIndex(scope.libraryId, index => {
929
- const entry = index.entries[fromId]
930
- if (!entry) throw new Error('unknown memory')
931
- entry.links = (entry.links || []).filter(link => {
932
- const drop = link.to === toId && (!kind || link.kind === kind)
933
- if (drop) {
934
- removed += 1
935
- if (link.source === 'auto') {
936
- removedAuto.push({ from: fromId, to: toId, kind: link.kind, rule: link.evidence?.rule || 'auto' })
937
- }
938
- }
939
- return !drop
940
- })
941
- })
942
- // Deleting an auto edge is a negative label: the deterministic layer must not
943
- // add it back on the next consolidation.
944
- if (removedAuto.length) {
945
- try { addSuppression(scope.libraryId, removedAuto, { by: 'user' }) } catch (error) {
946
- warn(`link suppression after auto edge removal skipped: ${error?.message || error}`)
947
- }
948
- }
949
- return { removed }
950
- }
951
-
952
- // Graph filtering is read-only: normalize legacy stamps without rewriting them.
953
- // Shared with the global graph so both sides agree on what "same domain" means.
954
- export function graphDomain(value) { return String(value ?? '').normalize('NFKC').trim().toLowerCase() }
955
-
956
- export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 200, includeOrphans = false, offset, domain }) {
957
- const scope = scopeFor({ exec, libraryId })
958
- const index = loadPrivateIndex(scope.libraryId)
959
- const entities = readEntities(scope.libraryId).entities
960
- const cap = Math.max(1, Math.min(200, Math.floor(Number(limit) || 200)))
961
- const hops = Math.max(0, Math.min(2, Math.floor(Number(depth) || 0)))
962
- const domainFilter = graphDomain(domain)
963
- const domains = new Set()
964
- const visible = new Map()
965
- for (const [id, entry] of Object.entries(index.entries)) {
966
- if (!allowed(entry, exec)) continue
967
- const normalized = graphDomain(entry?.domain) || 'general'
968
- domains.add(normalized)
969
- if (!domainFilter || normalized === domainFilter) visible.set(id, normalized)
970
- }
971
- const paged = !focusId && offset !== undefined
972
- const start = paged ? Number(offset) : 0
973
- const pageStart = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0
974
- const edges = []
975
- const adjacency = new Map()
976
- for (const from of visible.keys()) {
977
- for (const link of index.entries[from].links || []) {
978
- if (!LINK_KINDS.includes(link.kind)) continue
979
- // A deleted target gets a placeholder; an inaccessible or other-domain
980
- // memory gets no hint. Filter before building either edges or adjacency.
981
- if (index.entries[link.to] && !visible.has(link.to)) continue
982
- // source is display metadata only ('auto' edges get a badge in the graph
983
- // view); an older link without the field reports null instead of undefined.
984
- // evidence.rule / surface / field let the graph say WHY an edge exists.
985
- // Legacy auto edges written before the rule schema carry no evidence.rule:
986
- // report them under the stable 'auto' bucket so the WebUI rule filter still
987
- // works on old data. New writes always record the real rule
988
- // (auto-link/apply.js) — this fallback is read-only display metadata.
989
- const edge = {
990
- from, to: link.to, kind: link.kind, note: link.note,
991
- confidence: link.confidence ?? 0.7, source: link.source || null,
992
- rule: link.evidence?.rule || (link.source === 'auto' ? 'auto' : null),
993
- evidence: link.evidence || null,
994
- }
995
- edges.push(edge)
996
- for (const [a, b] of [[from, link.to], [link.to, from]]) {
997
- if (!adjacency.has(a)) adjacency.set(a, new Set())
998
- adjacency.get(a).add(b)
999
- }
1000
- }
1001
- }
1002
- if (focusId && !visible.has(focusId) && !adjacency.has(focusId) && (!entities[focusId] || sessionIdOf(exec) || domainFilter)) throw new Error('unknown or inaccessible graph focus')
1003
- const selected = new Set()
1004
- const candidates = new Set()
1005
- if (focusId) {
1006
- let frontier = [focusId]
1007
- for (let hop = 0; hop <= hops; hop += 1) {
1008
- const next = []
1009
- for (const id of frontier) {
1010
- if (selected.size >= cap || selected.has(id)) continue
1011
- selected.add(id)
1012
- if (hop < hops) next.push(...(adjacency.get(id) || []))
1013
- }
1014
- frontier = next
1015
- }
1016
- } else {
1017
- // Build every qualifying candidate before slicing. Memories retain their
1018
- // original order, but later entities can no longer starve across pages.
1019
- // A domain never includes unrelated orphan entities, even on explicit opt-in.
1020
- for (const id of [...visible.keys(), ...Object.keys(entities), ...adjacency.keys()]) {
1021
- if (sessionIdOf(exec) && !visible.has(id) && !adjacency.has(id)) continue
1022
- if ((!includeOrphans || domainFilter) && entities[id] && !adjacency.has(id)) continue
1023
- candidates.add(id)
1024
- }
1025
- for (const id of [...candidates].slice(pageStart, pageStart + cap)) selected.add(id)
1026
- }
1027
- const nodes = [...selected].map(id => {
1028
- const entry = index.entries[id]
1029
- const entity = entities[id]
1030
- return { id, title: entry?.title || entity?.name || '[deleted]', layer: entry?.layer || null,
1031
- kind: entity?.kind || 'memory', strength: entry ? decayStrength(entry) : 0.5,
1032
- degree: adjacency.get(id)?.size || 0, missing: !entry && !entity,
1033
- ...(entry ? { domain: visible.get(id) } : {}),
1034
- ...(entity ? { status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional' } : {}) }
1035
- })
1036
- const remaining = pageStart + selected.size < candidates.size
1037
- return {
1038
- nodes, edges: edges.filter(edge => selected.has(edge.from) && (paged ? candidates.has(edge.to) : selected.has(edge.to))),
1039
- limit: cap, truncated: paged ? remaining : selected.size >= cap, focusId, domains: [...domains].sort(),
1040
- ...(paged ? { total: candidates.size, nextOffset: remaining ? pageStart + selected.size : null } : {}),
1041
- }
1042
- }
1043
-
1044
- // D9:recallRelations 只需要「与这条记忆相连的边」,旧实现却每次全库扫
1045
- // entries × links。这里按索引文件 mtime/size 建一份内存倒排(任意 id → 与它相连
1046
- // 的行),索引没变时直接复用;文件读不到(纯内存索引)时本次构建、不缓存。
1047
- const relationInvertedCache = new Map()
1048
-
1049
- function relationInvertedIndex(libraryId, index) {
1050
- let signature = null
1051
- try {
1052
- const stat = fs.statSync(path.join(indexDir(), `${libraryId}.json`))
1053
- signature = `${stat.mtimeMs}:${stat.size}`
1054
- } catch {}
1055
- const cached = relationInvertedCache.get(libraryId)
1056
- if (signature && cached && cached.signature === signature) return cached.inverted
1057
- const inverted = new Map()
1058
- const push = (key, row) => {
1059
- if (!key) return
1060
- let rows = inverted.get(key)
1061
- if (!rows) inverted.set(key, rows = [])
1062
- rows.push(row)
1063
- }
1064
- for (const [from, entry] of Object.entries(index?.entries || {})) {
1065
- for (const link of entry?.links || []) {
1066
- if (!link || !link.to) continue
1067
- const row = { from, link }
1068
- push(from, row)
1069
- // 自环(link.to === from)只存一份,避免查询看到同一行两次。
1070
- if (link.to !== from) push(link.to, row)
1071
- }
1072
- }
1073
- if (signature) relationInvertedCache.set(libraryId, { signature, inverted })
1074
- return inverted
1075
- }
1076
-
1077
- export function recallRelations(libraryId, index, id, sessionId) {
1078
- const store = readEntities(libraryId)
1079
- const entities = store.entities
1080
- // 关系衰减是写入侧算的(updateRelationship 每次更新都把 retention_strength 折一次),
1081
- // 但读取侧从来没用过它——一条半年没人碰过的关系,和一条昨天刚更新的关系,扩展
1082
- // 时的分量完全一样。这里把「这个实体背后最强的活跃关系还剩多少」带出去,让调用方
1083
- // 能按它排序和过滤。记忆型目标不归关系衰减管,retention 留 null。
1084
- const retentionOf = new Map()
1085
- for (const relationship of Object.values(store.relationships || {})) {
1086
- const value = Number.isFinite(Number(relationship?.retention_strength)) ? Number(relationship.retention_strength) : 1
1087
- for (const entityId of [relationship?.fromId, relationship?.toId]) {
1088
- if (!entityId) continue
1089
- const current = retentionOf.get(entityId)
1090
- if (current === undefined || value > current) retentionOf.set(entityId, value)
1091
- }
1092
- }
1093
- const out = []
1094
- // 倒排只含与 id 相连的行(出边来自 id 自己,入边来自别的条目)。行顺序与旧实现
1095
- // 的 entries 遍历顺序一致:入边按来源条目顺序、出边在 id 自己的位置。
1096
- for (const { from, link } of relationInvertedIndex(libraryId, index).get(id) || []) {
1097
- if (from !== id && link.to !== id) continue
1098
- const entry = index.entries?.[from]
1099
- if (!entry) continue
1100
- if (!isMemoryEligible(entry, { automatic: true }) || !visibleToSession(entry, sessionId)) continue
1101
- // entity-mention is a fact index, not a relationship: its confidence is 1.0
1102
- // by construction, and letting it into the top-2 would crowd out the manual /
1103
- // field-evidence edges this expansion exists to surface.
1104
- if (link.evidence?.rule === 'entity-mention') continue
1105
- const to = from === id ? link.to : from
1106
- const target = index.entries[to]
1107
- if (target && (!isMemoryEligible(target, { automatic: true }) || !visibleToSession(target, sessionId))) continue
1108
- // A dangling edge (entry and entity both gone) used to be dropped here
1109
- // while getGraph rendered the same disk state as a [deleted] placeholder —
1110
- // the two views disagreed. Both now report the edge and mark it `missing`;
1111
- // the caller filters if it wants the old silence back.
1112
- const missing = !target && !entities[to]
1113
- out.push({
1114
- id: to,
1115
- title: target?.title || entities[to]?.name || '[deleted]',
1116
- kind: link.kind,
1117
- note: String(link.note || '').slice(0, 80),
1118
- confidence: link.confidence ?? 0.7,
1119
- missing,
1120
- retention: target ? null : (retentionOf.has(to) ? retentionOf.get(to) : 1),
1121
- })
1122
- }
1123
- // Confidence is the write-time claim; retention is how much of it survived. An
1124
- // entity link pays both, a memory link only pays confidence.
1125
- const weightOf = (link) => (link.retention == null ? 1 : link.retention) * (Number(link.confidence) || 0)
1126
- return out.sort((a, b) => weightOf(b) - weightOf(a) || b.confidence - a.confidence).slice(0, 2)
1127
- }
1128
-
1129
- export function getRelationship({ exec, libraryId, fromId, toId }) {
1130
- const scope = scopeFor({ exec, libraryId })
1131
- const store = readEntities(scope.libraryId)
1132
- const relationship = store.relationships[JSON.stringify([fromId, toId])]
1133
- if (!relationship) return { relationship: null }
1134
- const index = loadPrivateIndex(scope.libraryId)
1135
- if (sessionIdOf(exec) && relationship.evidenceIds.some(id => !index.entries[id] || !allowed(index.entries[id], exec))) return { relationship: null }
1136
- return { relationship }
1137
- }
1138
-
1139
- export function updateRelationship({ exec, libraryId, fromId, toId, state, evidenceIds, reason }) {
1140
- const scope = scopeFor({ exec, libraryId })
1141
- if (fromId === toId) throw new Error('relationship needs two distinct entities')
1142
- if (!Array.isArray(evidenceIds) || !evidenceIds.length || evidenceIds.length > 20) throw new Error('relationship needs 1-20 evidence memory ids')
1143
- if (String(reason || '').trim().length < 8) throw new Error('relationship update needs an evidence-based reason')
1144
- if (!state || typeof state !== 'object' || Array.isArray(state)) throw new Error('relationship state must be an object')
1145
- const snapshot = {}
1146
- for (const key of ['familiarity', 'trust', 'warmth']) {
1147
- if (state[key] === undefined || state[key] === null) { snapshot[key] = null; continue }
1148
- if (!Number.isFinite(state[key]) || state[key] < 0 || state[key] > 1) throw new Error(`relationship ${key} must be 0-1 or null (unknown)`)
1149
- snapshot[key] = state[key]
1150
- }
1151
- for (const key of ['boundaries', 'callbacks', 'openPromises']) {
1152
- const values = state[key] || []
1153
- if (!Array.isArray(values) || values.length > 20 || values.some(value => typeof value !== 'string' || value.length > 300)) throw new Error(`invalid relationship ${key}`)
1154
- snapshot[key] = values.slice()
1155
- }
1156
- const index = loadPrivateIndex(scope.libraryId)
1157
- if (evidenceIds.some(id => !index.entries[id] || !allowed(index.entries[id], exec))) throw new Error('relationship evidence is not visible in this conversation')
1158
- const file = entitiesPath(scope.libraryId)
1159
- return withFileLock(file, () => {
1160
- const store = readEntities(scope.libraryId)
1161
- if (!store.entities[fromId] || !store.entities[toId]) throw new Error('relationship endpoints must be existing entities')
1162
- const key = JSON.stringify([fromId, toId])
1163
- const previous = store.relationships[key]
1164
- const at = stamp()
1165
- const history = [...(previous?.history || [])]
1166
- if (previous) {
1167
- history.push({
1168
- state: previous.state, evidenceIds: previous.evidenceIds, reason: previous.reason,
1169
- validFrom: previous.validFrom, validTo: at,
1170
- retention_strength: previous.retention_strength ?? 1,
1171
- })
1172
- }
1173
- if (history.length > RELATIONSHIP_HISTORY_LIMIT) history.splice(0, history.length - RELATIONSHIP_HISTORY_LIMIT)
1174
- const decayed = relationshipRetentionAt(
1175
- previous?.retention_strength ?? 1,
1176
- hoursBetween(previous?.last_access_at || previous?.validFrom, at),
1177
- )
1178
- const retention = previous
1179
- ? accessRelationship(decayed, { lastAccessAt: previous.last_access_at, now: Date.parse(at) })
1180
- : 1
1181
- const relationship = {
1182
- fromId, toId, state: snapshot, evidenceIds: [...new Set(evidenceIds)],
1183
- reason: String(reason).trim().slice(0, 1000), validFrom: previous?.validFrom || at, revision: (previous?.revision || 0) + 1,
1184
- retention_strength: retention,
1185
- last_access_at: at,
1186
- next_review_at: new Date(Date.parse(at) + RELATIONSHIP_HALF_LIFE_HOURS * 3_600_000).toISOString(),
1187
- history,
1188
- }
1189
- store.relationships[key] = relationship
1190
- writeJson(file, store)
1191
- return { relationship }
1192
- })
1193
- }
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { indexDir, readJsonStrict, writeJson, withFileLock, stamp, warn } from './paths.js'
4
+ import { loadPrivateIndex, updatePrivateIndex, newMemoryId, listLibraries } from './state.js'
5
+ import { resolveLibrary, sessionIdOf, visibleToSession, isMemoryEligible, decayStrength } from './memory.js'
6
+ import { record } from './activity-log.js'
7
+ // Entity merge suggestions reuse the exact folding rule auto-linking already
8
+ // uses (NFKC / case / whitespace / punctuation). This is a deliberate module
9
+ // cycle: private-links.js imports the entity writers from here, but both sides
10
+ // only touch each other's bindings in function bodies, and ESM hoists the
11
+ // function declarations before either module body runs.
12
+ import { normalizeEntityName } from './private-links.js'
13
+ import { refreshEntityMentions } from './auto-link/apply.js'
14
+ import { addSuppression, suppressionSet } from './auto-link/suppression.js'
15
+ import { ENTITY_STATUS } from './auto-link/policy.js'
16
+
17
+ export const LINK_KINDS = ['relation', 'commitment', 'event', 'person', 'conflict', 'supersede']
18
+ const ENTITY_KINDS = ['person', 'place', 'thing', 'org']
19
+ // Relationship revisions are audit history, not an ever-growing data store. A
20
+ // long-lived role-play can update one relation hundreds of times; keeping all of
21
+ // it made every recall re-parse a multi-MB sidecar. The current state and its
22
+ // evidence stay intact; only the old snapshots are capped.
23
+ const RELATIONSHIP_HISTORY_LIMIT = 50
24
+ // Relationship retention is metadata, not structure: the edge stays, only its
25
+ // confidence in the sidebar/recall can fade, freeze or revive. Parameters follow
26
+ // the local, wall-clock policy used by the audit comparison; no LLM, no text.
27
+ const RELATIONSHIP_HALF_LIFE_HOURS = 24
28
+ const RELATIONSHIP_ACCESS_ALPHA = 0.05
29
+ const RELATIONSHIP_ACCESS_COOLDOWN_MS = 3_600_000
30
+
31
+ function hoursBetween(from, to) {
32
+ const start = Date.parse(String(from || ''))
33
+ const end = Date.parse(String(to || ''))
34
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return 0
35
+ return Math.max(0, (end - start) / 3_600_000)
36
+ }
37
+
38
+ /** Exponential retention at a wall-clock instant; clock rollback never boosts it. */
39
+ export function relationshipRetentionAt(strength, elapsedHours, halfLifeHours = RELATIONSHIP_HALF_LIFE_HOURS) {
40
+ const base = Number(strength)
41
+ const hours = Number(elapsedHours)
42
+ const halfLife = Number(halfLifeHours)
43
+ if (!Number.isFinite(base) || base <= 0) return 0
44
+ if (!Number.isFinite(hours) || hours <= 0 || !Number.isFinite(halfLife) || halfLife <= 0) return Math.min(1, base)
45
+ return Math.min(1, base * Math.pow(0.5, hours / halfLife))
46
+ }
47
+
48
+ /** A recall/access reinforces without jumping to 1. */
49
+ export function accessRelationship(strength, { cooldownMs = RELATIONSHIP_ACCESS_COOLDOWN_MS, lastAccessAt = null, now = Date.now() } = {}) {
50
+ const base = Math.min(1, Math.max(0, Number(strength) || 0))
51
+ const last = Date.parse(String(lastAccessAt || ''))
52
+ if (Number.isFinite(last) && Number(now) - last < cooldownMs) return base
53
+ return Math.min(1, base + (1 - base) * RELATIONSHIP_ACCESS_ALPHA)
54
+ }
55
+
56
+ function entitiesPath(libraryId) { return path.join(indexDir(), `${libraryId}.entities.json`) }
57
+
58
+ function readEntities(libraryId) {
59
+ const result = readJsonStrict(entitiesPath(libraryId))
60
+ if (result.ok) {
61
+ if (!result.value?.entities || typeof result.value.entities !== 'object' || Array.isArray(result.value.entities)) throw new Error('invalid entity store')
62
+ return { relationships: {}, ...result.value }
63
+ }
64
+ if (result.missing) return { version: 1, entities: {}, relationships: {} }
65
+ throw new Error(`cannot read entity store: ${result.error?.message || 'invalid data'}`)
66
+ }
67
+
68
+ function scopeFor(args) { return resolveLibrary({ ...args, readOnly: true }) }
69
+ function allowed(entry, exec) {
70
+ return !sessionIdOf(exec) || (isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, sessionIdOf(exec)))
71
+ }
72
+
73
+ /**
74
+ * Entity listing with the derived `linked` flag. The visibility rule
75
+ * is unchanged: without a session every entity comes back (GraphPanel calls it
76
+ * exactly that way), with a session only entities reachable from visible memory
77
+ * links are listed. What is new is the classification:
78
+ * * `linked` = referenced by an entry's links[] OR by a relationship snapshot.
79
+ * A snapshot counts — an entity with only a relationship and no memory link
80
+ * is history, not an orphan, and must not be misjudged as one.
81
+ * * With a session, a snapshot only counts when its evidenceIds include a
82
+ * memory visible in this conversation; without a session every snapshot
83
+ * counts (there is nobody to hide it from).
84
+ * `linked` is derived on the fly and never written back to the entities file —
85
+ * the startup prune (pruneOrphanEntitiesAll) stays the sole collector.
86
+ */
87
+ export function listEntities(args) {
88
+ const scope = scopeFor(args)
89
+ const store = readEntities(scope.libraryId)
90
+ const index = loadPrivateIndex(scope.libraryId)
91
+ const sessionId = sessionIdOf(args.exec)
92
+ const linked = new Set()
93
+ for (const entry of Object.values(index.entries)) {
94
+ if (!allowed(entry, args.exec)) continue
95
+ for (const link of entry.links || []) linked.add(link.to)
96
+ }
97
+ for (const rel of Object.values(store.relationships || {})) {
98
+ if (sessionId) {
99
+ const evidenceVisible = (Array.isArray(rel?.evidenceIds) ? rel.evidenceIds : [])
100
+ .some(id => { const entry = index.entries[id]; return Boolean(entry) && allowed(entry, args.exec) })
101
+ if (!evidenceVisible) continue
102
+ }
103
+ if (rel?.fromId) linked.add(rel.fromId)
104
+ if (rel?.toId) linked.add(rel.toId)
105
+ }
106
+ const items = Object.values(store.entities)
107
+ .filter(entity => !sessionId || linked.has(entity.id))
108
+ .map(entity => ({
109
+ ...entity,
110
+ // Legacy rows have no status; they read as provisional, never confirmed.
111
+ status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional',
112
+ linked: linked.has(entity.id),
113
+ }))
114
+ return { items, total: items.length }
115
+ }
116
+
117
+ export function graphExport(libraryId) {
118
+ const scope = scopeFor({ libraryId })
119
+ return readEntities(scope.libraryId)
120
+ }
121
+
122
+ /**
123
+ * Rebuild the entity/relationship store a memory package came with.
124
+ *
125
+ * Returns the ids of entities this call actually created, tagged with `origin` (the
126
+ * import batch). A revert needs that list: it is the difference between "remove what
127
+ * the package brought" and "remove a person the user already knew".
128
+ */
129
+ export function restoreGraphData(libraryId, data, memoryIdMap, { origin = null } = {}) {
130
+ if (!data?.entities) return { createdEntityIds: [] }
131
+ const scope = scopeFor({ libraryId })
132
+ const entityMap = {}
133
+ const createdEntityIds = []
134
+ for (const [oldId, entity] of Object.entries(data.entities).slice(0, 2000)) {
135
+ if (!/^ent[-_][a-z0-9_-]+$/i.test(oldId)) continue
136
+ // An import is a user action: rows without a status come back confirmed, and
137
+ // an explicit status travels with the backup unchanged.
138
+ const restored = createEntity({
139
+ libraryId: scope.libraryId, name: entity.name, kind: entity.kind, aliases: entity.aliases || [], origin,
140
+ status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'confirmed',
141
+ confirmedBy: entity.confirmedBy || 'user',
142
+ })
143
+ entityMap[oldId] = restored.id
144
+ if (origin && restored.origin === origin) createdEntityIds.push(restored.id)
145
+ }
146
+ const remap = { ...entityMap, ...memoryIdMap }
147
+ updatePrivateIndex(libraryId, index => {
148
+ for (const id of Object.values(memoryIdMap)) {
149
+ const entry = index.entries[id]
150
+ if (!entry) continue
151
+ entry.links = (entry.links || []).map(link => ({ ...link, to: remap[link.to] || link.to }))
152
+ }
153
+ })
154
+ for (const relationship of Object.values(data.relationships || {})) {
155
+ if (!entityMap[relationship.fromId] || !entityMap[relationship.toId]) continue
156
+ const evidenceIds = (relationship.evidenceIds || []).map(id => memoryIdMap[id]).filter(Boolean)
157
+ if (!evidenceIds.length) continue
158
+ updateRelationship({ libraryId, fromId: entityMap[relationship.fromId], toId: entityMap[relationship.toId], state: relationship.state, evidenceIds, reason: relationship.reason || 'Imported relationship with explicit evidence.' })
159
+ }
160
+ // A backup carries the whole entity store, but only the memories that made it
161
+ // through the export/import mapping come back, so entities nothing points at
162
+ // any more would sit in the file forever as invisible weight. Collect them
163
+ // once the remap is done; a prune failure must not fail a restore that
164
+ // already succeeded, and the startup sweep would catch it on the next launch.
165
+ try {
166
+ pruneOrphanEntities(scope.libraryId)
167
+ } catch (error) {
168
+ warn(`orphan entity prune after graph restore skipped: ${error?.message || error}`)
169
+ }
170
+ return { createdEntityIds }
171
+ }
172
+
173
+ /**
174
+ * Undo `restoreGraphData` for one import batch: delete exactly the entities that call
175
+ * created. Relationships hang off those entities, so `deleteEntity` cascades them; an
176
+ * entity the user already had is untagged and therefore untouched. A failure is
177
+ * reported per id rather than thrown, because a revert that removed the memories has
178
+ * already done its job and half a graph is still better than an exception the caller
179
+ * cannot act on.
180
+ */
181
+ export function revertGraphData({ libraryId, entityIds = [] }) {
182
+ const removed = []
183
+ const failed = []
184
+ for (const entityId of entityIds) {
185
+ try {
186
+ deleteEntity({ libraryId, entityId, force: true })
187
+ removed.push(entityId)
188
+ } catch (error) {
189
+ failed.push({ entityId, error: String(error?.message || error) })
190
+ }
191
+ }
192
+ return { removed, failed }
193
+ }
194
+
195
+ /**
196
+ * `origin` tags an entity that somebody else created on this user's behalf — an
197
+ * imported memory package, say. It exists so the import can be undone: an entity
198
+ * that already existed before the import is returned as-is and stays untagged, so a
199
+ * revert can never delete a person the user had added themselves.
200
+ *
201
+ * `status` is the auto-link assertion state. The default is
202
+ * `provisional`: creation alone never proves a name is real, so a new row
203
+ * produces no mention edges until a user / agent / worker confirms it. Explicit
204
+ * creation paths (UI, import) pass `confirmed`; worker tools keep provisional
205
+ * and let the review queue decide.
206
+ */
207
+ export function createEntity({ exec, libraryId, name, kind = 'person', aliases = [], origin = null, status = 'provisional', confirmedBy = null }) {
208
+ const scope = scopeFor({ exec, libraryId })
209
+ if (!ENTITY_KINDS.includes(kind)) throw new Error(`entity kind must be ${ENTITY_KINDS.join(', ')}`)
210
+ if (!ENTITY_STATUS.includes(status)) throw new Error(`entity status must be ${ENTITY_STATUS.join(', ')}`)
211
+ const clean = String(name || '').trim()
212
+ if (!clean || clean.length > 120) throw new Error('entity name must contain 1-120 characters')
213
+ const file = entitiesPath(scope.libraryId)
214
+ return withFileLock(file, () => {
215
+ const store = readEntities(scope.libraryId)
216
+ const existing = Object.values(store.entities).find(entity => entity.name === clean && entity.kind === kind)
217
+ if (existing) return existing
218
+ const id = newMemoryId('ent')
219
+ const at = stamp()
220
+ const entity = {
221
+ id, name: clean, kind, aliases: normalizeAliases(aliases), status,
222
+ createdAt: at, updatedAt: at,
223
+ ...(origin ? { origin: String(origin) } : {}),
224
+ ...(status === 'confirmed' ? { confirmedAt: at, confirmedBy: String(confirmedBy || 'user') } : {}),
225
+ }
226
+ store.entities[id] = entity
227
+ writeJson(file, store)
228
+ return entity
229
+ })
230
+ }
231
+
232
+ /**
233
+ * Explicit confirmation is the only way an entity becomes `confirmed`. The write
234
+ * is followed by one incremental mention pass for that entity, so existing
235
+ * memories gain their edges immediately instead of waiting for the next
236
+ * consolidation.
237
+ */
238
+ export function confirmEntities({ exec, libraryId, entityIds, by = 'user' }) {
239
+ const scope = scopeFor({ exec, libraryId })
240
+ const ids = [...new Set((Array.isArray(entityIds) ? entityIds : []).map(id => String(id || '').trim()).filter(Boolean))]
241
+ if (!ids.length) throw new Error('entityIds must name at least one entity')
242
+ if (!['user', 'agent', 'worker'].includes(by)) throw new Error('confirmation actor must be user, agent or worker')
243
+ const file = entitiesPath(scope.libraryId)
244
+ const confirmed = []
245
+ // Already-confirmed rows are refreshed too: if they were confirmed while the
246
+ // mode was 'off', status changed but no edge was written. Re-confirming (or the
247
+ // deterministic switch below) must be able to backfill, idempotently.
248
+ const refreshTargets = []
249
+ withFileLock(file, () => {
250
+ const store = readEntities(scope.libraryId)
251
+ const at = stamp()
252
+ for (const id of ids) {
253
+ const entity = store.entities[id]
254
+ if (!entity || typeof entity !== 'object') throw new Error(`unknown entity: ${id}`)
255
+ if (entity.status === 'archived') continue
256
+ if (entity.status === 'confirmed') { refreshTargets.push(entity); continue }
257
+ entity.status = 'confirmed'
258
+ entity.origin = by
259
+ entity.confirmedAt = at
260
+ entity.confirmedBy = by
261
+ entity.updatedAt = at
262
+ confirmed.push(entity)
263
+ refreshTargets.push(entity)
264
+ }
265
+ if (confirmed.length) writeJson(file, store)
266
+ })
267
+ let suppression = null
268
+ try { suppression = suppressionSet(scope.libraryId) } catch {}
269
+ let entities = 0
270
+ for (const entity of refreshTargets) {
271
+ try {
272
+ const result = refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression })
273
+ entities += result.added + result.updated
274
+ } catch (error) {
275
+ warn(`mention refresh after entity confirmation skipped: ${error?.message || error}`)
276
+ }
277
+ }
278
+ return { confirmed: confirmed.map(entity => entity.id), skipped: ids.length - confirmed.length, entities }
279
+ }
280
+
281
+ /**
282
+ * One-time grading of pre-status entity rows. It never confirms on
283
+ * statistical evidence: an old row is `confirmed` only when somebody had already
284
+ * asserted it (origin user/agent/worker, or a non-auto link points at it), and
285
+ * everything else becomes `provisional`. Callers pass `apply:false` for dry runs.
286
+ */
287
+ export function gradeLegacyEntities({ libraryId, apply = false } = {}) {
288
+ const scope = scopeFor({ libraryId })
289
+ const file = entitiesPath(scope.libraryId)
290
+ return withFileLock(file, () => {
291
+ const store = readEntities(scope.libraryId)
292
+ const asserted = new Set()
293
+ try {
294
+ for (const entry of Object.values(loadPrivateIndex(scope.libraryId).entries || {})) {
295
+ for (const link of entry.links || []) {
296
+ if (link?.to && link.source !== 'auto') asserted.add(link.to)
297
+ }
298
+ }
299
+ } catch {}
300
+ const result = { scanned: 0, changed: 0, provisional: 0, confirmed: 0, applied: apply === true }
301
+ const at = stamp()
302
+ for (const entity of Object.values(store.entities || {})) {
303
+ result.scanned += 1
304
+ if (!ENTITY_STATUS.includes(entity.status)) {
305
+ const protectedRow = ['user', 'agent', 'worker'].includes(entity.origin) || asserted.has(entity.id)
306
+ const status = protectedRow ? 'confirmed' : 'provisional'
307
+ result[status] += 1
308
+ if (apply) {
309
+ entity.status = status
310
+ if (status === 'confirmed') {
311
+ entity.confirmedAt = entity.confirmedAt || at
312
+ entity.confirmedBy = entity.confirmedBy || (['user', 'agent', 'worker'].includes(entity.origin) ? entity.origin : 'user')
313
+ }
314
+ entity.updatedAt = at
315
+ result.changed += 1
316
+ }
317
+ continue
318
+ }
319
+ if (entity.status === 'confirmed') result.confirmed += 1
320
+ if (entity.status === 'provisional') result.provisional += 1
321
+ }
322
+ if (apply && result.changed) writeJson(file, store)
323
+ return result
324
+ })
325
+ }
326
+
327
+ function normalizeAliases(aliases) {
328
+ if (!Array.isArray(aliases) || aliases.some(alias => typeof alias !== 'string')) throw new Error('aliases must be an array of strings')
329
+ return [...new Set(aliases.map(alias => alias.trim()).filter(Boolean))].slice(0, 30).map(alias => alias.slice(0, 120))
330
+ }
331
+
332
+ export function renameEntity({ libraryId, entityId, name, aliases = [] }) {
333
+ const scope = scopeFor({ libraryId })
334
+ const clean = String(name || '').trim()
335
+ if (!clean || clean.length > 120) throw new Error('entity name must contain 1-120 characters')
336
+ const file = entitiesPath(scope.libraryId)
337
+ const entity = withFileLock(file, () => {
338
+ const store = readEntities(scope.libraryId)
339
+ const row = store.entities[entityId]
340
+ if (!row) throw new Error('unknown entity')
341
+ row.name = clean
342
+ row.aliases = normalizeAliases(aliases)
343
+ row.updatedAt = stamp()
344
+ writeJson(file, store)
345
+ return row
346
+ })
347
+ // A confirmed entity's mention edges cite surfaces by name; rename/alias edits
348
+ // must collect the stale ones and attach the new ones immediately.
349
+ if (entity.status === 'confirmed') {
350
+ let suppression = null
351
+ try { suppression = suppressionSet(scope.libraryId) } catch {}
352
+ try {
353
+ refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression, operation: 'auto-link-rename' })
354
+ } catch (error) {
355
+ warn(`mention refresh after entity rename skipped: ${error?.message || error}`)
356
+ }
357
+ }
358
+ return entity
359
+ }
360
+
361
+ // What keeps an entity alive. Edges only live in one direction: an entry's
362
+ // links[] names the entity, the entity stores nothing back. On top of that,
363
+ // relationship snapshots (same file, keyed by the endpoint pair) describe the
364
+ // pair with history and evidence that outlive the individual entries — deleting
365
+ // an endpoint would leave a snapshot whose endpoints no longer resolve, so a
366
+ // snapshot counts as a reference too. An entity referenced by neither is an
367
+ // *orphan*: unreachable except as a graph placeholder, and safe to collect.
368
+ // Orphans come from old builds whose permanent delete dropped the memory row
369
+ // without cascading, and from partial backups.
370
+
371
+ /**
372
+ * Remove every entity in one library that no entry links to and no relationship
373
+ * snapshot references. Idempotent: on healthy data it writes nothing. Returns
374
+ * `{ removed, total }` with the removed entity ids.
375
+ *
376
+ * `keep` names ids that must survive even while unreferenced — a merge passes
377
+ * its target, because folding sources into a row and then collecting that row
378
+ * would silently undo the merge when the pair had no edges yet.
379
+ */
380
+ export function pruneOrphanEntities(libraryId, keep = []) {
381
+ const scope = scopeFor({ libraryId })
382
+ const file = entitiesPath(scope.libraryId)
383
+ const protectedIds = new Set(Array.isArray(keep) ? keep : [])
384
+ return withFileLock(file, () => {
385
+ const store = readEntities(scope.libraryId)
386
+ const ids = Object.keys(store.entities)
387
+ if (!ids.length) return { removed: [], total: 0 }
388
+ const referenced = new Set()
389
+ for (const entry of Object.values(loadPrivateIndex(scope.libraryId).entries || {})) {
390
+ for (const link of entry.links || []) referenced.add(link.to)
391
+ }
392
+ for (const relationship of Object.values(store.relationships || {})) {
393
+ referenced.add(relationship.fromId)
394
+ referenced.add(relationship.toId)
395
+ }
396
+ const removed = ids.filter(id => !referenced.has(id) && !protectedIds.has(id))
397
+ // Write only when something actually goes, so the common case never touches
398
+ // the file (mtime-based caches, backups and concurrent readers all benefit).
399
+ if (removed.length) {
400
+ for (const id of removed) delete store.entities[id]
401
+ writeJson(file, store)
402
+ }
403
+ return { removed, total: ids.length }
404
+ })
405
+ }
406
+
407
+ /**
408
+ * The startup sweep: run pruneOrphanEntities over every active library. One
409
+ * corrupt store must not stop the rest, so per-library failures are collected
410
+ * instead of thrown; the caller decides how to log them. Archived libraries are
411
+ * deliberately left alone (frozen user data — restoring one runs the prune via
412
+ * restoreGraphData anyway). Returns `{ scanned, removed, failed }`.
413
+ */
414
+ export function pruneOrphanEntitiesAll() {
415
+ const libraries = listLibraries()
416
+ const result = { scanned: libraries.length, removed: 0, failed: [] }
417
+ for (const library of libraries) {
418
+ try {
419
+ result.removed += pruneOrphanEntities(library.id).removed.length
420
+ } catch (error) {
421
+ result.failed.push({ libraryId: library.id, error: String(error?.message || error) })
422
+ }
423
+ }
424
+ return result
425
+ }
426
+
427
+ /**
428
+ * Delete an entity. This is graph bookkeeping, not a memory write: the entity
429
+ * row goes, no memory text is touched. An entity still referenced by links or
430
+ * relationship snapshots is refused by default — silently deleting it would
431
+ * turn every one of those edges into a `[deleted]` placeholder and rewrite what
432
+ * those memories are *about*. `force` deletes through that: inbound links are
433
+ * removed from every entry (not session-filtered — a link left behind in an
434
+ * entry this conversation cannot see would dangle exactly the way this guard
435
+ * exists to prevent, and the entry text itself is untouched) and relationship
436
+ * snapshots on the endpoints are dropped with their history, which is the loss
437
+ * `force` is asking for. Index links are cleaned before the entity row so a
438
+ * crash between the two writes leaves at worst a collectable orphan, never a
439
+ * link to an entity that is already gone.
440
+ */
441
+ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
442
+ const scope = scopeFor({ exec, libraryId })
443
+ if (!entityId || typeof entityId !== 'string') throw new Error('entityId is required')
444
+ const file = entitiesPath(scope.libraryId)
445
+ const removedAuto = []
446
+ const result = withFileLock(file, () => {
447
+ const store = readEntities(scope.libraryId)
448
+ if (!store.entities[entityId]) throw new Error('unknown entity')
449
+ const index = loadPrivateIndex(scope.libraryId)
450
+ let inbound = 0
451
+ for (const entry of Object.values(index.entries || {})) {
452
+ for (const link of entry.links || []) if (link.to === entityId) inbound += 1
453
+ }
454
+ // 关系快照的 key 是 JSON.stringify([fromId, toId])。旧数据、备份恢复或手写
455
+ // 导入都可能带非 JSON key——这里必须和 mergeEntities 同口径地跳过损坏 key,
456
+ // 否则一个坏 key 会让整次删除抛 SyntaxError(RPC 直接失败),而它本来只是
457
+ // 一条读不懂的历史。跳过 = 保留:损坏 key 不参与删除,也就不会被静默丢掉。
458
+ const relationshipKeys = Object.keys(store.relationships || {})
459
+ .filter(key => {
460
+ let endpoints
461
+ try { endpoints = JSON.parse(key) } catch { return false }
462
+ if (!Array.isArray(endpoints) || endpoints.length !== 2) return false
463
+ const [from, to] = endpoints
464
+ return from === entityId || to === entityId
465
+ })
466
+ if ((inbound || relationshipKeys.length) && !force) {
467
+ const parts = []
468
+ if (inbound) parts.push(`${inbound} link(s) point at it`)
469
+ if (relationshipKeys.length) parts.push(`${relationshipKeys.length} relationship snapshot(s) reference it`)
470
+ throw new Error(`entity is still referenced: ${parts.join(' and ')}; remove the links first or pass force to delete the entity with them`)
471
+ }
472
+ let removedLinks = 0
473
+ if (inbound) {
474
+ updatePrivateIndex(scope.libraryId, fresh => {
475
+ for (const [fromId, entry] of Object.entries(fresh.entries)) {
476
+ if (!Array.isArray(entry.links) || !entry.links.some(link => link.to === entityId)) continue
477
+ const kept = entry.links.filter(link => {
478
+ if (link.to !== entityId) return true
479
+ if (link.source === 'auto') {
480
+ removedAuto.push({
481
+ from: fromId, to: entityId, kind: link.kind,
482
+ rule: link.evidence?.rule || 'auto',
483
+ })
484
+ }
485
+ return false
486
+ })
487
+ removedLinks += entry.links.length - kept.length
488
+ entry.links = kept
489
+ }
490
+ })
491
+ }
492
+ for (const key of relationshipKeys) delete store.relationships[key]
493
+ delete store.entities[entityId]
494
+ writeJson(file, store)
495
+ return { entityId, deleted: true, removedLinks, removedRelationships: relationshipKeys.length }
496
+ })
497
+ // Revoking an entity must not let the next consolidation resurrect its auto
498
+ // edges; the exact edge keys go into the suppression table.
499
+ if (removedAuto.length) {
500
+ try { addSuppression(scope.libraryId, removedAuto, { by: 'user' }) } catch (error) {
501
+ warn(`link suppression after entity delete skipped: ${error?.message || error}`)
502
+ }
503
+ }
504
+ return result
505
+ }
506
+
507
+ /**
508
+ * Merge one or more source entities into a target entity inside the same
509
+ * library. This is graph bookkeeping, not a memory write: no memory text or
510
+ * vector is touched, links only change the entity id they point at.
511
+ *
512
+ * Lock order follows deleteEntity exactly: the entity file lock is taken first
513
+ * and the private index lock is nested inside it (withFileLock is re-entrant,
514
+ * and no path takes the index lock before the entity lock, so this order cannot
515
+ * deadlock). The index remap is written *before* the source rows are deleted:
516
+ * a crash between the two writes leaves at worst collectable entities behind,
517
+ * never a surviving link that points at an entity that is already gone.
518
+ *
519
+ * Dedupe after remapping keeps the edge that already pointed at the target (or,
520
+ * with no such edge, the first remapped one), and carries an `auto` marker over
521
+ * from a dropped duplicate so the graph view keeps its badge. Relationship
522
+ * snapshots are re-keyed on the target; an existing target-side snapshot wins
523
+ * and the discarded source key is reported in `relationships.conflicts`.
524
+ */
525
+ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
526
+ const scope = scopeFor({ exec, libraryId })
527
+ if (typeof targetId !== 'string' || !targetId.trim()) throw new Error('targetId is required')
528
+ const target = targetId.trim()
529
+ if (!Array.isArray(sourceIds) || !sourceIds.length) throw new Error('sourceIds must be a non-empty array of entity ids')
530
+ const sources = []
531
+ const seen = new Set()
532
+ for (const raw of sourceIds) {
533
+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('sourceIds must contain entity ids')
534
+ const id = raw.trim()
535
+ if (id === target) throw new Error('target entity cannot be one of its own sources')
536
+ if (seen.has(id)) continue
537
+ seen.add(id)
538
+ sources.push(id)
539
+ }
540
+ if (!sources.length) throw new Error('sourceIds must name at least one entity')
541
+ const file = entitiesPath(scope.libraryId)
542
+ let targetName = target
543
+ let mergedEntity = null
544
+ const result = withFileLock(file, () => {
545
+ const store = readEntities(scope.libraryId)
546
+ const targetEntity = store.entities[target]
547
+ if (!targetEntity || typeof targetEntity !== 'object') throw new Error(`unknown entity: ${target}`)
548
+ targetName = String(targetEntity.name || target)
549
+ const sourceEntities = []
550
+ for (const id of sources) {
551
+ const entity = store.entities[id]
552
+ if (!entity || typeof entity !== 'object') throw new Error(`unknown entity: ${id}`)
553
+ if (entity.kind !== targetEntity.kind) {
554
+ throw new Error(`cannot merge entities of different kinds: ${targetEntity.kind || 'unknown'} vs ${entity.kind || 'unknown'}`)
555
+ }
556
+ sourceEntities.push(entity)
557
+ }
558
+
559
+ // Union of names: the target's own name stays the display name, every
560
+ // source name becomes an alias, and the shared normalizer trims, dedupes
561
+ // and caps at 30. Anything beyond the cap is reported, not silently lost.
562
+ const rawAliases = [
563
+ ...(Array.isArray(targetEntity.aliases) ? targetEntity.aliases : []),
564
+ ...sourceEntities.flatMap(entity => [entity.name, ...(Array.isArray(entity.aliases) ? entity.aliases : [])]),
565
+ ].filter(alias => typeof alias === 'string')
566
+ const aliasUnion = [...new Set(rawAliases.map(alias => alias.trim()).filter(Boolean))]
567
+ const aliases = normalizeAliases(aliasUnion)
568
+ const droppedAliases = aliasUnion.slice(aliases.length)
569
+
570
+ const sourceSet = new Set(sources)
571
+ let remappedLinks = 0
572
+ let duplicateLinks = 0
573
+ updatePrivateIndex(scope.libraryId, index => {
574
+ for (const entry of Object.values(index.entries || {})) {
575
+ const links = Array.isArray(entry.links) ? entry.links : null
576
+ if (!links || !links.some(link => link && sourceSet.has(link.to))) continue
577
+ // Kinds already present on the target win the dedupe; every remapped
578
+ // edge of such a kind is a duplicate, and an `auto` marker survives on
579
+ // the retained edge even when the dropped copy was the auto one.
580
+ const targetKinds = new Set()
581
+ for (const link of links) if (link && link.to === target) targetKinds.add(link.kind)
582
+ const autoKinds = new Set()
583
+ const nextLinks = []
584
+ for (const link of links) {
585
+ if (!link || !sourceSet.has(link.to)) { nextLinks.push(link); continue }
586
+ remappedLinks += 1
587
+ if (targetKinds.has(link.kind)) {
588
+ duplicateLinks += 1
589
+ if (link.source === 'auto') autoKinds.add(link.kind)
590
+ continue
591
+ }
592
+ targetKinds.add(link.kind)
593
+ // An auto mention edge cites the entity it was built for; the merged
594
+ // row inherits those citations so a later refresh can find them.
595
+ const remapped = { ...link, to: target }
596
+ if (remapped.evidence && sourceSet.has(remapped.evidence.entityId)) {
597
+ remapped.evidence = { ...remapped.evidence, entityId: target }
598
+ }
599
+ nextLinks.push(remapped)
600
+ }
601
+ for (const kind of autoKinds) {
602
+ const at = nextLinks.findIndex(item => item && item.to === target && item.kind === kind)
603
+ if (at >= 0 && !nextLinks[at].source) nextLinks[at] = { ...nextLinks[at], source: 'auto' }
604
+ }
605
+ entry.links = nextLinks
606
+ }
607
+ })
608
+
609
+ // Re-key snapshots: replace source endpoints with the target, keep an
610
+ // existing target-side snapshot untouched (it is the history written under
611
+ // the real pair), and drop self-loops a merge would create. The whole
612
+ // snapshot object, history included, moves unchanged.
613
+ const relationships = { moved: 0, conflicts: [] }
614
+ for (const key of Object.keys(store.relationships || {})) {
615
+ const snapshot = store.relationships[key]
616
+ if (!snapshot || typeof snapshot !== 'object') continue
617
+ let endpoints
618
+ try { endpoints = JSON.parse(key) } catch { continue }
619
+ if (!Array.isArray(endpoints) || endpoints.length !== 2) continue
620
+ const [fromId, toId] = endpoints
621
+ if (!sourceSet.has(fromId) && !sourceSet.has(toId)) continue
622
+ const nextFrom = sourceSet.has(fromId) ? target : fromId
623
+ const nextTo = sourceSet.has(toId) ? target : toId
624
+ delete store.relationships[key]
625
+ if (nextFrom === nextTo) {
626
+ relationships.conflicts.push({ key, reason: 'self' })
627
+ continue
628
+ }
629
+ const nextKey = JSON.stringify([nextFrom, nextTo])
630
+ if (store.relationships[nextKey]) {
631
+ relationships.conflicts.push({ key, reason: 'existing-target', keptKey: nextKey })
632
+ continue
633
+ }
634
+ store.relationships[nextKey] = { ...snapshot, fromId: nextFrom, toId: nextTo }
635
+ relationships.moved += 1
636
+ }
637
+
638
+ targetEntity.aliases = aliases
639
+ // A merge is an assertion union: folding a confirmed source into a
640
+ // provisional target confirms the surviving row. An archived target keeps
641
+ // its archived state — the user retired that identity on purpose.
642
+ const confirmedSource = sourceEntities.find(entity => entity.status === 'confirmed')
643
+ if (confirmedSource && (!targetEntity.status || targetEntity.status === 'provisional')) {
644
+ targetEntity.status = 'confirmed'
645
+ targetEntity.confirmedAt = confirmedSource.confirmedAt || stamp()
646
+ targetEntity.confirmedBy = confirmedSource.confirmedBy || 'user'
647
+ if (!targetEntity.origin) targetEntity.origin = confirmedSource.origin || 'user'
648
+ } else if (!ENTITY_STATUS.includes(targetEntity.status)) {
649
+ targetEntity.status = 'provisional'
650
+ }
651
+ targetEntity.updatedAt = stamp()
652
+ for (const id of sources) delete store.entities[id]
653
+ writeJson(file, store)
654
+ // Safety net: a source may have been kept alive only by a snapshot that the
655
+ // merge dropped. The same lock is re-entered, so this cannot race the write
656
+ // above; a prune failure must not turn a completed merge into an error. The
657
+ // target is protected — an unreferenced pair is still a legitimate merge and
658
+ // collecting the row it just merged into would undo it.
659
+ try { pruneOrphanEntities(scope.libraryId, [target]) } catch (error) {
660
+ warn(`orphan entity prune after entity merge skipped: ${error?.message || error}`)
661
+ }
662
+ mergedEntity = targetEntity
663
+ return { targetId: target, merged: sources, aliases, droppedAliases, remappedLinks, duplicateLinks, relationships }
664
+ })
665
+
666
+ // The merged row now owns the union of names; recompute its mention edges so
667
+ // citations point at the surviving entity and new aliases take effect.
668
+ if (mergedEntity?.status === 'confirmed') {
669
+ let suppression = null
670
+ try { suppression = suppressionSet(scope.libraryId) } catch {}
671
+ try {
672
+ result.mentionRefresh = refreshEntityMentions({
673
+ libraryId: scope.libraryId, entity: mergedEntity, suppression, operation: 'auto-link-merge',
674
+ })
675
+ } catch (error) {
676
+ warn(`mention refresh after entity merge skipped: ${error?.message || error}`)
677
+ }
678
+ }
679
+ // The merge is already durable; the activity log is diagnostics and is
680
+ // fail-open by design, so it must never decide the result.
681
+ try {
682
+ record({
683
+ kind: 'write', scope: 'private', libraryId: scope.libraryId, ok: true,
684
+ message: `实体合并:「${targetName}」并入完成(${sources.length} 个来源)`,
685
+ detail: {
686
+ op: 'entity-merge', targetId: target, merged: sources,
687
+ remappedLinks: result.remappedLinks, duplicateLinks: result.duplicateLinks,
688
+ movedRelationships: result.relationships.moved,
689
+ relationshipConflicts: result.relationships.conflicts.length,
690
+ aliases: result.aliases.length, droppedAliases: result.droppedAliases.length,
691
+ },
692
+ refs: [target, ...sources],
693
+ })
694
+ } catch {}
695
+ return result
696
+ }
697
+
698
+ const SUGGEST_LIMIT = 20
699
+
700
+ function compareText(a, b) { return a < b ? -1 : a > b ? 1 : 0 }
701
+
702
+ // Bounded Levenshtein. Row minima never decrease, so once a row's best cell is
703
+ // already above the budget the remaining rows cannot recover; scanning stops.
704
+ function withinEditDistance(a, b, max) {
705
+ if (a === b) return true
706
+ if (Math.abs(a.length - b.length) > max) return false
707
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index)
708
+ for (let i = 1; i <= a.length; i += 1) {
709
+ const current = [i]
710
+ let best = i
711
+ for (let j = 1; j <= b.length; j += 1) {
712
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1
713
+ const value = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost)
714
+ current[j] = value
715
+ if (value < best) best = value
716
+ }
717
+ if (best > max) return false
718
+ previous = current
719
+ }
720
+ return previous[b.length] <= max
721
+ }
722
+
723
+ /** Pure-read helper: does this CJK pair look like one name written two ways? */
724
+ // 同一个人常被写成全称、昵称和单字称呼(顾清欢 / 欢欢 / 晴),三种表面互不包含、
725
+ // 编辑距离又太远,于是各自成节点。只在「一端收尾、另一端起头」的共享字串上提议合并,
726
+ // 并要求较长一侧去掉重叠后还剩两个字——空气/气候这种共用一个字的词对不提议。
727
+ // 永远是候选,由用户点两次确认,绝不自动合并。
728
+ function isNameCorePair(shorter, longer) {
729
+ const cjkOnly = value => /^[\u3400-\u9fff\uf900-\ufaff]+$/u.test(value)
730
+ if (!cjkOnly(shorter) || !cjkOnly(longer)) return false
731
+ if (longer.length > 5) return false
732
+ if (shorter.length === 1) return longer.includes(shorter)
733
+ const overlap = (first, second) => {
734
+ for (let size = Math.min(first.length, second.length); size >= 1; size -= 1) {
735
+ if (first.slice(-size) === second.slice(0, size)) return size
736
+ }
737
+ return 0
738
+ }
739
+ const shared = Math.max(overlap(shorter, longer), overlap(longer, shorter))
740
+ return shared >= 1 && longer.length - shared >= 2
741
+ }
742
+
743
+ const MERGE_REASON_ORDER = { containment: 0, 'edit-distance': 1, 'name-core': 2 }
744
+
745
+ /**
746
+ * Pure read: candidate entity merges inside one library. Never writes and never
747
+ * merges — the caller shows the pair and the user confirms.
748
+ * Names are folded with normalizeEntityName (NFKC / case / whitespace /
749
+ * punctuation), identical folded names are skipped (that duplicate is handled by
750
+ * createEntity or an explicit merge), and only same-kind pairs qualify. A pair
751
+ * is a candidate when the shorter normalized name is contained in the longer one
752
+ * and has >= 2 characters, when both names have >= 3 characters and sit at most
753
+ * 2 edits apart, or (CJK only) when they look like the same name written in full
754
+ * and in short — see isNameCorePair. The longer name is the target (the hub the
755
+ * shorter one folds into); on equal length the older id wins, which keeps the
756
+ * direction stable across calls. Results are sorted by reason then names then ids,
757
+ * and capped at 20.
758
+ */
759
+ export function suggestEntityMerges({ libraryId } = {}) {
760
+ const scope = scopeFor({ libraryId })
761
+ const store = readEntities(scope.libraryId)
762
+ const rows = Object.values(store.entities || {})
763
+ .filter(entity => entity && typeof entity === 'object' && entity.id)
764
+ .map(entity => ({ id: String(entity.id), kind: String(entity.kind || ''), key: normalizeEntityName(entity.name) }))
765
+ .filter(row => row.key)
766
+ const found = []
767
+ for (let i = 0; i < rows.length; i += 1) {
768
+ for (let j = i + 1; j < rows.length; j += 1) {
769
+ const a = rows[i]
770
+ const b = rows[j]
771
+ if (a.kind !== b.kind || a.key === b.key) continue
772
+ const aIsLonger = a.key.length > b.key.length || (a.key.length === b.key.length && a.id < b.id)
773
+ const longer = aIsLonger ? a : b
774
+ const shorter = aIsLonger ? b : a
775
+ let reason = null
776
+ if (shorter.key.length >= 2 && longer.key.includes(shorter.key)) reason = 'containment'
777
+ else if (shorter.key.length >= 3
778
+ && longer.key.length - shorter.key.length <= 2
779
+ && withinEditDistance(shorter.key, longer.key, 2)) reason = 'edit-distance'
780
+ else if (isNameCorePair(shorter.key, longer.key)) reason = 'name-core'
781
+ if (!reason) continue
782
+ found.push({ sourceId: shorter.id, targetId: longer.id, reason, sourceKey: shorter.key, targetKey: longer.key })
783
+ }
784
+ }
785
+ found.sort((x, y) => (MERGE_REASON_ORDER[x.reason] - MERGE_REASON_ORDER[y.reason])
786
+ || compareText(x.targetKey, y.targetKey)
787
+ || compareText(x.sourceKey, y.sourceKey)
788
+ || compareText(x.targetId, y.targetId)
789
+ || compareText(x.sourceId, y.sourceId))
790
+ return { items: found.slice(0, SUGGEST_LIMIT).map(item => ({ sourceId: item.sourceId, targetId: item.targetId, reason: item.reason })) }
791
+ }
792
+
793
+ // Unknown names need a complete source surface. Existing, asserted entities use
794
+ // the broader mention matcher; guessing Chinese word boundaries here would turn
795
+ // title n-grams into identities again. An evidence note is not source evidence.
796
+ function hasCompleteEntityName(name, text) {
797
+ const term = String(name || '').normalize('NFKC').toLowerCase().trim()
798
+ const source = String(text || '').normalize('NFKC').toLowerCase()
799
+ if (!term) return false
800
+ const quoted = /「([^」\n]+)」|『([^』\n]+)』|“([^”\n]+)”|‘([^’\n]+)’|"([^"\n]+)"|'([^'\n]+)'|《([^》\n]+)》/gu
801
+ for (const match of source.matchAll(quoted)) {
802
+ if (match.slice(1).some(value => value !== undefined && value.trim() === term)) return true
803
+ }
804
+ const word = /[\p{L}\p{N}\p{M}_.’'-]/u
805
+ for (let at = source.indexOf(term); at !== -1; at = source.indexOf(term, at + term.length)) {
806
+ const left = source.slice(0, at)
807
+ const right = source.slice(at + term.length)
808
+ const rightBoundary = !right || !word.test([...right][0])
809
+ const leftBoundary = !left || !word.test([...left].at(-1))
810
+ if (leftBoundary && rightBoundary) return true
811
+ if (rightBoundary && /(?:名叫|名字(?:是|叫|为)?|称呼(?:是|叫|为)?|自称|叫|username|nickname)\s*[::=]?\s*$/u.test(left)) return true
812
+ }
813
+ return false
814
+ }
815
+
816
+ function validateLinkArguments(kind, note, confidence) {
817
+ if (!LINK_KINDS.includes(kind)) throw new Error(`link kind must be ${LINK_KINDS.join(', ')}`)
818
+ const reason = String(note || '').trim()
819
+ if (reason.replace(/\s/g, '').length < 8 || reason.length > 500) throw new Error('link note must contain 8-500 characters explaining the evidence')
820
+ if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) throw new Error('link confidence must be between 0 and 1')
821
+ return reason
822
+ }
823
+
824
+ /** Model-named entities stay provisional; manual UI creation is unchanged. */
825
+ export function linkNamedEntity({ exec, libraryId, fromId, entity, kind, note, confidence = 0.7 }) {
826
+ const scope = scopeFor({ exec, libraryId })
827
+ validateLinkArguments(kind, note, confidence)
828
+ const name = String(entity?.name || '').trim()
829
+ const entityKind = entity?.kind || 'person'
830
+ if (!ENTITY_KINDS.includes(entityKind)) throw new Error('invalid entity kind')
831
+ if (!name || name.length > 120 || !normalizeEntityName(name)) throw new Error('entity name must contain 1-120 identifying characters')
832
+ const origin = loadPrivateIndex(scope.libraryId).entries[fromId]
833
+ if (!origin || !allowed(origin, exec)) throw new Error('unknown or inaccessible memory')
834
+ const normalized = normalizeEntityName(name)
835
+ const existing = listEntities({ exec, libraryId: scope.libraryId }).items.find(item => normalizeEntityName(item.name) === normalized
836
+ || (Array.isArray(item.aliases) && item.aliases.some(alias => normalizeEntityName(alias) === normalized)))
837
+ if (existing && existing.kind !== entityKind) throw new Error('entity already exists with a different kind')
838
+ if (kind === 'person' && entityKind !== 'person') throw new Error('person links must target a person entity')
839
+ if (!existing) {
840
+ if ((origin.links || []).length >= 100) throw new Error('memory already has 100 links; review the existing connections first')
841
+ if (!hasCompleteEntityName(name, origin.title) && !hasCompleteEntityName(name, origin.content)) {
842
+ throw new Error('新实体需要来源记忆中的完整名称(complete name);不能用词语碎片、代词推测或关联理由代替。请引用完整称呼,或在界面中手动确认实体。')
843
+ }
844
+ }
845
+ const target = existing || createEntity({ exec, libraryId: scope.libraryId, name, kind: entityKind, status: 'provisional', origin: 'worker' })
846
+ return linkEntries({ exec, libraryId: scope.libraryId, fromId, toId: target.id, kind, note, confidence })
847
+ }
848
+
849
+ /**
850
+ * Write one directed link from a memory to a memory or entity.
851
+ *
852
+ * `source` records who made the edge: 'auto' (private auto-association / entity
853
+ * hub, §5.3–5.5) or 'user'. Anything else is omitted rather than stored, so the
854
+ * field never turns into a free-form label and an old link without it keeps
855
+ * reading as a model/user link. Replacement stays idempotent: the same
856
+ * (to, kind) pair is overwritten in place instead of appended.
857
+ */
858
+ export function linkEntries({ exec, libraryId, fromId, toId, kind, note, confidence = 0.7, source }) {
859
+ const scope = scopeFor({ exec, libraryId })
860
+ const reason = validateLinkArguments(kind, note, confidence)
861
+ if (fromId === toId) throw new Error('a memory cannot link to itself')
862
+ const linkSource = source === 'auto' || source === 'user' ? source : null
863
+ const entities = readEntities(scope.libraryId).entities
864
+ let result
865
+ updatePrivateIndex(scope.libraryId, index => {
866
+ const origin = index.entries[fromId]
867
+ const target = index.entries[toId]
868
+ if (!origin || !allowed(origin, exec) || target && !allowed(target, exec)) throw new Error('unknown or inaccessible memory')
869
+ if (!target && !entities[toId]) throw new Error('link target must be an existing memory or entity')
870
+ if (kind === 'person' && entities[toId]?.kind !== 'person') throw new Error('person links must target a person entity')
871
+ const links = Array.isArray(origin.links) ? origin.links : []
872
+ result = { to: toId, kind, note: reason, confidence, createdAt: stamp() }
873
+ if (linkSource) result.source = linkSource
874
+ const found = links.findIndex(link => link.to === toId && link.kind === kind)
875
+ if (found >= 0) links[found] = result
876
+ else {
877
+ if (links.length >= 100) throw new Error('memory already has 100 links; review the existing connections first')
878
+ links.push(result)
879
+ }
880
+ origin.links = links
881
+ })
882
+ return { from: fromId, ...result }
883
+ }
884
+
885
+ /**
886
+ * Remove every automatic edge in one library. Manual / worker edges are kept
887
+ * byte-for-byte, and each removed (from,to,kind) is suppressed so the
888
+ * deterministic layer cannot recreate it (P6). Used by the graph page's
889
+ * "remove all auto edges" action and by operators cleaning a legacy library.
890
+ */
891
+ export function purgeAutoLinks({ libraryId } = {}) {
892
+ const scope = scopeFor({ libraryId })
893
+ const removed = []
894
+ updatePrivateIndex(scope.libraryId, index => {
895
+ for (const [fromId, entry] of Object.entries(index.entries || {})) {
896
+ if (!Array.isArray(entry.links)) continue
897
+ const kept = []
898
+ for (const link of entry.links) {
899
+ if (link && link.source === 'auto') {
900
+ removed.push({ from: fromId, to: link.to, kind: link.kind, rule: link.evidence?.rule || 'auto' })
901
+ continue
902
+ }
903
+ kept.push(link)
904
+ }
905
+ if (kept.length !== entry.links.length) entry.links = kept
906
+ }
907
+ })
908
+ if (removed.length) {
909
+ try { addSuppression(scope.libraryId, removed, { by: 'user' }) } catch (error) {
910
+ warn(`link suppression after auto purge skipped: ${error?.message || error}`)
911
+ }
912
+ }
913
+ try {
914
+ record({
915
+ kind: 'write', scope: 'private', libraryId: scope.libraryId, ok: true,
916
+ message: `批量删除自动边:${removed.length} 条`,
917
+ detail: { op: 'auto-link-purge', removed: removed.length },
918
+ refs: [...new Set(removed.map(edge => edge.from))].slice(0, 20),
919
+ })
920
+ } catch {}
921
+ return { removed: removed.length }
922
+ }
923
+
924
+ export function unlinkEntry({ libraryId, fromId, toId, kind }) {
925
+ const scope = scopeFor({ libraryId })
926
+ let removed = 0
927
+ const removedAuto = []
928
+ updatePrivateIndex(scope.libraryId, index => {
929
+ const entry = index.entries[fromId]
930
+ if (!entry) throw new Error('unknown memory')
931
+ entry.links = (entry.links || []).filter(link => {
932
+ const drop = link.to === toId && (!kind || link.kind === kind)
933
+ if (drop) {
934
+ removed += 1
935
+ if (link.source === 'auto') {
936
+ removedAuto.push({ from: fromId, to: toId, kind: link.kind, rule: link.evidence?.rule || 'auto' })
937
+ }
938
+ }
939
+ return !drop
940
+ })
941
+ })
942
+ // Deleting an auto edge is a negative label: the deterministic layer must not
943
+ // add it back on the next consolidation.
944
+ if (removedAuto.length) {
945
+ try { addSuppression(scope.libraryId, removedAuto, { by: 'user' }) } catch (error) {
946
+ warn(`link suppression after auto edge removal skipped: ${error?.message || error}`)
947
+ }
948
+ }
949
+ return { removed }
950
+ }
951
+
952
+ // Graph filtering is read-only: normalize legacy stamps without rewriting them.
953
+ // Shared with the global graph so both sides agree on what "same domain" means.
954
+ export function graphDomain(value) { return String(value ?? '').normalize('NFKC').trim().toLowerCase() }
955
+
956
+ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 200, includeOrphans = false, offset, domain }) {
957
+ const scope = scopeFor({ exec, libraryId })
958
+ const index = loadPrivateIndex(scope.libraryId)
959
+ const entities = readEntities(scope.libraryId).entities
960
+ const cap = Math.max(1, Math.min(200, Math.floor(Number(limit) || 200)))
961
+ const hops = Math.max(0, Math.min(2, Math.floor(Number(depth) || 0)))
962
+ const domainFilter = graphDomain(domain)
963
+ const domains = new Set()
964
+ const visible = new Map()
965
+ for (const [id, entry] of Object.entries(index.entries)) {
966
+ if (!allowed(entry, exec)) continue
967
+ const normalized = graphDomain(entry?.domain) || 'general'
968
+ domains.add(normalized)
969
+ if (!domainFilter || normalized === domainFilter) visible.set(id, normalized)
970
+ }
971
+ const paged = !focusId && offset !== undefined
972
+ const start = paged ? Number(offset) : 0
973
+ const pageStart = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0
974
+ const edges = []
975
+ const adjacency = new Map()
976
+ for (const from of visible.keys()) {
977
+ for (const link of index.entries[from].links || []) {
978
+ if (!LINK_KINDS.includes(link.kind)) continue
979
+ // A deleted target gets a placeholder; an inaccessible or other-domain
980
+ // memory gets no hint. Filter before building either edges or adjacency.
981
+ if (index.entries[link.to] && !visible.has(link.to)) continue
982
+ // source is display metadata only ('auto' edges get a badge in the graph
983
+ // view); an older link without the field reports null instead of undefined.
984
+ // evidence.rule / surface / field let the graph say WHY an edge exists.
985
+ // Legacy auto edges written before the rule schema carry no evidence.rule:
986
+ // report them under the stable 'auto' bucket so the WebUI rule filter still
987
+ // works on old data. New writes always record the real rule
988
+ // (auto-link/apply.js) — this fallback is read-only display metadata.
989
+ const edge = {
990
+ from, to: link.to, kind: link.kind, note: link.note,
991
+ confidence: link.confidence ?? 0.7, source: link.source || null,
992
+ rule: link.evidence?.rule || (link.source === 'auto' ? 'auto' : null),
993
+ evidence: link.evidence || null,
994
+ }
995
+ edges.push(edge)
996
+ for (const [a, b] of [[from, link.to], [link.to, from]]) {
997
+ if (!adjacency.has(a)) adjacency.set(a, new Set())
998
+ adjacency.get(a).add(b)
999
+ }
1000
+ }
1001
+ }
1002
+ if (focusId && !visible.has(focusId) && !adjacency.has(focusId) && (!entities[focusId] || sessionIdOf(exec) || domainFilter)) throw new Error('unknown or inaccessible graph focus')
1003
+ const selected = new Set()
1004
+ const candidates = new Set()
1005
+ if (focusId) {
1006
+ let frontier = [focusId]
1007
+ for (let hop = 0; hop <= hops; hop += 1) {
1008
+ const next = []
1009
+ for (const id of frontier) {
1010
+ if (selected.size >= cap || selected.has(id)) continue
1011
+ selected.add(id)
1012
+ if (hop < hops) next.push(...(adjacency.get(id) || []))
1013
+ }
1014
+ frontier = next
1015
+ }
1016
+ } else {
1017
+ // Build every qualifying candidate before slicing. Memories retain their
1018
+ // original order, but later entities can no longer starve across pages.
1019
+ // A domain never includes unrelated orphan entities, even on explicit opt-in.
1020
+ for (const id of [...visible.keys(), ...Object.keys(entities), ...adjacency.keys()]) {
1021
+ if (sessionIdOf(exec) && !visible.has(id) && !adjacency.has(id)) continue
1022
+ if ((!includeOrphans || domainFilter) && entities[id] && !adjacency.has(id)) continue
1023
+ candidates.add(id)
1024
+ }
1025
+ for (const id of [...candidates].slice(pageStart, pageStart + cap)) selected.add(id)
1026
+ }
1027
+ const nodes = [...selected].map(id => {
1028
+ const entry = index.entries[id]
1029
+ const entity = entities[id]
1030
+ return { id, title: entry?.title || entity?.name || '[deleted]', layer: entry?.layer || null,
1031
+ kind: entity?.kind || 'memory', strength: entry ? decayStrength(entry) : 0.5,
1032
+ degree: adjacency.get(id)?.size || 0, missing: !entry && !entity,
1033
+ ...(entry ? { domain: visible.get(id) } : {}),
1034
+ ...(entity ? { status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional' } : {}) }
1035
+ })
1036
+ const remaining = pageStart + selected.size < candidates.size
1037
+ return {
1038
+ nodes, edges: edges.filter(edge => selected.has(edge.from) && (paged ? candidates.has(edge.to) : selected.has(edge.to))),
1039
+ limit: cap, truncated: paged ? remaining : selected.size >= cap, focusId, domains: [...domains].sort(),
1040
+ ...(paged ? { total: candidates.size, nextOffset: remaining ? pageStart + selected.size : null } : {}),
1041
+ }
1042
+ }
1043
+
1044
+ // recallRelations 只需要与指定记忆相连的边,避免每次全库扫描
1045
+ // entries × links。这里按索引文件 mtime/size 建一份内存倒排(任意 id → 与它相连
1046
+ // 的行),索引没变时直接复用;文件读不到(纯内存索引)时本次构建、不缓存。
1047
+ const relationInvertedCache = new Map()
1048
+
1049
+ function relationInvertedIndex(libraryId, index) {
1050
+ let signature = null
1051
+ try {
1052
+ const stat = fs.statSync(path.join(indexDir(), `${libraryId}.json`))
1053
+ signature = `${stat.mtimeMs}:${stat.size}`
1054
+ } catch {}
1055
+ const cached = relationInvertedCache.get(libraryId)
1056
+ if (signature && cached && cached.signature === signature) return cached.inverted
1057
+ const inverted = new Map()
1058
+ const push = (key, row) => {
1059
+ if (!key) return
1060
+ let rows = inverted.get(key)
1061
+ if (!rows) inverted.set(key, rows = [])
1062
+ rows.push(row)
1063
+ }
1064
+ for (const [from, entry] of Object.entries(index?.entries || {})) {
1065
+ for (const link of entry?.links || []) {
1066
+ if (!link || !link.to) continue
1067
+ const row = { from, link }
1068
+ push(from, row)
1069
+ // 自环(link.to === from)只存一份,避免查询看到同一行两次。
1070
+ if (link.to !== from) push(link.to, row)
1071
+ }
1072
+ }
1073
+ if (signature) relationInvertedCache.set(libraryId, { signature, inverted })
1074
+ return inverted
1075
+ }
1076
+
1077
+ export function recallRelations(libraryId, index, id, sessionId) {
1078
+ const store = readEntities(libraryId)
1079
+ const entities = store.entities
1080
+ // 关系衰减是写入侧算的(updateRelationship 每次更新都把 retention_strength 折一次),
1081
+ // 但读取侧从来没用过它——一条半年没人碰过的关系,和一条昨天刚更新的关系,扩展
1082
+ // 时的分量完全一样。这里把「这个实体背后最强的活跃关系还剩多少」带出去,让调用方
1083
+ // 能按它排序和过滤。记忆型目标不归关系衰减管,retention 留 null。
1084
+ const retentionOf = new Map()
1085
+ for (const relationship of Object.values(store.relationships || {})) {
1086
+ const value = Number.isFinite(Number(relationship?.retention_strength)) ? Number(relationship.retention_strength) : 1
1087
+ for (const entityId of [relationship?.fromId, relationship?.toId]) {
1088
+ if (!entityId) continue
1089
+ const current = retentionOf.get(entityId)
1090
+ if (current === undefined || value > current) retentionOf.set(entityId, value)
1091
+ }
1092
+ }
1093
+ const out = []
1094
+ // 倒排只含与 id 相连的行(出边来自 id 自己,入边来自别的条目)。行顺序与旧实现
1095
+ // 的 entries 遍历顺序一致:入边按来源条目顺序、出边在 id 自己的位置。
1096
+ for (const { from, link } of relationInvertedIndex(libraryId, index).get(id) || []) {
1097
+ if (from !== id && link.to !== id) continue
1098
+ const entry = index.entries?.[from]
1099
+ if (!entry) continue
1100
+ if (!isMemoryEligible(entry, { automatic: true }) || !visibleToSession(entry, sessionId)) continue
1101
+ // entity-mention is a fact index, not a relationship: its confidence is 1.0
1102
+ // by construction, and letting it into the top-2 would crowd out the manual /
1103
+ // field-evidence edges this expansion exists to surface.
1104
+ if (link.evidence?.rule === 'entity-mention') continue
1105
+ const to = from === id ? link.to : from
1106
+ const target = index.entries[to]
1107
+ if (target && (!isMemoryEligible(target, { automatic: true }) || !visibleToSession(target, sessionId))) continue
1108
+ // A dangling edge (entry and entity both gone) used to be dropped here
1109
+ // while getGraph rendered the same disk state as a [deleted] placeholder —
1110
+ // the two views disagreed. Both now report the edge and mark it `missing`;
1111
+ // the caller filters if it wants the old silence back.
1112
+ const missing = !target && !entities[to]
1113
+ out.push({
1114
+ id: to,
1115
+ title: target?.title || entities[to]?.name || '[deleted]',
1116
+ kind: link.kind,
1117
+ note: String(link.note || '').slice(0, 80),
1118
+ confidence: link.confidence ?? 0.7,
1119
+ missing,
1120
+ retention: target ? null : (retentionOf.has(to) ? retentionOf.get(to) : 1),
1121
+ })
1122
+ }
1123
+ // Confidence is the write-time claim; retention is how much of it survived. An
1124
+ // entity link pays both, a memory link only pays confidence.
1125
+ const weightOf = (link) => (link.retention == null ? 1 : link.retention) * (Number(link.confidence) || 0)
1126
+ return out.sort((a, b) => weightOf(b) - weightOf(a) || b.confidence - a.confidence).slice(0, 2)
1127
+ }
1128
+
1129
+ export function getRelationship({ exec, libraryId, fromId, toId }) {
1130
+ const scope = scopeFor({ exec, libraryId })
1131
+ const store = readEntities(scope.libraryId)
1132
+ const relationship = store.relationships[JSON.stringify([fromId, toId])]
1133
+ if (!relationship) return { relationship: null }
1134
+ const index = loadPrivateIndex(scope.libraryId)
1135
+ if (sessionIdOf(exec) && relationship.evidenceIds.some(id => !index.entries[id] || !allowed(index.entries[id], exec))) return { relationship: null }
1136
+ return { relationship }
1137
+ }
1138
+
1139
+ export function updateRelationship({ exec, libraryId, fromId, toId, state, evidenceIds, reason }) {
1140
+ const scope = scopeFor({ exec, libraryId })
1141
+ if (fromId === toId) throw new Error('relationship needs two distinct entities')
1142
+ if (!Array.isArray(evidenceIds) || !evidenceIds.length || evidenceIds.length > 20) throw new Error('relationship needs 1-20 evidence memory ids')
1143
+ if (String(reason || '').trim().length < 8) throw new Error('relationship update needs an evidence-based reason')
1144
+ if (!state || typeof state !== 'object' || Array.isArray(state)) throw new Error('relationship state must be an object')
1145
+ const snapshot = {}
1146
+ for (const key of ['familiarity', 'trust', 'warmth']) {
1147
+ if (state[key] === undefined || state[key] === null) { snapshot[key] = null; continue }
1148
+ if (!Number.isFinite(state[key]) || state[key] < 0 || state[key] > 1) throw new Error(`relationship ${key} must be 0-1 or null (unknown)`)
1149
+ snapshot[key] = state[key]
1150
+ }
1151
+ for (const key of ['boundaries', 'callbacks', 'openPromises']) {
1152
+ const values = state[key] || []
1153
+ if (!Array.isArray(values) || values.length > 20 || values.some(value => typeof value !== 'string' || value.length > 300)) throw new Error(`invalid relationship ${key}`)
1154
+ snapshot[key] = values.slice()
1155
+ }
1156
+ const index = loadPrivateIndex(scope.libraryId)
1157
+ if (evidenceIds.some(id => !index.entries[id] || !allowed(index.entries[id], exec))) throw new Error('relationship evidence is not visible in this conversation')
1158
+ const file = entitiesPath(scope.libraryId)
1159
+ return withFileLock(file, () => {
1160
+ const store = readEntities(scope.libraryId)
1161
+ if (!store.entities[fromId] || !store.entities[toId]) throw new Error('relationship endpoints must be existing entities')
1162
+ const key = JSON.stringify([fromId, toId])
1163
+ const previous = store.relationships[key]
1164
+ const at = stamp()
1165
+ const history = [...(previous?.history || [])]
1166
+ if (previous) {
1167
+ history.push({
1168
+ state: previous.state, evidenceIds: previous.evidenceIds, reason: previous.reason,
1169
+ validFrom: previous.validFrom, validTo: at,
1170
+ retention_strength: previous.retention_strength ?? 1,
1171
+ })
1172
+ }
1173
+ if (history.length > RELATIONSHIP_HISTORY_LIMIT) history.splice(0, history.length - RELATIONSHIP_HISTORY_LIMIT)
1174
+ const decayed = relationshipRetentionAt(
1175
+ previous?.retention_strength ?? 1,
1176
+ hoursBetween(previous?.last_access_at || previous?.validFrom, at),
1177
+ )
1178
+ const retention = previous
1179
+ ? accessRelationship(decayed, { lastAccessAt: previous.last_access_at, now: Date.parse(at) })
1180
+ : 1
1181
+ const relationship = {
1182
+ fromId, toId, state: snapshot, evidenceIds: [...new Set(evidenceIds)],
1183
+ reason: String(reason).trim().slice(0, 1000), validFrom: previous?.validFrom || at, revision: (previous?.revision || 0) + 1,
1184
+ retention_strength: retention,
1185
+ last_access_at: at,
1186
+ next_review_at: new Date(Date.parse(at) + RELATIONSHIP_HALF_LIFE_HOURS * 3_600_000).toISOString(),
1187
+ history,
1188
+ }
1189
+ store.relationships[key] = relationship
1190
+ writeJson(file, store)
1191
+ return { relationship }
1192
+ })
1193
+ }