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.
- package/AGENTS.md +108 -110
- package/CHANGELOG.md +169 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +79 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1015 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1586 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +124 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1521 -1429
package/lib/state.js
CHANGED
|
@@ -1,1928 +1,1948 @@
|
|
|
1
|
-
import fs from 'node:fs'
|
|
2
|
-
import path from 'node:path'
|
|
3
|
-
import crypto from 'node:crypto'
|
|
4
|
-
import {
|
|
5
|
-
dataDir, librariesDir, indexDir, backupsDir, memoryRefKey,
|
|
6
|
-
ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
|
|
7
|
-
} from './paths.js'
|
|
8
|
-
import {
|
|
9
|
-
createBackup, deleteBackupEntry, listBackupEntries, restoreFromBackup,
|
|
10
|
-
} from './backup.js'
|
|
11
|
-
import { migrateIndexVisibility } from './visibility.js'
|
|
12
|
-
import { memuDbFor, memuGlobalDbFor, removeActiveLibrary } from './vector-profile.js'
|
|
13
|
-
import { normalizeEmotion, derivedValence } from './mood.js'
|
|
14
|
-
import { localCalendarDay } from './temporal.js'
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
//
|
|
40
|
-
//
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
//
|
|
54
|
-
//
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
//
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
//
|
|
65
|
-
//
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
// <memory-freshness
|
|
69
|
-
//
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
//
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
//
|
|
77
|
-
//
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
//
|
|
84
|
-
//
|
|
85
|
-
//
|
|
86
|
-
//
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
//
|
|
90
|
-
//
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
//
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
//
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
// '
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
//
|
|
136
|
-
//
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
//
|
|
143
|
-
// (
|
|
144
|
-
//
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
//
|
|
160
|
-
//
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
//
|
|
164
|
-
//
|
|
165
|
-
|
|
166
|
-
//
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
//
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
//
|
|
173
|
-
//
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
//
|
|
219
|
-
//
|
|
220
|
-
//
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
let
|
|
224
|
-
let
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
//
|
|
238
|
-
// be
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
//
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
// (writing defaults
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
//
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
//
|
|
294
|
-
//
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
flushTimer
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
//
|
|
323
|
-
//
|
|
324
|
-
//
|
|
325
|
-
//
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
if (
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
//
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
//
|
|
359
|
-
//
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
if (
|
|
363
|
-
|
|
364
|
-
//
|
|
365
|
-
//
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
cache.
|
|
378
|
-
cache.
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
*
|
|
392
|
-
*
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
//
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
const
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
if (
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
//
|
|
463
|
-
//
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
//
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
//
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
//
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
//
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
if (
|
|
510
|
-
if (key === '
|
|
511
|
-
if (key === '
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
*
|
|
526
|
-
*
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
const
|
|
531
|
-
const
|
|
532
|
-
const
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
seen.
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
if (value
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
const
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
//
|
|
560
|
-
//
|
|
561
|
-
//
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
*
|
|
576
|
-
*
|
|
577
|
-
*
|
|
578
|
-
*
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
const
|
|
583
|
-
const
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
//
|
|
613
|
-
//
|
|
614
|
-
//
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
//
|
|
631
|
-
//
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
if (
|
|
644
|
-
return '
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
.
|
|
652
|
-
.
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
.
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
//
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
//
|
|
683
|
-
//
|
|
684
|
-
//
|
|
685
|
-
//
|
|
686
|
-
//
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
if (state.libraries[id]
|
|
692
|
-
|
|
693
|
-
//
|
|
694
|
-
//
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
const
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
const
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
if (
|
|
719
|
-
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
const
|
|
739
|
-
const
|
|
740
|
-
|
|
741
|
-
state.libraries[id]
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
const
|
|
755
|
-
const
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
//
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
found[1].
|
|
763
|
-
found[1].
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
}
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
state.libraries[id]
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
//
|
|
781
|
-
//
|
|
782
|
-
//
|
|
783
|
-
//
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
const
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
binding.
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
//
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
lib.
|
|
805
|
-
lib.
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
lib.
|
|
812
|
-
lib.
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
*
|
|
823
|
-
*
|
|
824
|
-
*
|
|
825
|
-
*
|
|
826
|
-
*
|
|
827
|
-
*
|
|
828
|
-
*
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
const
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
if (!
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
*
|
|
854
|
-
*
|
|
855
|
-
*
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
if (
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
state.libraries[id].
|
|
872
|
-
state
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
//
|
|
879
|
-
//
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
lib.
|
|
887
|
-
lib.
|
|
888
|
-
lib.
|
|
889
|
-
|
|
890
|
-
lib
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
const
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
//
|
|
925
|
-
//
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
//
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
const
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
//
|
|
959
|
-
//
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
const
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
//
|
|
968
|
-
//
|
|
969
|
-
//
|
|
970
|
-
//
|
|
971
|
-
//
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
const
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
//
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
const
|
|
1017
|
-
|
|
1018
|
-
const
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
const
|
|
1039
|
-
if (
|
|
1040
|
-
const
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
const
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
binding.
|
|
1062
|
-
binding.
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
for (const
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
binding.pendingInjections
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
const
|
|
1160
|
-
if (
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
]
|
|
1170
|
-
binding
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
binding.
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
binding.
|
|
1181
|
-
|
|
1182
|
-
binding.
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
binding
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
}
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
const
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
const
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
export function
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
return
|
|
1301
|
-
}
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
return
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
//
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
const
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
}
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
}
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
if (
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
}
|
|
1488
|
-
if (
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
delete binding.
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
}
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
function
|
|
1550
|
-
|
|
1551
|
-
return
|
|
1552
|
-
}
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
//
|
|
1562
|
-
//
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
}
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
//
|
|
1580
|
-
//
|
|
1581
|
-
//
|
|
1582
|
-
//
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
const
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
const
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
const
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
function
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
}
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
}
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
&&
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
*/
|
|
1747
|
-
export function
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
}
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
}
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
*/
|
|
1842
|
-
export
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
const
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
if (
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import {
|
|
5
|
+
dataDir, librariesDir, indexDir, backupsDir, memoryRefKey,
|
|
6
|
+
ensureDir, readJson, readFailure, readFailuresUnder, writeJson, withFileLock, assertJsonShape, warn, stamp, shortHash, libraryIdForScope, isSafeId,
|
|
7
|
+
} from './paths.js'
|
|
8
|
+
import {
|
|
9
|
+
createBackup, deleteBackupEntry, listBackupEntries, restoreFromBackup,
|
|
10
|
+
} from './backup.js'
|
|
11
|
+
import { migrateIndexVisibility } from './visibility.js'
|
|
12
|
+
import { memuDbFor, memuGlobalDbFor, removeActiveLibrary } from './vector-profile.js'
|
|
13
|
+
import { normalizeEmotion, derivedValence } from './mood.js'
|
|
14
|
+
import { localCalendarDay } from './temporal.js'
|
|
15
|
+
import { normalizeMemoryContext } from './context.js'
|
|
16
|
+
|
|
17
|
+
const STATE_FILE = () => path.join(dataDir(), 'state.json')
|
|
18
|
+
const GLOBAL_DB = () => path.join(dataDir(), 'global.sqlite3')
|
|
19
|
+
const GLOBAL_INDEX = () => path.join(indexDir(), 'global.json')
|
|
20
|
+
|
|
21
|
+
// Observable outcome of the last backup action; see listBackupEntries().
|
|
22
|
+
let lastBackupReport = null
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_SETTINGS = {
|
|
25
|
+
sidebarSettings: false,
|
|
26
|
+
visionCaptionEnabled: true,
|
|
27
|
+
// Only these named tools may carry the explicit inbound protocol in model text.
|
|
28
|
+
// Producer-owned tool meta is the preferred integration and needs no allowlist.
|
|
29
|
+
inboundToolNames: [],
|
|
30
|
+
autoInject: 'smart',
|
|
31
|
+
// 自动关联(DESIGN §6.4):'suggest' 只出候选、不写任何边(迁移期默认),
|
|
32
|
+
// 'deterministic' 只写由已确认实体或字段证据推出的确定性边,'off' 完全关闭。
|
|
33
|
+
// allowWorkerAssertion 是 v3 的预留开关(worker 确认实体),本版不读取。
|
|
34
|
+
autoLinkMode: 'suggest',
|
|
35
|
+
allowWorkerAssertion: false,
|
|
36
|
+
// These defaults are tuned for high-density chat — a QQ-style group where many
|
|
37
|
+
// short messages arrive per minute, in fragments rather than sentences, and the
|
|
38
|
+
// topic drifts every few of them. Under that cadence the failure mode is not
|
|
39
|
+
// "too little memory", it is noise: a per-turn block sized for paragraph-long
|
|
40
|
+
// prompts drowns the conversation it was meant to help. So the per-turn budgets
|
|
41
|
+
// are small, and the windows that stop repetition are measured in many turns.
|
|
42
|
+
privateTopK: 5,
|
|
43
|
+
globalTopK: 5,
|
|
44
|
+
// Cross-library recall: merge private candidates from other libraries that use
|
|
45
|
+
// the same memory domain. Reading across folders changes the isolation boundary,
|
|
46
|
+
// so it is opt-in; writes still target the bound library only.
|
|
47
|
+
crossLibraryRecall: false,
|
|
48
|
+
anchorTokens: 800,
|
|
49
|
+
// 800 tokens for one recall block. A dense chat calls recall on almost every
|
|
50
|
+
// message, so the injected block has to stay clearly smaller than the message it
|
|
51
|
+
// serves. This is the recall budget, not the whole plugin-message ceiling.
|
|
52
|
+
turnTokens: 800,
|
|
53
|
+
// Whole plugin-message ceiling: anchor + recall + optional cue/texture. It must
|
|
54
|
+
// be at least the sum of the sub-budgets the user wants to allow; the default leaves
|
|
55
|
+
// room for the default anchor and recall blocks.
|
|
56
|
+
injectionTotalTokens: 2000,
|
|
57
|
+
relevanceThreshold: 0.4,
|
|
58
|
+
// 16 turns is a couple of minutes of group traffic. The old 8 expired inside a
|
|
59
|
+
// single burst, so the same entry came back every minute or two.
|
|
60
|
+
dedupeTurns: 16,
|
|
61
|
+
// Every 6 turns instead of 3: the global layer is cross-conversation and drags
|
|
62
|
+
// foreign context in, and three turns of dense chat is nothing at all.
|
|
63
|
+
globalEveryNTurns: 6,
|
|
64
|
+
// 6 characters is about one short CJK clause. 12 skipped most of what a group
|
|
65
|
+
// chat actually says — recall was off in exactly the conversations that wanted
|
|
66
|
+
// it. "嗯" / "好" / "收到" (2-3 chars) still skip.
|
|
67
|
+
minUserChars: 6,
|
|
68
|
+
// When recall includes potentially stale memories, append a <memory-freshness> hint
|
|
69
|
+
// asking models with search tools to verify them, or to say when they cannot. Enabled
|
|
70
|
+
// by default; freshnessDays is the sole age threshold.
|
|
71
|
+
freshnessHint: true,
|
|
72
|
+
freshnessDays: 30,
|
|
73
|
+
// Keep the always-on layer tight: dense chat generates many small candidates,
|
|
74
|
+
// and 16 pins would eat the anchor budget before the anchor starts.
|
|
75
|
+
mustRememberCap: 12,
|
|
76
|
+
// Short-term layer: a memory that only has to survive the arc of one
|
|
77
|
+
// conversation. It expires rather than being deleted, so the idle
|
|
78
|
+
// consolidation pass still gets to promote it to long_term before it goes. 72h
|
|
79
|
+
// spans "we talked about this over the weekend"; 0 disables the layer, and a
|
|
80
|
+
// write with layer=short_term is then refused instead of silently becoming
|
|
81
|
+
// permanent.
|
|
82
|
+
shortTermTtlHours: 72,
|
|
83
|
+
// Prompt pages beyond 通用. Each one owns a set of `<key>.<domain>.md` overrides
|
|
84
|
+
// and can be assigned to a conversation, so the list is data, not code.
|
|
85
|
+
// All shipped pages stay enabled; a new conversation starts on RP via the
|
|
86
|
+
// binding's domainOverride. Every enabled domain is also offered by the session
|
|
87
|
+
// picker, so these two lists cannot drift apart.
|
|
88
|
+
promptDomains: ['rp', 'coding', 'mixed'],
|
|
89
|
+
// Unpin is the model's own call (see memory.js privateUnpin). These two are the
|
|
90
|
+
// guardrails that replaced the human marker: a per-conversation quota and a
|
|
91
|
+
// cooldown, both small on purpose.
|
|
92
|
+
unpinBudgetPerSession: 2,
|
|
93
|
+
unpinCooldownMinutes: 3,
|
|
94
|
+
// Rolled once per user turn: at dense cadence 5% means a cue every ~20 turns,
|
|
95
|
+
// which reads as constant interruption. 2% keeps it rare.
|
|
96
|
+
randomCueChance: 0.02,
|
|
97
|
+
newSessionPromptDismissed: false,
|
|
98
|
+
// What "remember my choice" stores: off | auto | both.
|
|
99
|
+
newSessionDefault: 'both',
|
|
100
|
+
curatorModel: null,
|
|
101
|
+
autoInstallEngine: true,
|
|
102
|
+
pipIndexes: [],
|
|
103
|
+
// Fresh installs start with the plugin fully alive: auto-install, the
|
|
104
|
+
// new-session prompt, domestic texture, and idle consolidation are all on.
|
|
105
|
+
// These stay ordinary switches, and an existing saved choice is preserved.
|
|
106
|
+
sleepConsolidation: true,
|
|
107
|
+
// Group chat arrives in bursts, but a burst is seconds apart and the per-turn
|
|
108
|
+
// timestamps already cover that. Two idle minutes still separates "reading a
|
|
109
|
+
// diff / thinking" from "gone", and keeps the per-run window small.
|
|
110
|
+
sleepAfterIdleMinutes: 2,
|
|
111
|
+
// 主动记忆:分数门槛、饥饿阈值(空闲超过它无条件检查)、两种抑制冷却(分钟;整理冷却默认 0,
|
|
112
|
+
// 薄证据的重复 fork 由评分拦截,只有用户显式配置才启用硬冷却)。
|
|
113
|
+
activeMemoryMinScore: 0.8,
|
|
114
|
+
activeMemoryStarvationMinutes: 15,
|
|
115
|
+
activeMemoryCooldownMinutes: 0,
|
|
116
|
+
activeMemoryRecallCooldownMinutes: 15,
|
|
117
|
+
// 全局提炼的审核放行(§4.10):'auto' 只暂扣冲突、缺证据与高风险改写;
|
|
118
|
+
// 'review-all' 把全部内容操作送进复核。硬门在两档下都生效。
|
|
119
|
+
curatorReviewMode: 'auto',
|
|
120
|
+
autoCurateEveryHours: 0,
|
|
121
|
+
autoCurateSessionLimit: 8,
|
|
122
|
+
// 'local' keeps every memory on this machine; 'cloud' hands MemU's own backend
|
|
123
|
+
// the storage, which is the vendor path and off by default.
|
|
124
|
+
memoryMode: 'local',
|
|
125
|
+
// Who turns a conversation into memory. 'agent' means the conversation's own
|
|
126
|
+
// agent writes and summarizes into the JSON index, with no MemU engine and no
|
|
127
|
+
// embedding API. 'api' hands the work to the configured remote MemU service.
|
|
128
|
+
memoryBackend: 'agent',
|
|
129
|
+
vectorSource: 'local',
|
|
130
|
+
habitsInjection: true,
|
|
131
|
+
// 一次性的带日期承诺过期之后的复提间隔(天)。带日期 + open_loop 的过期条目不走
|
|
132
|
+
// 3 天年龄门槛,也不会因为“提过一次”永久沉默;它按这个间隔重复,直到被关闭或归档。
|
|
133
|
+
// 它和普通 3 天腿共用每回合 limit 1,dated 过期腿优先。
|
|
134
|
+
openLoopRemindDays: 7,
|
|
135
|
+
// Scheduled anniversary wake-ups start a host turn in the bound session, so they are
|
|
136
|
+
// disabled by default and require explicit user opt-in. salientWakeHour is local
|
|
137
|
+
// wall-clock time (HH:mm); an empty salientWakeTimeZone follows the system, while a
|
|
138
|
+
// non-empty value must be a valid IANA time zone.
|
|
139
|
+
salientWake: 'off',
|
|
140
|
+
salientWakeHour: '09:00',
|
|
141
|
+
salientWakeTimeZone: '',
|
|
142
|
+
// 整理 fork 的模型选择(三模式)。'inherit' 沿用父会话的 provider/model;'host' 用
|
|
143
|
+
// consolidationModel("<provider>/<model>",同 curatorModel 的解析口径)指名宿主已
|
|
144
|
+
// 激活的 route;'custom' 用 consolidationCustom* 在宿主 llm 注册表挂本插件私有 route
|
|
145
|
+
// (lib/fork-model.js CONSOLIDATION_CUSTOM_ROUTE)。fork 的 AgentOptions 没有
|
|
146
|
+
// baseURL/apiKey 通道,自定义端点只能走注册 route,所以 custom 的连接四件套存在这里。
|
|
147
|
+
// apiKey 落盘在 state.json(与 ~/.memu/config.env 的 0600 同一信任域),但任何 RPC
|
|
148
|
+
// 回包只给 has/tail 打码视图——rpc.js 的 redactConsolidationSettings。
|
|
149
|
+
consolidationModelMode: 'inherit',
|
|
150
|
+
consolidationModel: null,
|
|
151
|
+
// 1.3.1:整理 fork 的思考强度独立于父会话。'inherit' 保持旧行为;'off' /
|
|
152
|
+
// 'medium' / 'low' / 'high' 直接覆盖,用于成本/质量的 A/B。
|
|
153
|
+
consolidationReasoningEffort: 'medium',
|
|
154
|
+
consolidationCustomBaseURL: '',
|
|
155
|
+
consolidationCustomApiKey: '',
|
|
156
|
+
consolidationCustomModel: '',
|
|
157
|
+
consolidationCustomApi: 'openai-completions',
|
|
158
|
+
// Incremental turn log. 'on' (default) persists each turn and provides cached context
|
|
159
|
+
// for the persistent consolidation worker; it is not the completion ledger. When 'off',
|
|
160
|
+
// input falls back to condenseEvents.
|
|
161
|
+
consolidationTurnLog: 'on',
|
|
162
|
+
// Consolidation executor: 'fork' (default) starts a fresh fork per window; 'worker'
|
|
163
|
+
// reuses a persistent worker across windows. Switching back to 'fork' requires no data
|
|
164
|
+
// migration; the turn log is a cache and the ledger remains authoritative.
|
|
165
|
+
consolidationRunner: 'fork',
|
|
166
|
+
// Worker tool-log detail: 'none' stores no tool rows, 'errors' stores error results,
|
|
167
|
+
// and 'summary' stores one summary row.
|
|
168
|
+
consolidationTurnLogTools: 'none',
|
|
169
|
+
// A positive age marks cleanup candidates; deletion always needs a user action.
|
|
170
|
+
purgeArchivedAfterDays: 0,
|
|
171
|
+
// 升级后的一次性实体碎片自愈(lib/index.js startEntityRepairPass)。默认开,但它**只**合并
|
|
172
|
+
// 可证明的那一类(窗口片段重建出正文里出现过的完整名);"只是相似"的候选永远等人工确认。
|
|
173
|
+
// 关掉它 = 连可证明的也不动,全部留在诊断页的手动按钮上。写入前一律先备份。
|
|
174
|
+
autoRepairEntityFragments: true,
|
|
175
|
+
// 回合中途补充召回(inject.js midTurnPolicy):默认开。这些键必须注册在这里——
|
|
176
|
+
// updateSettings 对 DEFAULT_SETTINGS 之外的键静默丢弃,文档里「midTurnRecall: false
|
|
177
|
+
// 可关」的承诺只有落了默认值与白名单才成立。阈值口径见 docs/memory-semantics.md §8.4。
|
|
178
|
+
midTurnRecall: true,
|
|
179
|
+
midTurnMinSteps: 4,
|
|
180
|
+
midTurnMinUnits: 3,
|
|
181
|
+
midTurnMinChars: 6000,
|
|
182
|
+
midTurnMaxPerTurn: 2,
|
|
183
|
+
midTurnCooldownMs: 60000,
|
|
184
|
+
midTurnTokens: 400,
|
|
185
|
+
midTurnFullUnits: 6,
|
|
186
|
+
midTurnFullChars: 15000,
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function defaultState() {
|
|
190
|
+
return {
|
|
191
|
+
version: 1,
|
|
192
|
+
settings: { ...DEFAULT_SETTINGS },
|
|
193
|
+
libraries: {},
|
|
194
|
+
sessions: {},
|
|
195
|
+
// Per-folder memory switches. Keyed by the normalized scope key (the same key
|
|
196
|
+
// a library uses), so a folder keeps its choice even before it has a library.
|
|
197
|
+
workspacePolicies: {},
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function mergeState(raw) {
|
|
202
|
+
const base = defaultState()
|
|
203
|
+
if (!raw || typeof raw !== 'object') return base
|
|
204
|
+
const rawSettings = raw.settings && typeof raw.settings === 'object' ? raw.settings : {}
|
|
205
|
+
const legacyVectorSource = rawSettings.vectorSource === 'api' || rawSettings.vectorSource === 'local'
|
|
206
|
+
? rawSettings.vectorSource
|
|
207
|
+
: (rawSettings.memoryMode === 'cloud' ? 'api' : 'local')
|
|
208
|
+
return {
|
|
209
|
+
...base,
|
|
210
|
+
...raw,
|
|
211
|
+
settings: { ...base.settings, ...rawSettings, vectorSource: legacyVectorSource },
|
|
212
|
+
libraries: raw.libraries && typeof raw.libraries === 'object' ? raw.libraries : {},
|
|
213
|
+
sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
|
|
214
|
+
workspacePolicies: raw.workspacePolicies && typeof raw.workspacePolicies === 'object' ? raw.workspacePolicies : {},
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Bookkeeping writes are coalesced to avoid repeated full state.json rewrites. Memory
|
|
219
|
+
// indexes deliberately bypass this cache: losing an index entry is not equivalent to
|
|
220
|
+
// losing injection bookkeeping. Validate the cache against mtime and size so an external
|
|
221
|
+
// writer, such as a backup or another profile, is never silently shadowed.
|
|
222
|
+
const FLUSH_MS = 50
|
|
223
|
+
let cache = null
|
|
224
|
+
let dirty = false
|
|
225
|
+
let flushTimer = null
|
|
226
|
+
|
|
227
|
+
function statOf(file) {
|
|
228
|
+
try { return fs.statSync(file) } catch { return null }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function adoptCache(state, fromReadFailure = false, base = null) {
|
|
232
|
+
const stat = statOf(STATE_FILE())
|
|
233
|
+
cache = {
|
|
234
|
+
dir: dataDir(),
|
|
235
|
+
state,
|
|
236
|
+
base: structuredClone(base || state),
|
|
237
|
+
// True when this cache content is a *fallback* built from defaults because
|
|
238
|
+
// the file could not be read — not the on-disk truth. A fallback must never
|
|
239
|
+
// be written back: that would replace real bindings/libraries with defaults.
|
|
240
|
+
fromReadFailure,
|
|
241
|
+
mtimeMs: stat ? stat.mtimeMs : 0,
|
|
242
|
+
size: stat ? stat.size : -1,
|
|
243
|
+
}
|
|
244
|
+
return state
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function loadState() {
|
|
248
|
+
const dir = dataDir()
|
|
249
|
+
if (cache && cache.dir === dir) {
|
|
250
|
+
if (dirty) return cache.state
|
|
251
|
+
const stat = statOf(STATE_FILE())
|
|
252
|
+
if (!stat) {
|
|
253
|
+
// Gone from disk while we hold a good copy: keep it and put it back.
|
|
254
|
+
dirty = true
|
|
255
|
+
scheduleFlush()
|
|
256
|
+
return cache.state
|
|
257
|
+
}
|
|
258
|
+
// A fallback cache never satisfies the mtime check: it is not the on-disk
|
|
259
|
+
// truth, so keep re-reading until the file reads cleanly again.
|
|
260
|
+
if (!cache.fromReadFailure && stat.mtimeMs === cache.mtimeMs && stat.size === cache.size) return cache.state
|
|
261
|
+
}
|
|
262
|
+
dirty = false
|
|
263
|
+
let raw = readJson(STATE_FILE(), null)
|
|
264
|
+
if (raw !== null) raw = assertJsonShape(STATE_FILE(), raw, value => value && typeof value === 'object' && !Array.isArray(value)
|
|
265
|
+
&& ['libraries', 'sessions', 'settings', 'workspacePolicies'].every(key => value[key] === undefined || value[key] && typeof value[key] === 'object' && !Array.isArray(value[key])))
|
|
266
|
+
// Distinguish "no file yet" (writing defaults is harmless) from "read failed"
|
|
267
|
+
// (writing defaults would destroy the real state still on disk).
|
|
268
|
+
const failed = readFailure(STATE_FILE()) !== null
|
|
269
|
+
return adoptCache(mergeState(raw), failed)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function saveState(state) {
|
|
273
|
+
// Carry the fallback marker over: saving new content does not make a
|
|
274
|
+
// previously-failed read trustworthy.
|
|
275
|
+
const previous = cache?.dir === dataDir() ? cache : null
|
|
276
|
+
adoptCache(state, previous?.fromReadFailure === true, previous?.base)
|
|
277
|
+
if (previous) { cache.mtimeMs = previous.mtimeMs; cache.size = previous.size }
|
|
278
|
+
dirty = true
|
|
279
|
+
bumpMemoryRevision()
|
|
280
|
+
flushState()
|
|
281
|
+
return state
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function updateState(fn) {
|
|
285
|
+
const state = structuredClone(loadState())
|
|
286
|
+
const next = fn(state) || state
|
|
287
|
+
if (cache) cache.state = next
|
|
288
|
+
dirty = true
|
|
289
|
+
scheduleFlush()
|
|
290
|
+
return next
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Codes that mean "the store was momentarily unavailable", not "this write can never
|
|
294
|
+
// succeed". Only these are re-armed; a read-only filesystem or a corrupt path would
|
|
295
|
+
// otherwise retry forever at FLUSH_MS.
|
|
296
|
+
const RETRYABLE_FLUSH_CODES = ['DSH_MEMU_STORE_BUSY', 'EPERM', 'EBUSY', 'EACCES']
|
|
297
|
+
|
|
298
|
+
function scheduleFlush() {
|
|
299
|
+
if (flushTimer) return
|
|
300
|
+
flushTimer = setTimeout(() => {
|
|
301
|
+
flushTimer = null
|
|
302
|
+
try {
|
|
303
|
+
flushState()
|
|
304
|
+
} catch (error) {
|
|
305
|
+
warnSinkSafe(`state flush failed: ${error?.message || error}`)
|
|
306
|
+
if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
|
|
307
|
+
}
|
|
308
|
+
}, FLUSH_MS)
|
|
309
|
+
flushTimer.unref?.()
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Writes any pending bookkeeping change now. Safe to call when clean. */
|
|
313
|
+
export function flushState() {
|
|
314
|
+
if (flushTimer) {
|
|
315
|
+
clearTimeout(flushTimer)
|
|
316
|
+
flushTimer = null
|
|
317
|
+
}
|
|
318
|
+
if (!dirty || !cache) return
|
|
319
|
+
try {
|
|
320
|
+
return withFileLock(STATE_FILE(), flushStateLocked)
|
|
321
|
+
} catch (error) {
|
|
322
|
+
// S-10: the timer was already cleared above, so a failed flush used to leave the
|
|
323
|
+
// pending bookkeeping dirty with nothing scheduled — one busy lock was enough to
|
|
324
|
+
// strand inbound pending / lastRecallError / sleepRetryAt in memory until the next
|
|
325
|
+
// unrelated write (or a crash). Re-arm before rethrowing so the batch is retried;
|
|
326
|
+
// the caller still sees the error.
|
|
327
|
+
warnSinkSafe(`state flush failed: ${error?.message || error}`)
|
|
328
|
+
if (RETRYABLE_FLUSH_CODES.includes(error?.code)) scheduleFlush()
|
|
329
|
+
throw error
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function mergeChanges(base, local, disk) {
|
|
334
|
+
if (JSON.stringify(base) === JSON.stringify(local)) return structuredClone(disk)
|
|
335
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
336
|
+
if (!object(base) || !object(local) || !object(disk)) return structuredClone(local)
|
|
337
|
+
const next = { ...disk }
|
|
338
|
+
for (const key of new Set([...Object.keys(base), ...Object.keys(local)])) {
|
|
339
|
+
if (JSON.stringify(base[key]) === JSON.stringify(local[key])) continue
|
|
340
|
+
if (!Object.hasOwn(local, key)) delete next[key]
|
|
341
|
+
else next[key] = mergeChanges(base[key], local[key], disk[key])
|
|
342
|
+
}
|
|
343
|
+
return next
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function flushStateLocked() {
|
|
347
|
+
if (!cache.fromReadFailure) {
|
|
348
|
+
// A read can race another process's rename before its post-read stat.
|
|
349
|
+
// Always merge the disk truth under the lock; mtime/size is not a transaction.
|
|
350
|
+
const disk = readJson(STATE_FILE(), null)
|
|
351
|
+
if (readFailure(STATE_FILE())) throw new Error('state.json changed but could not be read; pending changes retained')
|
|
352
|
+
cache.state = mergeChanges(cache.base, cache.state, mergeState(disk))
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
writeJson(STATE_FILE(), cache.state)
|
|
356
|
+
} catch (error) {
|
|
357
|
+
if (error?.code !== 'dsh-memu-memory/read-failed') throw error
|
|
358
|
+
// The write barrier is set only while the file is unreadable. Re-probe: a
|
|
359
|
+
// successful read clears it, so a transient EBUSY does not freeze the plugin
|
|
360
|
+
// until restart. If it is still unreadable this write throws again.
|
|
361
|
+
const diskRaw = readJson(STATE_FILE(), null)
|
|
362
|
+
if (readFailure(STATE_FILE()) !== null) throw error
|
|
363
|
+
if (cache.fromReadFailure) {
|
|
364
|
+
// The pending write was built on top of a *fallback* state, not the real
|
|
365
|
+
// one. Writing it now would overwrite good data with defaults. Adopt the
|
|
366
|
+
// disk truth instead and drop the pending fallback write.
|
|
367
|
+
warn('state.json read failed earlier; discarding changes made against the fallback state to avoid overwriting real data')
|
|
368
|
+
adoptCache(mergeState(diskRaw), false)
|
|
369
|
+
dirty = false
|
|
370
|
+
return
|
|
371
|
+
}
|
|
372
|
+
writeJson(STATE_FILE(), cache.state)
|
|
373
|
+
}
|
|
374
|
+
dirty = false
|
|
375
|
+
noteMemoryWrite('state', null)
|
|
376
|
+
const stat = statOf(STATE_FILE())
|
|
377
|
+
cache.mtimeMs = stat ? stat.mtimeMs : 0
|
|
378
|
+
cache.size = stat ? stat.size : -1
|
|
379
|
+
cache.base = structuredClone(cache.state)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function warnSinkSafe(message) {
|
|
383
|
+
warn(message)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export function getSettings() {
|
|
387
|
+
return loadState().settings
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Files that failed to read and are now write-protected, plus quarantined
|
|
392
|
+
* copies left behind. Surfaced by `memu_status` so a silent storage fault is
|
|
393
|
+
* visible instead of becoming "my memories vanished".
|
|
394
|
+
*/
|
|
395
|
+
export function storageHealth() {
|
|
396
|
+
const issues = readFailuresUnder(dataDir()).map((failure) => {
|
|
397
|
+
const relative = path.relative(dataDir(), failure.file).replace(/\\/g, '/')
|
|
398
|
+
const { file, ...rest } = failure
|
|
399
|
+
return { file: relative, ...rest }
|
|
400
|
+
})
|
|
401
|
+
const quarantined = []
|
|
402
|
+
for (const [dir, prefix] of [[dataDir(), ''], [indexDir(), 'index/']]) {
|
|
403
|
+
try {
|
|
404
|
+
for (const name of fs.readdirSync(dir)) {
|
|
405
|
+
if (name.includes('.corrupt-')) quarantined.push(`${prefix}${name}`)
|
|
406
|
+
}
|
|
407
|
+
} catch {}
|
|
408
|
+
}
|
|
409
|
+
return { issues, quarantined }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// The default is deliberately the self-contained path: a fresh install must be
|
|
413
|
+
// able to remember without MemU, Ollama, or any vendor key.
|
|
414
|
+
export function getMemoryBackend() {
|
|
415
|
+
return loadState().settings?.memoryBackend === 'api' ? 'api' : 'agent'
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// Single route authority for automatic memory reads and writes.
|
|
419
|
+
export function effectiveVectorRoute(settings = loadState().settings) {
|
|
420
|
+
if (settings?.memoryBackend !== 'api') return 'lexical'
|
|
421
|
+
return settings?.vectorSource === 'api' ? 'remote-api' : 'managed-local'
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export function vectorBackendEnabled(settings = loadState().settings) {
|
|
425
|
+
return effectiveVectorRoute(settings) !== 'lexical'
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
export function updateSettings(patch) {
|
|
429
|
+
const clean = {}
|
|
430
|
+
const ranges = {
|
|
431
|
+
privateTopK: [1, 20], globalTopK: [1, 20], anchorTokens: [160, 8000], turnTokens: [80, 8000],
|
|
432
|
+
injectionTotalTokens: [160, 16000],
|
|
433
|
+
relevanceThreshold: [0, 1], dedupeTurns: [0, 200], globalEveryNTurns: [0, 200], minUserChars: [0, 1000],
|
|
434
|
+
freshnessDays: [1, 3650],
|
|
435
|
+
mustRememberCap: [1, 100], randomCueChance: [0, 1], shortTermTtlHours: [0, 8760],
|
|
436
|
+
unpinBudgetPerSession: [1, 20], unpinCooldownMinutes: [0, 1440], sleepAfterIdleMinutes: [1, 1440],
|
|
437
|
+
openLoopRemindDays: [1, 365],
|
|
438
|
+
autoCurateEveryHours: [0, 8760], autoCurateSessionLimit: [1, 10], purgeArchivedAfterDays: [0, 36500],
|
|
439
|
+
activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
|
|
440
|
+
activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
|
|
441
|
+
midTurnMinSteps: [1, 64], midTurnMinUnits: [1, 200], midTurnMinChars: [0, 200000],
|
|
442
|
+
midTurnMaxPerTurn: [1, 10], midTurnCooldownMs: [0, 600000], midTurnTokens: [120, 2000],
|
|
443
|
+
midTurnFullUnits: [1, 200], midTurnFullChars: [0, 200000],
|
|
444
|
+
}
|
|
445
|
+
const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], autoLinkMode: ['suggest', 'deterministic', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'], consolidationTurnLog: ['on', 'off'], consolidationTurnLogTools: ['none', 'errors', 'summary'], consolidationRunner: ['worker', 'fork'] }
|
|
446
|
+
for (const [key, value] of Object.entries(patch || {})) {
|
|
447
|
+
if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
|
|
448
|
+
if (enums[key]) {
|
|
449
|
+
if (!enums[key].includes(value)) throw new Error(`invalid setting ${key}`)
|
|
450
|
+
clean[key] = value
|
|
451
|
+
} else if (ranges[key]) {
|
|
452
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`setting ${key} must be a finite number`)
|
|
453
|
+
const [min, max] = ranges[key]
|
|
454
|
+
clean[key] = Math.max(min, Math.min(max, value))
|
|
455
|
+
} else if (typeof DEFAULT_SETTINGS[key] === 'boolean') {
|
|
456
|
+
if (typeof value !== 'boolean') throw new Error(`setting ${key} must be boolean`)
|
|
457
|
+
clean[key] = value
|
|
458
|
+
} else if (key === 'curatorModel') {
|
|
459
|
+
if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid curator model')
|
|
460
|
+
clean[key] = value
|
|
461
|
+
} else if (key === 'consolidationModel') {
|
|
462
|
+
// host 模式的 "<provider>/<model>"。格式本身留给 lib/fork-model.js 的解析口径
|
|
463
|
+
// (与 curatorModel 一致:这里只挡类型与超长),写错的值会在 fork 创建时被
|
|
464
|
+
// invalid-consolidation-model 拒绝并在活动日志里说清,设置页先存的草稿不该被卡死。
|
|
465
|
+
if (value !== null && (typeof value !== 'string' || value.length > 200)) throw new Error('invalid consolidation model')
|
|
466
|
+
clean[key] = value
|
|
467
|
+
} else if (key === 'consolidationCustomBaseURL') {
|
|
468
|
+
// custom 模式的端点。空串是「还没填」,合法;非空必须是不带内嵌凭据的 http(s)
|
|
469
|
+
// URL——与 pipIndexes / vision endpoint 同一把尺(宿主请求头进不了带凭据的 URL)。
|
|
470
|
+
if (typeof value !== 'string') throw new Error('setting consolidationCustomBaseURL must be a string')
|
|
471
|
+
const trimmed = value.trim()
|
|
472
|
+
if (trimmed) {
|
|
473
|
+
try {
|
|
474
|
+
const url = new URL(trimmed)
|
|
475
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('bad protocol')
|
|
476
|
+
} catch {
|
|
477
|
+
throw new Error('consolidationCustomBaseURL must be an HTTP(S) URL without embedded credentials')
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
clean[key] = trimmed
|
|
481
|
+
} else if (key === 'consolidationCustomApiKey') {
|
|
482
|
+
// custom 模式选填的明文 key(本地网关可以没有)。落盘在 state.json,回包只给
|
|
483
|
+
// 打码视图(rpc.js);这里只挡类型与荒谬长度,两头空白顺手去掉。
|
|
484
|
+
if (typeof value !== 'string' || value.length > 500) throw new Error('invalid consolidation custom api key')
|
|
485
|
+
clean[key] = value.trim()
|
|
486
|
+
} else if (key === 'consolidationCustomModel') {
|
|
487
|
+
// custom 模式必填的模型 id。允许 '/'(openrouter 风格的嵌套 id),只挡类型与长度。
|
|
488
|
+
if (typeof value !== 'string' || value.length > 200) throw new Error('invalid consolidation custom model')
|
|
489
|
+
clean[key] = value.trim()
|
|
490
|
+
} else if (key === 'salientWakeHour') {
|
|
491
|
+
// 定时唤醒的本地墙上时间。只收 HH:mm,不收 "9:00":宿主的 at 输入按 HH:mm[:ss]
|
|
492
|
+
// 解释,少一位会被拒或读成别的时刻,宁可在设置页就拒绝。
|
|
493
|
+
if (typeof value !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) throw new Error('setting salientWakeHour must be HH:mm')
|
|
494
|
+
clean[key] = value
|
|
495
|
+
} else if (key === 'salientWakeTimeZone') {
|
|
496
|
+
// 空串是"跟随系统",是合法配置,不在这里解析成具体城市;非空必须是有效 IANA 区,
|
|
497
|
+
// 否则宿主的 at 计时会在投递时被拒(invalid_time_zone),排了也不会响。
|
|
498
|
+
if (typeof value !== 'string' || value.length > 100) throw new Error('invalid salientWakeTimeZone')
|
|
499
|
+
const zone = value.trim()
|
|
500
|
+
if (zone) {
|
|
501
|
+
try {
|
|
502
|
+
new Intl.DateTimeFormat('en-US', { timeZone: zone })
|
|
503
|
+
} catch {
|
|
504
|
+
throw new Error(`invalid salientWakeTimeZone: ${zone}`)
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
clean[key] = zone
|
|
508
|
+
} else if (key === 'pipIndexes' || key === 'promptDomains' || key === 'inboundToolNames') {
|
|
509
|
+
if (!Array.isArray(value) || value.length > 20 || value.some(item => typeof item !== 'string')) throw new Error(`invalid setting ${key}`)
|
|
510
|
+
if (key === 'promptDomains' && value.some(item => !/^[a-z0-9][a-z0-9_-]{0,23}$/.test(item))) throw new Error('invalid domain id')
|
|
511
|
+
if (key === 'inboundToolNames' && value.some(item => !/^[A-Za-z0-9_.:/-]{1,160}$/.test(item))) throw new Error('invalid inbound tool name')
|
|
512
|
+
if (key === 'pipIndexes' && value.some(item => {
|
|
513
|
+
try { const url = new URL(item); return !['http:', 'https:'].includes(url.protocol) || url.username || url.password } catch { return true }
|
|
514
|
+
})) throw new Error('pip indexes must be HTTP(S) URLs without credentials')
|
|
515
|
+
clean[key] = value.slice()
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return updateState((state) => {
|
|
519
|
+
state.settings = { ...state.settings, ...clean }
|
|
520
|
+
return state
|
|
521
|
+
}).settings
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* The prompt pages a user can edit and assign. Ids are used as file suffixes and
|
|
526
|
+
* as session domains, so they are restricted to a slug alphabet; `general` is
|
|
527
|
+
* implicit (the base prompt) and never appears here.
|
|
528
|
+
*/
|
|
529
|
+
export function getPromptDomains() {
|
|
530
|
+
const raw = loadState().settings?.promptDomains
|
|
531
|
+
const list = Array.isArray(raw) ? raw : DEFAULT_SETTINGS.promptDomains
|
|
532
|
+
const seen = new Set()
|
|
533
|
+
const out = []
|
|
534
|
+
for (const value of list) {
|
|
535
|
+
const id = String(value || '').trim().toLowerCase()
|
|
536
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,23}$/.test(id) || id === 'general' || seen.has(id)) continue
|
|
537
|
+
seen.add(id)
|
|
538
|
+
out.push(id)
|
|
539
|
+
}
|
|
540
|
+
return out
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
export function addPromptDomain(id) {
|
|
544
|
+
const value = String(id || '').trim().toLowerCase()
|
|
545
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,23}$/.test(value)) throw new Error('domain id must be 1-24 chars: a-z, 0-9, - or _')
|
|
546
|
+
if (value === 'general') throw new Error('"general" is the built-in 通用 page')
|
|
547
|
+
const list = getPromptDomains()
|
|
548
|
+
if (list.includes(value)) return list
|
|
549
|
+
return updateSettings({ promptDomains: [...list, value] }).promptDomains
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
export function removePromptDomain(id) {
|
|
553
|
+
const value = String(id || '').trim().toLowerCase()
|
|
554
|
+
const list = getPromptDomains()
|
|
555
|
+
if (!list.includes(value)) return list
|
|
556
|
+
return updateSettings({ promptDomains: list.filter((item) => item !== value) }).promptDomains
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// Both switches default to on: that is the behaviour every existing folder had
|
|
560
|
+
// before this setting existed. Turning the private switch off means "this folder
|
|
561
|
+
// keeps no private library", not "delete the one it has" — nothing is ever deleted
|
|
562
|
+
// by a switch.
|
|
563
|
+
export const DEFAULT_FOLDER_POLICY = { useLibrary: true, useGlobal: true }
|
|
564
|
+
|
|
565
|
+
function policyFor(state, scopeKey) {
|
|
566
|
+
return { ...DEFAULT_FOLDER_POLICY, ...(state.workspacePolicies?.[scopeKey] || {}) }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
export function getWorkspacePolicy(scopeKey) {
|
|
570
|
+
const key = normalizeCwd(scopeKey) || '__default__'
|
|
571
|
+
return { scopeKey: key, ...policyFor(loadState(), key) }
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* The folder policy is a ceiling, not an initial value. `sessions[].useLibrary`
|
|
576
|
+
* records what the user chose for that conversation; the folder decides how far
|
|
577
|
+
* that choice can go. Storing the wish and computing the effect separately is
|
|
578
|
+
* what lets re-enabling a folder restore each conversation's own choice instead
|
|
579
|
+
* of flipping everything back on.
|
|
580
|
+
*/
|
|
581
|
+
export function effectiveScope(binding, policy = null) {
|
|
582
|
+
const folder = policy || (binding?.scopeKey ? getWorkspacePolicy(binding.scopeKey) : { ...DEFAULT_FOLDER_POLICY })
|
|
583
|
+
const wantsLibrary = binding ? binding.useLibrary !== false : folder.useLibrary !== false
|
|
584
|
+
const wantsGlobal = binding ? binding.useGlobal !== false : folder.useGlobal !== false
|
|
585
|
+
return {
|
|
586
|
+
folder,
|
|
587
|
+
useLibrary: folder.useLibrary !== false && wantsLibrary,
|
|
588
|
+
useGlobal: folder.useGlobal !== false && wantsGlobal,
|
|
589
|
+
libraryBlocked: folder.useLibrary === false,
|
|
590
|
+
globalBlocked: folder.useGlobal === false,
|
|
591
|
+
enabled: (folder.useLibrary !== false && wantsLibrary) || (folder.useGlobal !== false && wantsGlobal),
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
export function listWorkspacePolicies() {
|
|
596
|
+
const state = loadState()
|
|
597
|
+
return Object.entries(state.workspacePolicies || {})
|
|
598
|
+
.map(([scopeKey, policy]) => ({ scopeKey, ...DEFAULT_FOLDER_POLICY, ...policy }))
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export function setWorkspacePolicy(scopeKey, patch = {}) {
|
|
602
|
+
const key = normalizeCwd(scopeKey) || '__default__'
|
|
603
|
+
const state = updateState((draft) => {
|
|
604
|
+
draft.workspacePolicies = draft.workspacePolicies || {}
|
|
605
|
+
const next = { ...DEFAULT_FOLDER_POLICY, ...(draft.workspacePolicies[key] || {}) }
|
|
606
|
+
for (const field of ['useLibrary', 'useGlobal']) {
|
|
607
|
+
if (typeof patch[field] === 'boolean') next[field] = patch[field]
|
|
608
|
+
}
|
|
609
|
+
draft.workspacePolicies[key] = { ...next, updatedAt: stamp() }
|
|
610
|
+
const library = Object.entries(draft.libraries)
|
|
611
|
+
.find(([, lib]) => lib.scopeKey === key && lib.archived !== true)
|
|
612
|
+
// Existing conversations are deliberately NOT edited: their switches record
|
|
613
|
+
// what the user chose for that chat, and the folder policy above already
|
|
614
|
+
// clamps them at read time. The only repair worth doing is pointing a
|
|
615
|
+
// conversation at its folder's library once one exists again.
|
|
616
|
+
if (patch.useLibrary === true) {
|
|
617
|
+
for (const binding of Object.values(draft.sessions || {})) {
|
|
618
|
+
const inFolder = binding.scopeKey === key
|
|
619
|
+
|| (binding.libraryId && draft.libraries[binding.libraryId]?.scopeKey === key)
|
|
620
|
+
if (inFolder && !binding.libraryId && library) binding.libraryId = library[0]
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return draft
|
|
624
|
+
})
|
|
625
|
+
return { scopeKey: key, ...policyFor(state, key) }
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
export function normalizeCwd(cwd) {
|
|
629
|
+
if (!cwd || typeof cwd !== 'string') return ''
|
|
630
|
+
// The no-workspace placeholder is a key, not a path. Resolving it would produce
|
|
631
|
+
// a machine-dependent scope like `d:/somewhere/__default__` and leak a junk
|
|
632
|
+
// library into the list every time a session starts without a folder.
|
|
633
|
+
if (cwd === '__default__') return '__default__'
|
|
634
|
+
let resolved
|
|
635
|
+
try { resolved = path.resolve(cwd) } catch { resolved = cwd }
|
|
636
|
+
let text = resolved.replace(/\\/g, '/').replace(/\/+$/, '')
|
|
637
|
+
if (process.platform === 'win32') text = text.toLowerCase()
|
|
638
|
+
return text
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export function detectDomain({ agentPreset, cwd } = {}) {
|
|
642
|
+
const text = `${agentPreset || ''} ${cwd || ''}`.toLowerCase()
|
|
643
|
+
if (/(roleplay|role-play|character|persona|rp[-_ ]|沉浸|角色扮演)/.test(text)) return 'rp'
|
|
644
|
+
if (cwd) return 'coding'
|
|
645
|
+
return 'general'
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export function listLibraries() {
|
|
649
|
+
const state = loadState()
|
|
650
|
+
return Object.entries(state.libraries)
|
|
651
|
+
.filter(([, lib]) => lib.archived !== true)
|
|
652
|
+
.map(([id, lib]) => ({ id, ...lib }))
|
|
653
|
+
.sort((a, b) => String(b.lastUsedAt || '').localeCompare(String(a.lastUsedAt || '')))
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
export function listLibrariesAll() {
|
|
657
|
+
const state = loadState()
|
|
658
|
+
return Object.entries(state.libraries).map(([id, lib]) => ({ id, ...lib }))
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
export function listArchivedLibraries() {
|
|
662
|
+
const state = loadState()
|
|
663
|
+
return Object.entries(state.libraries)
|
|
664
|
+
.filter(([, lib]) => lib.archived === true)
|
|
665
|
+
.map(([id, lib]) => ({ id, ...lib }))
|
|
666
|
+
// Oldest archived first: the ones nobody revived are the deletion candidates.
|
|
667
|
+
.sort((a, b) => String(a.archivedAt || '').localeCompare(String(b.archivedAt || '')))
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// A library's scope folder is gone from disk. `__default__` has no folder to check,
|
|
671
|
+
// so it never counts as missing.
|
|
672
|
+
export function libraryScopeMissing(lib) {
|
|
673
|
+
const key = lib?.scopeKey
|
|
674
|
+
if (!key || key === '__default__') return false
|
|
675
|
+
try {
|
|
676
|
+
return !fs.existsSync(key)
|
|
677
|
+
} catch {
|
|
678
|
+
return false
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// Hard delete: the sqlite store and its sidecar index leave with the state entry.
|
|
683
|
+
// Only ever called on an already-archived library, so the caller had to confirm twice.
|
|
684
|
+
// `force` exists for the one legitimate case the state cannot see: the caller already
|
|
685
|
+
// unbound every session and knows it. Without it, a library that a live conversation
|
|
686
|
+
// still points at cannot be deleted — the sweep used to be able to put an in-use
|
|
687
|
+
// library into the only state `deleteLibrary` accepts.
|
|
688
|
+
export function deleteLibrary(id, { force = false } = {}) {
|
|
689
|
+
if (!isSafeId(id)) throw new Error('invalid library id')
|
|
690
|
+
const state = loadState()
|
|
691
|
+
if (!state.libraries[id]) return { ok: false, error: 'library not found' }
|
|
692
|
+
if (state.libraries[id].archived !== true) return { ok: false, error: 'archive the library before deleting it' }
|
|
693
|
+
// 只拦「危险归档 + 仍在用」:扫描误归档的那一类才有一键删掉全部记忆的风险。
|
|
694
|
+
// 用户主动归档仍有绑定会话时照旧允许(删除会连同绑定一起清掉,这是既有语义);
|
|
695
|
+
// 冷数据的旧归档同理放行,否则本机 rp / 另一个工作区库 这类库会变成"永远删不掉"。
|
|
696
|
+
if (!force && archivedWhileInUse(state.libraries[id], { inUse: inUseLibraryIds(state).has(id) })) {
|
|
697
|
+
return { ok: false, error: 'this library was archived while a conversation still uses it; unbind or delete those sessions first (force overrides)' }
|
|
698
|
+
}
|
|
699
|
+
const activeVectorDb = removeActiveLibrary(id)
|
|
700
|
+
const legacyVectorDb = path.join(librariesDir(), id + '.sqlite3')
|
|
701
|
+
delete state.libraries[id]
|
|
702
|
+
for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
|
|
703
|
+
if (binding?.libraryId === id) delete state.sessions[sessionId]
|
|
704
|
+
}
|
|
705
|
+
saveState(state)
|
|
706
|
+
const removed = []
|
|
707
|
+
const vectorPrefix = id + '.'
|
|
708
|
+
const vectorGenerationFiles = fs.existsSync(librariesDir())
|
|
709
|
+
? fs.readdirSync(librariesDir()).filter(name => name.startsWith(vectorPrefix) && name.endsWith('.sqlite3')).map(name => path.join(librariesDir(), name))
|
|
710
|
+
: []
|
|
711
|
+
for (const file of [activeVectorDb, legacyVectorDb, ...vectorGenerationFiles, ...['json', 'entities.json', 'media.json', 'stats.json', 'link-suppression.json', 'anchor-candidates.json'].map(suffix => path.join(indexDir(), `${id}.${suffix}`))]) {
|
|
712
|
+
if (!file) continue
|
|
713
|
+
try {
|
|
714
|
+
if (fs.existsSync(file)) { fs.rmSync(file, { force: true }); removed.push(file) }
|
|
715
|
+
} catch {}
|
|
716
|
+
}
|
|
717
|
+
const attachments = path.join(dataDir(), 'attachments', id)
|
|
718
|
+
if (!path.resolve(attachments).startsWith(path.resolve(dataDir(), 'attachments') + path.sep)) throw new Error('attachment path escaped')
|
|
719
|
+
if (fs.existsSync(attachments)) fs.rmSync(attachments, { recursive: true, force: true })
|
|
720
|
+
return { ok: true, id, removed }
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
export function getLibrary(id) {
|
|
724
|
+
if (!id) return null
|
|
725
|
+
const lib = loadState().libraries[id]
|
|
726
|
+
return lib ? { id, ...lib } : null
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function uniqueLibraryId(state, scopeKey) {
|
|
730
|
+
let id = libraryIdForScope(scopeKey)
|
|
731
|
+
if (state.libraries[id] && state.libraries[id].scopeKey !== scopeKey) {
|
|
732
|
+
id = `${id}-${shortHash(scopeKey)}`
|
|
733
|
+
}
|
|
734
|
+
return id
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
export function createLibrary({ name, scopeKey, cwd } = {}) {
|
|
738
|
+
const key = normalizeCwd(scopeKey || cwd || name || '__default__')
|
|
739
|
+
const state = loadState()
|
|
740
|
+
const id = uniqueLibraryId(state, key)
|
|
741
|
+
if (state.libraries[id]) return { id, ...state.libraries[id] }
|
|
742
|
+
state.libraries[id] = {
|
|
743
|
+
name: String(name || path.basename(key) || 'Default').slice(0, 80),
|
|
744
|
+
scopeKey: key,
|
|
745
|
+
createdAt: stamp(),
|
|
746
|
+
lastUsedAt: stamp(),
|
|
747
|
+
}
|
|
748
|
+
saveState(state)
|
|
749
|
+
ensureDir(librariesDir())
|
|
750
|
+
return { id, ...state.libraries[id] }
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
export function ensureLibraryForCwd(cwd) {
|
|
754
|
+
const scopeKey = normalizeCwd(cwd) || '__default__'
|
|
755
|
+
const state = loadState()
|
|
756
|
+
const found = Object.entries(state.libraries).find(([, lib]) => lib.scopeKey === scopeKey)
|
|
757
|
+
if (found) {
|
|
758
|
+
found[1].lastUsedAt = stamp()
|
|
759
|
+
// The folder came back: re-binding it revives the library instead of silently
|
|
760
|
+
// writing new memories into an archived one.
|
|
761
|
+
if (found[1].archived) {
|
|
762
|
+
found[1].archived = false
|
|
763
|
+
found[1].archivedAt = null
|
|
764
|
+
found[1].revivedAt = stamp()
|
|
765
|
+
}
|
|
766
|
+
saveState(state)
|
|
767
|
+
return { id: found[0], ...found[1] }
|
|
768
|
+
}
|
|
769
|
+
return createLibrary({ scopeKey, name: scopeKey === '__default__' ? 'Default' : path.basename(scopeKey) })
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
export function renameLibrary(id, name) {
|
|
773
|
+
const state = loadState()
|
|
774
|
+
if (!state.libraries[id]) return null
|
|
775
|
+
state.libraries[id].name = String(name || '').trim().slice(0, 80) || state.libraries[id].name
|
|
776
|
+
saveState(state)
|
|
777
|
+
return { id, ...state.libraries[id] }
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// A pre-folder build could bind a conversation before its cwd was known, leaving
|
|
781
|
+
// one shared "Default" bucket for every workspace. The conversation is the only
|
|
782
|
+
// place that still knows the real folder, so when it is opened with a cwd we
|
|
783
|
+
// promote that bucket in place: same id, so its memories and index stay attached,
|
|
784
|
+
// but the name and scope become the folder a human expects to see.
|
|
785
|
+
export function adoptDefaultLibrary(libraryId, cwd) {
|
|
786
|
+
const key = normalizeCwd(cwd)
|
|
787
|
+
if (!key || key === '__default__') return null
|
|
788
|
+
const state = loadState()
|
|
789
|
+
const lib = state.libraries[libraryId]
|
|
790
|
+
if (!lib || normalizeCwd(lib.scopeKey || '') !== '__default__') return null
|
|
791
|
+
const existing = Object.entries(state.libraries)
|
|
792
|
+
.find(([id, other]) => id !== libraryId && other.scopeKey === key && other.archived !== true)
|
|
793
|
+
if (existing) {
|
|
794
|
+
for (const binding of Object.values(state.sessions || {})) {
|
|
795
|
+
if (binding.libraryId === libraryId) {
|
|
796
|
+
binding.libraryId = existing[0]
|
|
797
|
+
binding.scopeKey = key
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
// Keep the old bucket recoverable but out of the way when nothing points at it
|
|
801
|
+
// any more. It is never deleted: a mis-detected cwd must not destroy memories.
|
|
802
|
+
const stillBound = Object.values(state.sessions || {}).some((b) => b.libraryId === libraryId)
|
|
803
|
+
if (!stillBound) {
|
|
804
|
+
lib.archived = true
|
|
805
|
+
lib.archivedAt = stamp()
|
|
806
|
+
lib.adoptedInto = existing[0]
|
|
807
|
+
}
|
|
808
|
+
saveState(state)
|
|
809
|
+
return { id: existing[0], ...existing[1], adopted: true, reused: true }
|
|
810
|
+
}
|
|
811
|
+
lib.scopeKey = key
|
|
812
|
+
lib.name = key.split(/[\\/]/).filter(Boolean).pop() || lib.name || 'Default'
|
|
813
|
+
lib.updatedAt = stamp()
|
|
814
|
+
for (const binding of Object.values(state.sessions || {})) {
|
|
815
|
+
if (binding.libraryId === libraryId) binding.scopeKey = key
|
|
816
|
+
}
|
|
817
|
+
saveState(state)
|
|
818
|
+
return { id: libraryId, ...lib, adopted: true }
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* Returns libraries used by a live session: any binding with `sessionGone !== true`
|
|
823
|
+
* counts as active. Archive scans cannot rely only on workspaceRegistry because
|
|
824
|
+
* libraries scoped to IM plugins or profiles may not be registered there.
|
|
825
|
+
*
|
|
826
|
+
* Use binding state rather than an age window: elapsed time cannot reliably
|
|
827
|
+
* distinguish an idle library from one that was just opened. Passing state lets the
|
|
828
|
+
* sweep read it once and calculate the result once.
|
|
829
|
+
*/
|
|
830
|
+
export function inUseLibraryIds(state = null) {
|
|
831
|
+
const snapshot = state || loadState()
|
|
832
|
+
const ids = new Set()
|
|
833
|
+
for (const binding of Object.values(snapshot.sessions || {})) {
|
|
834
|
+
if (!binding || binding.sessionGone === true) continue
|
|
835
|
+
const libraryId = binding.libraryId
|
|
836
|
+
if (!libraryId || !snapshot.libraries?.[libraryId]) continue
|
|
837
|
+
ids.add(libraryId)
|
|
838
|
+
}
|
|
839
|
+
return ids
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
export function isLibraryInUse(id) {
|
|
843
|
+
return Boolean(id) && inUseLibraryIds().has(id)
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// 1.3.13 及更早的归档没有 `archivedBy`:分不清是用户点的归档还是老扫描误归档。
|
|
847
|
+
// 对这类库只认「还热」的(lastUsedAt 在 14 天内),冷归档按用户意图对待。
|
|
848
|
+
export const ARCHIVE_REVIVE_FRESH_MS = 14 * 86_400_000
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* 「归档了但其实还在用」——扫描误归档的判据,同时也是删除守卫的判据。
|
|
852
|
+
*
|
|
853
|
+
* 用户主动归档(`archivedBy === 'user'`)永远不算;扫描归档的(`'sweep'`)永远算;
|
|
854
|
+
* 旧数据按 lastUsedAt 的新鲜度判。两处共用同一个函数,避免"扫描复活、删除又放行"这种
|
|
855
|
+
* 两套口径各说各话。
|
|
856
|
+
*/
|
|
857
|
+
export function archivedWhileInUse(lib, { inUse = false, now = Date.now() } = {}) {
|
|
858
|
+
if (!inUse || !lib) return false
|
|
859
|
+
if (lib.archivedBy === 'user') return false
|
|
860
|
+
if (lib.archivedBy === 'sweep') return true
|
|
861
|
+
const lastUsed = Date.parse(lib.lastUsedAt || '') || 0
|
|
862
|
+
return lastUsed > 0 && now - lastUsed <= ARCHIVE_REVIVE_FRESH_MS
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** `by` 记录是谁归档的:用户的主动归档不该被扫描悄悄复活。 */
|
|
866
|
+
export function archiveLibrary(id, { by = 'user' } = {}) {
|
|
867
|
+
const state = loadState()
|
|
868
|
+
if (!state.libraries[id]) return false
|
|
869
|
+
state.libraries[id].archived = true
|
|
870
|
+
state.libraries[id].archivedAt = stamp()
|
|
871
|
+
state.libraries[id].archivedBy = by
|
|
872
|
+
saveState(state)
|
|
873
|
+
return true
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// Registry presence is the signal for both directions: the sweep only calls this for
|
|
877
|
+
// a scope that just came back into the workspace list. Checking the disk here would
|
|
878
|
+
// contradict the archive rule (removing a workspace keeps its folder on disk, and a
|
|
879
|
+
// folder can be absent for reasons that have nothing to do with DSH).
|
|
880
|
+
export function restoreLibrary(id) {
|
|
881
|
+
const state = loadState()
|
|
882
|
+
const lib = state.libraries[id]
|
|
883
|
+
if (!lib) return { ok: false, error: 'library not found' }
|
|
884
|
+
lib.archived = false
|
|
885
|
+
lib.archivedAt = null
|
|
886
|
+
lib.archivedBy = null
|
|
887
|
+
lib.revivedAt = stamp()
|
|
888
|
+
lib.lastUsedAt = stamp()
|
|
889
|
+
saveState(state)
|
|
890
|
+
return { ok: true, id, library: { id, ...lib } }
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
export function getSessionBinding(sessionId) {
|
|
894
|
+
if (!sessionId) return null
|
|
895
|
+
const state = loadState()
|
|
896
|
+
return state.sessions[sessionId] || null
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
export function setSessionBinding(sessionId, patch) {
|
|
900
|
+
return updateState((state) => {
|
|
901
|
+
const previous = state.sessions[sessionId] || {}
|
|
902
|
+
const next = { ...previous, ...(patch || {}) }
|
|
903
|
+
for (const key of ['lastInjectedUserMessageId', 'guideRulesKey', 'guideMessageAt', 'anchorPushed']) {
|
|
904
|
+
if (!Object.hasOwn(patch || {}, key)) continue
|
|
905
|
+
next.injectionOwners = { ...(next.injectionOwners || {}), [key]: `legacy:${crypto.randomUUID()}` }
|
|
906
|
+
}
|
|
907
|
+
const scopeFields = ['libraryId', 'scopeKey', 'memoryContext', 'useLibrary', 'useGlobal', 'domainOverride']
|
|
908
|
+
if (scopeFields.some(key => Object.hasOwn(patch || {}, key) && JSON.stringify(previous[key]) !== JSON.stringify(next[key]))) {
|
|
909
|
+
next.scopeGeneration = Number(previous.scopeGeneration || 0) + 1
|
|
910
|
+
}
|
|
911
|
+
state.sessions[sessionId] = next
|
|
912
|
+
return state
|
|
913
|
+
}).sessions[sessionId]
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
export function ensureSession(sessionId, { cwd, agentPreset, libraryId = null, createLibrary = true } = {}) {
|
|
917
|
+
if (!sessionId) throw new Error('ensureSession requires a sessionId')
|
|
918
|
+
const initial = loadState()
|
|
919
|
+
const previous = initial.sessions[sessionId]
|
|
920
|
+
if (previous?.libraryId && initial.libraries[previous.libraryId]) {
|
|
921
|
+
const boundLibrary = initial.libraries[previous.libraryId]
|
|
922
|
+
// 一个正在被这个会话读写的库不该停在 archived:归档的语义是「隐藏、准备清理」,
|
|
923
|
+
// 而在用的库既不该消失,也不该落进 `deleteLibrary` 唯一允许删除的状态。旧版扫描
|
|
924
|
+
// 只要 scope 不在 workspaceRegistry 就归档,而这条快路径从不复活,于是库能一边
|
|
925
|
+
// 「归档」一边长数据 9 小时。用户主动归档(archivedBy === 'user')除外。
|
|
926
|
+
if (boundLibrary.archived === true && boundLibrary.archivedBy !== 'user') {
|
|
927
|
+
restoreLibrary(previous.libraryId)
|
|
928
|
+
const revived = loadState().sessions[sessionId]
|
|
929
|
+
if (revived) return revived
|
|
930
|
+
}
|
|
931
|
+
const libraryScope = normalizeCwd(boundLibrary.scopeKey || '')
|
|
932
|
+
// Repair the old placeholder bucket as soon as the live conversation reveals
|
|
933
|
+
// its folder. Without this, every historical Default library stays mislabelled
|
|
934
|
+
// even though new conversations are correct.
|
|
935
|
+
if (libraryScope === '__default__' && normalizeCwd(cwd)) {
|
|
936
|
+
const adopted = adoptDefaultLibrary(previous.libraryId, cwd)
|
|
937
|
+
if (adopted) {
|
|
938
|
+
const repaired = loadState().sessions[sessionId]
|
|
939
|
+
if (repaired) return repaired
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
// A library that already knows its folder but still carries the placeholder
|
|
943
|
+
// name should show the folder too; this is the case the old repair missed.
|
|
944
|
+
const placeholderName = !boundLibrary.name || boundLibrary.name === 'Default' || boundLibrary.name === '__default__'
|
|
945
|
+
if (libraryScope && libraryScope !== '__default__' && placeholderName) {
|
|
946
|
+
boundLibrary.name = libraryScope.split(/[\\/]/).filter(Boolean).pop() || boundLibrary.name || 'Default'
|
|
947
|
+
boundLibrary.updatedAt = stamp()
|
|
948
|
+
}
|
|
949
|
+
boundLibrary.lastUsedAt = stamp()
|
|
950
|
+
saveState(initial)
|
|
951
|
+
return previous
|
|
952
|
+
}
|
|
953
|
+
const scopeKey = normalizeCwd(cwd) || '__default__'
|
|
954
|
+
const policy = policyFor(initial, scopeKey)
|
|
955
|
+
const requested = libraryId && initial.libraries[libraryId] ? libraryId : null
|
|
956
|
+
// A per-conversation switch is the user's choice and must survive every turn:
|
|
957
|
+
// `ensureSession` runs on each step, so overwriting it from the folder policy
|
|
958
|
+
// here used to reset the sidebar toggle constantly. The folder still clamps at
|
|
959
|
+
// read time via effectiveScope().
|
|
960
|
+
const existingBinding = initial.sessions[sessionId]
|
|
961
|
+
const wantsLibrary = existingBinding ? existingBinding.useLibrary !== false : policy.useLibrary !== false
|
|
962
|
+
const wantsGlobal = existingBinding ? existingBinding.useGlobal !== false : policy.useGlobal !== false
|
|
963
|
+
let lib = null
|
|
964
|
+
if (requested) lib = { id: requested, ...initial.libraries[requested] }
|
|
965
|
+
// `createLibrary` governs *creating* a library, never *adopting* one. Tying both
|
|
966
|
+
// to it meant a folder that already had a library still started every new
|
|
967
|
+
// conversation with `libraryId === null` whenever the caller passed
|
|
968
|
+
// `createLibrary: false` — the exact shape of "my memories are gone in a new
|
|
969
|
+
// chat". Re-using the folder's library is not a side effect; it is the point of
|
|
970
|
+
// the folder policy. Archived libraries are skipped here (reviving one is a
|
|
971
|
+
// deliberate act) and creation still needs the switch.
|
|
972
|
+
else if (policy.useLibrary && wantsLibrary) {
|
|
973
|
+
const folder = Object.entries(initial.libraries).find(([, l]) => l.scopeKey === scopeKey && l.archived !== true)
|
|
974
|
+
if (folder) lib = { id: folder[0], ...folder[1] }
|
|
975
|
+
else if (createLibrary) lib = ensureLibraryForCwd(cwd || '__default__')
|
|
976
|
+
}
|
|
977
|
+
const state = loadState()
|
|
978
|
+
const existing = state.sessions[sessionId]
|
|
979
|
+
const binding = {
|
|
980
|
+
...(existing || {}),
|
|
981
|
+
useLibrary: requested ? true : wantsLibrary,
|
|
982
|
+
useGlobal: wantsGlobal,
|
|
983
|
+
scopeKey,
|
|
984
|
+
domain: existing?.domain || detectDomain({ agentPreset, cwd }),
|
|
985
|
+
// 未被问过的新会话不再硬编码 RP 兜底(issue #2 缺陷 2):领域跟随 detectDomain
|
|
986
|
+
// 的文件夹/预设判定,与上方 domain 字段同一口径。弹窗或侧栏写下的显式答案会
|
|
987
|
+
// 覆盖这里,并留下 domainSource:'chosen' 作为「已答」的凭据。
|
|
988
|
+
domainOverride: existing?.domainOverride ?? detectDomain({ agentPreset, cwd }),
|
|
989
|
+
domainSource: existing?.domainSource ?? 'auto',
|
|
990
|
+
injectedIds: existing?.injectedIds || [],
|
|
991
|
+
injectedAt: existing?.injectedAt || {},
|
|
992
|
+
lastInjectedTurn: existing?.lastInjectedTurn ?? 0,
|
|
993
|
+
reinjectPending: existing?.reinjectPending || false,
|
|
994
|
+
activeCue: existing?.activeCue || null,
|
|
995
|
+
libraryId: existing?.libraryId && state.libraries[existing.libraryId]
|
|
996
|
+
? existing.libraryId
|
|
997
|
+
: (lib?.id || null),
|
|
998
|
+
}
|
|
999
|
+
state.sessions[sessionId] = binding
|
|
1000
|
+
saveState(state)
|
|
1001
|
+
return binding
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
export function deleteSessionBinding(sessionId) {
|
|
1005
|
+
return updateState((state) => {
|
|
1006
|
+
delete state.sessions[sessionId]
|
|
1007
|
+
return state
|
|
1008
|
+
})
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// Only typed, host-admitted records prove content identity. Legacy bare ids do not.
|
|
1012
|
+
export function recentMemoryRefs(binding, memoryClock, dedupeTurns) {
|
|
1013
|
+
const window = Number(dedupeTurns)
|
|
1014
|
+
const clock = Number(memoryClock)
|
|
1015
|
+
if (!(window > 0) || !Number.isFinite(clock)) return []
|
|
1016
|
+
const latest = new Map()
|
|
1017
|
+
const revoked = new Set(binding?.revokedInjectionMessages || [])
|
|
1018
|
+
for (const record of binding?.acceptedMemoryMessages || []) {
|
|
1019
|
+
if (record.generation !== Number(binding.scopeGeneration || 0)
|
|
1020
|
+
|| record.epoch !== Number(binding.injectionEpoch || 0) || revoked.has(record.messageId)) continue
|
|
1021
|
+
for (const ref of record.refs || []) {
|
|
1022
|
+
const key = memoryRefKey(ref)
|
|
1023
|
+
const previous = latest.get(key)
|
|
1024
|
+
if (!previous || record.memoryClock >= previous.clock) latest.set(key, { ref, clock: record.memoryClock })
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
return [...latest.values()].filter(item => item.clock <= clock && clock - item.clock < window)
|
|
1028
|
+
.map(item => ({ ...item.ref }))
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
/** Commit one immutable message after its exact body entered host history. No entry bodies. */
|
|
1032
|
+
export function markInjectedRefs(sessionId, refs, memoryClock, options = {}) {
|
|
1033
|
+
if (!sessionId || typeof options.messageId !== 'string' || !Number.isFinite(Number(memoryClock))) return null
|
|
1034
|
+
let committed = null
|
|
1035
|
+
updateState(state => {
|
|
1036
|
+
const binding = state.sessions[sessionId]
|
|
1037
|
+
if (!binding) return state
|
|
1038
|
+
const records = binding.acceptedMemoryMessages || []
|
|
1039
|
+
if (records.some(record => record.messageId === options.messageId)) return state
|
|
1040
|
+
const generation = Number(options.generation ?? binding.scopeGeneration ?? 0)
|
|
1041
|
+
const epoch = Number(options.epoch ?? binding.injectionEpoch ?? 0)
|
|
1042
|
+
if (generation !== Number(binding.scopeGeneration || 0) || epoch !== Number(binding.injectionEpoch || 0)) return state
|
|
1043
|
+
const typed = (refs || []).filter(ref => ref && ['private', 'global'].includes(ref.scope)
|
|
1044
|
+
&& typeof ref.id === 'string' && typeof ref.revision === 'string'
|
|
1045
|
+
&& (ref.scope === 'global' || typeof ref.libraryId === 'string'))
|
|
1046
|
+
.map(ref => ({ scope: ref.scope, libraryId: ref.libraryId ?? null, id: ref.id, revision: ref.revision,
|
|
1047
|
+
...(ref.groupKey !== undefined ? { groupKey: ref.groupKey } : {}),
|
|
1048
|
+
...(ref.groupRevision !== undefined ? { groupRevision: ref.groupRevision } : {}) }))
|
|
1049
|
+
committed = { messageId: options.messageId, hostTurn: options.hostTurn ?? null, generation, epoch,
|
|
1050
|
+
memoryClock: Number(memoryClock), refs: typed, admittedAt: stamp() }
|
|
1051
|
+
const next = [...records, committed]
|
|
1052
|
+
let count = next.reduce((sum, record) => sum + record.refs.length, 0)
|
|
1053
|
+
while (next.length > 1 && (count > 400 || next.length > 400)) count -= next.shift().refs.length
|
|
1054
|
+
if (count > 400) committed.refs = committed.refs.slice(-400)
|
|
1055
|
+
binding.acceptedMemoryMessages = next
|
|
1056
|
+
// Old anchor consumers retain their compatibility view, never a typed cooldown.
|
|
1057
|
+
const ids = typed.map(ref => ref.id)
|
|
1058
|
+
if ((binding.injectedIds || []).includes('__anchor__')) binding.anchorPushed = true
|
|
1059
|
+
binding.injectedIds = [...new Set([...(binding.injectedIds || []).filter(id => id !== '__anchor__'), ...ids])].slice(-400)
|
|
1060
|
+
binding.injectedAt = { ...(binding.injectedAt || {}) }
|
|
1061
|
+
binding.injectionOwners = { ...(binding.injectionOwners || {}) }
|
|
1062
|
+
binding.injectionOwnerClocks = { ...(binding.injectionOwnerClocks || {}) }
|
|
1063
|
+
committed.effects = {}
|
|
1064
|
+
const applyEffect = (key, value, field = key, id = null) => {
|
|
1065
|
+
const owner = binding.injectionOwners[key]
|
|
1066
|
+
const priorClock = typeof owner === 'string' && owner.startsWith('legacy:')
|
|
1067
|
+
? Math.max(Number(binding.lastInjectedTurn || 0), Number(binding.inbound?.clock || 0), Number(binding.injectionOwnerClocks[key] || 0))
|
|
1068
|
+
: binding.injectionOwnerClocks[key] ?? records.find(record => record.messageId === owner)?.memoryClock ?? -1
|
|
1069
|
+
if (Number(priorClock) > Number(memoryClock)) return
|
|
1070
|
+
const previous = id === null ? binding[field] : binding[field]?.[id]
|
|
1071
|
+
committed.effects[key] = { value: structuredClone(previous), owner: binding.injectionOwners[key] ?? null,
|
|
1072
|
+
clock: binding.injectionOwnerClocks[key] ?? null, field, id }
|
|
1073
|
+
if (id === null) binding[field] = structuredClone(value)
|
|
1074
|
+
else binding[field] = { ...(binding[field] || {}), [id]: structuredClone(value) }
|
|
1075
|
+
binding.injectionOwners[key] = options.messageId
|
|
1076
|
+
binding.injectionOwnerClocks[key] = Number(memoryClock)
|
|
1077
|
+
}
|
|
1078
|
+
for (const id of ids) applyEffect(`id:${id}`, Number(memoryClock), 'injectedAt', id)
|
|
1079
|
+
const actions = structuredClone(options.actions || {})
|
|
1080
|
+
const patch = actions.patch || {}
|
|
1081
|
+
if (actions.anchor) { patch.anchorPushed = true; patch.reinjectPending = false }
|
|
1082
|
+
if (actions.cue) patch.activeCue = { id: String(actions.cue.id), text: String(actions.cue.text || '').slice(0, 500),
|
|
1083
|
+
sourceId: actions.cue.sourceId ? String(actions.cue.sourceId) : null,
|
|
1084
|
+
recallQuery: actions.cue.recallQuery ? String(actions.cue.recallQuery).slice(0, 200) : null, createdAt: stamp() }
|
|
1085
|
+
if (actions.lexicon?.selected?.length) patch.lexiconInjectionClock = Number(memoryClock)
|
|
1086
|
+
for (const [key, value] of Object.entries(patch)) applyEffect(key, value)
|
|
1087
|
+
for (const [id, day] of Object.entries(actions.anniversaries || {})) applyEffect(`anniversary:${id}`, day, 'anniversariesShown', id)
|
|
1088
|
+
for (const id of actions.nudgeIds || []) applyEffect(`nudge:${id}`, stamp(), 'openLoopRemindedAt', id)
|
|
1089
|
+
// An immutable proposal consumes only its displayed occurrences, never a SHA or snapshot queue.
|
|
1090
|
+
const media = actions.media
|
|
1091
|
+
if (media?.scope?.sessionId === sessionId && media.scope.libraryId === binding.libraryId
|
|
1092
|
+
&& media.scope.incarnation === binding.mediaIncarnation
|
|
1093
|
+
&& media.scope.contextKey === JSON.stringify(normalizeMemoryContext(binding.memoryContext))) {
|
|
1094
|
+
const ids = new Set((media.occurrenceIds || []).filter(id => typeof id === 'string'))
|
|
1095
|
+
const consumed = (binding.pendingMedia || []).filter(item => ids.has(item.occurrenceId)
|
|
1096
|
+
&& JSON.stringify(item.mediaScope) === JSON.stringify(media.scope))
|
|
1097
|
+
committed.media = { scope: structuredClone(media.scope), occurrences: structuredClone(consumed) }
|
|
1098
|
+
const consumedIds = new Set(consumed.map(item => item.occurrenceId))
|
|
1099
|
+
binding.pendingMedia = (binding.pendingMedia || []).filter(item => !consumedIds.has(item.occurrenceId))
|
|
1100
|
+
}
|
|
1101
|
+
binding.lastInjectedTurn = Math.max(Number(binding.lastInjectedTurn || 0), Number(memoryClock))
|
|
1102
|
+
if (typed.length || actions.anchor) binding.lastInjectedAt = stamp()
|
|
1103
|
+
return state
|
|
1104
|
+
})
|
|
1105
|
+
if (committed) flushState()
|
|
1106
|
+
return committed ? structuredClone(committed) : null
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/**
|
|
1110
|
+
* A durable copy of pending admission proposals. `injectionAdmissions` is an
|
|
1111
|
+
* in-process Map, so proposals would be lost across host restarts or when another
|
|
1112
|
+
* process observes the same home. Persist only minimal commit credentials keyed by
|
|
1113
|
+
* message-content digest so another observer can complete admission. Keep the most
|
|
1114
|
+
* recent 8 entries; reposts replace matching digests and older entries are evicted.
|
|
1115
|
+
*/
|
|
1116
|
+
const PENDING_INJECTION_MAX = 8
|
|
1117
|
+
// 凭据只为「这一轮内的跨进程补认」服务:崩溃错过 turn/end 时它可能残留,
|
|
1118
|
+
// 同内容重投(锚点文本高度重复)会认领到最旧那条、把 turn 归属记错。
|
|
1119
|
+
// 读取时按 30 分钟 TTL 过滤并取最新匹配;写入时顺手清扫过期项。
|
|
1120
|
+
const PENDING_INJECTION_TTL_MS = 30 * 60 * 1000
|
|
1121
|
+
|
|
1122
|
+
function pendingInjectionFresh(item, now = Date.now()) {
|
|
1123
|
+
const at = Date.parse(item?.at || '')
|
|
1124
|
+
return Number.isFinite(at) && now - at < PENDING_INJECTION_TTL_MS
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
export function rememberPendingInjection(sessionId, record = {}) {
|
|
1128
|
+
if (!sessionId || !record.digest || !record.messageId) return null
|
|
1129
|
+
return updateState((state) => {
|
|
1130
|
+
const binding = state.sessions[sessionId]
|
|
1131
|
+
if (!binding) return state
|
|
1132
|
+
const kept = (binding.pendingInjections || []).filter(item => item?.messageId !== record.messageId && pendingInjectionFresh(item))
|
|
1133
|
+
kept.push({
|
|
1134
|
+
digest: String(record.digest), messageId: String(record.messageId),
|
|
1135
|
+
turn: Number(record.turn) || 0, clock: Number(record.clock) || 0,
|
|
1136
|
+
generation: Number(record.generation) || 0, epoch: Number(record.epoch) || 0,
|
|
1137
|
+
refs: Array.isArray(record.refs) ? record.refs : [],
|
|
1138
|
+
actions: record.actions && typeof record.actions === 'object' ? record.actions : {},
|
|
1139
|
+
at: stamp(),
|
|
1140
|
+
})
|
|
1141
|
+
binding.pendingInjections = kept.slice(-PENDING_INJECTION_MAX)
|
|
1142
|
+
return state
|
|
1143
|
+
})
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
export function findPendingInjection(sessionId, digest, messageId = null) {
|
|
1147
|
+
if (!sessionId || !digest) return null
|
|
1148
|
+
const rows = (getSessionBinding(sessionId)?.pendingInjections || [])
|
|
1149
|
+
.filter(item => item?.digest === digest && pendingInjectionFresh(item)
|
|
1150
|
+
&& (!item.actions?.media?.occurrenceIds?.length || item.messageId === messageId))
|
|
1151
|
+
return rows[rows.length - 1] || null
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
export function forgetPendingInjection(sessionId, messageId) {
|
|
1155
|
+
if (!sessionId || !messageId) return null
|
|
1156
|
+
return updateState((state) => {
|
|
1157
|
+
const binding = state.sessions[sessionId]
|
|
1158
|
+
if (!binding?.pendingInjections) return state
|
|
1159
|
+
const kept = binding.pendingInjections.filter(item => item?.messageId !== messageId)
|
|
1160
|
+
if (kept.length) binding.pendingInjections = kept
|
|
1161
|
+
else delete binding.pendingInjections
|
|
1162
|
+
return state
|
|
1163
|
+
})
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
export function markInjected(sessionId, ids, turn) {
|
|
1167
|
+
if (!sessionId) return
|
|
1168
|
+
return updateState((state) => {
|
|
1169
|
+
const binding = state.sessions[sessionId]
|
|
1170
|
+
if (!binding) return state
|
|
1171
|
+
// 锚点哨兵不进 injectedIds:它是一份常驻提示,不是会被 400 条上限挤掉的记忆 id。
|
|
1172
|
+
// 单独记 anchorPushed,避免长会话里周期性把 ~800 token 的锚点当新消息重投。
|
|
1173
|
+
const incoming = ids || []
|
|
1174
|
+
// 旧 binding 可能把哨兵存在 injectedIds 里:迁移为 anchorPushed,之后只按标记判断。
|
|
1175
|
+
const anchor = incoming.includes('__anchor__') || (binding.injectedIds || []).includes('__anchor__')
|
|
1176
|
+
const merged = [...new Set([
|
|
1177
|
+
...(binding.injectedIds || []).filter((id) => id !== '__anchor__'),
|
|
1178
|
+
...incoming.filter((id) => id !== '__anchor__'),
|
|
1179
|
+
])]
|
|
1180
|
+
binding.injectedIds = merged.slice(-400)
|
|
1181
|
+
const owner = `legacy:${crypto.randomUUID()}`
|
|
1182
|
+
binding.injectionOwners = { ...(binding.injectionOwners || {}) }
|
|
1183
|
+
if (anchor) { binding.anchorPushed = true; binding.injectionOwners.anchorPushed = owner }
|
|
1184
|
+
const at = { ...(binding.injectedAt || {}) }
|
|
1185
|
+
for (const id of incoming) {
|
|
1186
|
+
at[id] = turn ?? Date.now()
|
|
1187
|
+
binding.injectionOwners[`id:${id}`] = owner
|
|
1188
|
+
}
|
|
1189
|
+
binding.injectedAt = at
|
|
1190
|
+
binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
|
|
1191
|
+
// 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
|
|
1192
|
+
binding.lastInjectedAt = stamp()
|
|
1193
|
+
return state
|
|
1194
|
+
})
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
/**
|
|
1198
|
+
* Records why the last per-turn recall produced nothing usable. A degraded
|
|
1199
|
+
* recall used to be swallowed by an empty catch, which made "memory is dead"
|
|
1200
|
+
* indistinguishable from "nothing was relevant" (P0-1).
|
|
1201
|
+
*/
|
|
1202
|
+
export function setRecallError(sessionId, message) {
|
|
1203
|
+
if (!sessionId) return
|
|
1204
|
+
const next = message ? String(message).slice(0, 500) : null
|
|
1205
|
+
return updateState((state) => {
|
|
1206
|
+
const binding = state.sessions[sessionId]
|
|
1207
|
+
if (!binding) return state
|
|
1208
|
+
if (next === null) {
|
|
1209
|
+
// Only clear when something is there, so a healthy turn costs no write.
|
|
1210
|
+
if (binding.lastRecallError) {
|
|
1211
|
+
delete binding.lastRecallError
|
|
1212
|
+
delete binding.lastRecallErrorAt
|
|
1213
|
+
}
|
|
1214
|
+
return state
|
|
1215
|
+
}
|
|
1216
|
+
if (binding.lastRecallError === next) return state
|
|
1217
|
+
binding.lastRecallError = next
|
|
1218
|
+
binding.lastRecallErrorAt = stamp()
|
|
1219
|
+
return state
|
|
1220
|
+
})
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
export function releaseInjected(sessionId) { return updateState((state) => {
|
|
1224
|
+
const binding = state.sessions[sessionId]
|
|
1225
|
+
if (binding) {
|
|
1226
|
+
binding.injectedIds = []
|
|
1227
|
+
binding.injectedAt = {}
|
|
1228
|
+
binding.injectionEpoch = Number(binding.injectionEpoch || 0) + 1
|
|
1229
|
+
}
|
|
1230
|
+
return state
|
|
1231
|
+
})
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
export function markReinjectPending(sessionId) {
|
|
1235
|
+
const binding = getSessionBinding(sessionId)
|
|
1236
|
+
return setSessionBinding(sessionId, { reinjectPending: true, injectionEpoch: Number(binding?.injectionEpoch || 0) + 1 })
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
export function clearReinjectPending(sessionId) {
|
|
1240
|
+
return setSessionBinding(sessionId, { reinjectPending: false })
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
export function getActiveCue(sessionId) {
|
|
1244
|
+
const binding = getSessionBinding(sessionId)
|
|
1245
|
+
const cue = binding?.activeCue
|
|
1246
|
+
if (!cue || typeof cue.id !== 'string') return null
|
|
1247
|
+
const at = Date.parse(cue.createdAt || '') || 0
|
|
1248
|
+
if (!at || Date.now() - at > 30 * 60 * 1000) return null
|
|
1249
|
+
return cue
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
export function armCue(sessionId, cue) {
|
|
1253
|
+
return setSessionBinding(sessionId, {
|
|
1254
|
+
activeCue: {
|
|
1255
|
+
id: String(cue.id),
|
|
1256
|
+
text: String(cue.text || '').slice(0, 500),
|
|
1257
|
+
// A derived cue remembers the memory it came out of. Kept on the binding so the
|
|
1258
|
+
// source is auditable while the cue is live, and so the anti-loop rule (a cue-born
|
|
1259
|
+
// memory never sources another cue) can be checked against what actually happened.
|
|
1260
|
+
sourceId: cue.sourceId ? String(cue.sourceId) : null,
|
|
1261
|
+
recallQuery: cue.recallQuery ? String(cue.recallQuery).slice(0, 200) : null,
|
|
1262
|
+
createdAt: stamp(),
|
|
1263
|
+
},
|
|
1264
|
+
})
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
export function consumeCue(sessionId, cueId) {
|
|
1268
|
+
const binding = getSessionBinding(sessionId)
|
|
1269
|
+
if (!binding?.activeCue || binding.activeCue.id !== cueId) return false
|
|
1270
|
+
setSessionBinding(sessionId, { activeCue: null })
|
|
1271
|
+
return true
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
// The session's running mood is a retrieval lens on the binding, not a fact about
|
|
1275
|
+
// the user: it must never be recalled as a stored memory.
|
|
1276
|
+
export function setSessionMood(sessionId, mood) {
|
|
1277
|
+
// 给了 emotion 就以四轴为准,valence 只是投影;只有 valence 的旧形状原样存,不反推四轴。
|
|
1278
|
+
const emotion = normalizeEmotion(mood?.emotion ?? null)
|
|
1279
|
+
const bounded = (raw, min, max) => Math.max(min, Math.min(max, Number.isFinite(raw) ? raw : 0)) // 显式 0 是读数的一部分,不能用 `|| 默认值`
|
|
1280
|
+
return setSessionBinding(sessionId, { mood: {
|
|
1281
|
+
valence: emotion ? derivedValence(emotion) : bounded(mood?.valence, -1, 1),
|
|
1282
|
+
emotion, arousal: bounded(mood?.arousal, 0, 1), dominance: bounded(mood?.dominance, -1, 1), at: Date.now(),
|
|
1283
|
+
} })
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
export function getSessionMood(sessionId) {
|
|
1287
|
+
return getSessionBinding(sessionId)?.mood || null
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
export function setLastSleepAt(sessionId, at) {
|
|
1291
|
+
return setSessionBinding(sessionId, { lastSleepAt: at || stamp() })
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
export function getLastSleepAt(sessionId) {
|
|
1295
|
+
return getSessionBinding(sessionId)?.lastSleepAt || null
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
export function listSessionBindings() {
|
|
1299
|
+
const state = loadState()
|
|
1300
|
+
return Object.entries(state.sessions || {}).map(([sessionId, binding]) => ({ sessionId, ...binding }))
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
// The idle clock that sleep consolidation measures against: the last turn the
|
|
1304
|
+
// plugin actually saw for this session.
|
|
1305
|
+
export function touchSession(sessionId) {
|
|
1306
|
+
return setSessionBinding(sessionId, { lastTurnAt: stamp() })
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
export function getCycleState() {
|
|
1310
|
+
return loadState().cycle || {}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
export function setCycleState(patch) {
|
|
1314
|
+
return updateState((state) => {
|
|
1315
|
+
state.cycle = { ...(state.cycle || {}), ...(patch || {}) }
|
|
1316
|
+
return state
|
|
1317
|
+
}).cycle
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// An anniversary fires once per calendar day per memory, otherwise every turn of
|
|
1321
|
+
// the day would reopen the same feeling.
|
|
1322
|
+
export function wasAnniversaryShown(sessionId, memoryId, dayKey) {
|
|
1323
|
+
const shown = getSessionBinding(sessionId)?.anniversariesShown
|
|
1324
|
+
return Boolean(shown && shown[memoryId] === dayKey)
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
export function markAnniversaryShown(sessionId, memoryId, dayKey) {
|
|
1328
|
+
const binding = getSessionBinding(sessionId)
|
|
1329
|
+
const shown = { ...(binding?.anniversariesShown || {}) }
|
|
1330
|
+
// Keep only the current day's keys so the map cannot grow without bound.
|
|
1331
|
+
const fresh = Object.fromEntries(Object.entries(shown).filter(([, v]) => v === dayKey))
|
|
1332
|
+
fresh[memoryId] = dayKey
|
|
1333
|
+
return setSessionBinding(sessionId, { anniversariesShown: fresh,
|
|
1334
|
+
injectionOwners: { ...(binding?.injectionOwners || {}), [`anniversary:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
// ── repeated open loops ────────────────────────────────────────────────────────
|
|
1338
|
+
// A dated promise that has already slipped its day keeps coming back on an interval
|
|
1339
|
+
// instead of being forgotten. The regular 3-day nudge records its ids in
|
|
1340
|
+
// `injectedIds`, which is right for "I already mentioned this once" and wrong for
|
|
1341
|
+
// "it was never closed"; that is why the overdue leg keeps its own clock.
|
|
1342
|
+
//
|
|
1343
|
+
// `openLoopRemindedAt` maps memoryId -> ISO timestamp of the last time the overdue
|
|
1344
|
+
// nudge actually reached the prompt. Entries older than 90 days are dropped on
|
|
1345
|
+
// write so the map cannot grow without bound (an old key would not suppress
|
|
1346
|
+
// anything anyway — the interval has long elapsed).
|
|
1347
|
+
const OPEN_LOOP_REMIND_PRUNE_MS = 90 * 86_400_000
|
|
1348
|
+
|
|
1349
|
+
function localDayKeyOf(date) {
|
|
1350
|
+
return localCalendarDay(date)
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
function prunedOpenLoopReminded(sessionId, now = new Date()) {
|
|
1354
|
+
const nowDate = now instanceof Date ? now : new Date(now)
|
|
1355
|
+
const nowMs = nowDate.getTime()
|
|
1356
|
+
const map = getSessionBinding(sessionId)?.openLoopRemindedAt
|
|
1357
|
+
const fresh = {}
|
|
1358
|
+
if (!map || typeof map !== 'object') return fresh
|
|
1359
|
+
for (const [memoryId, iso] of Object.entries(map)) {
|
|
1360
|
+
const at = Date.parse(String(iso || ''))
|
|
1361
|
+
if (!Number.isFinite(at)) continue
|
|
1362
|
+
if (nowMs - at > OPEN_LOOP_REMIND_PRUNE_MS) continue
|
|
1363
|
+
fresh[memoryId] = map[memoryId]
|
|
1364
|
+
}
|
|
1365
|
+
return fresh
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
/**
|
|
1369
|
+
* Whether an overdue open loop was already repeated on this local calendar day.
|
|
1370
|
+
* A session binding written before this field existed has no map: it is a first
|
|
1371
|
+
* reminder, not an error.
|
|
1372
|
+
*/
|
|
1373
|
+
export function wasOpenLoopRemindedToday(sessionId, memoryId, now = new Date()) {
|
|
1374
|
+
if (!sessionId || !memoryId) return false
|
|
1375
|
+
const iso = getSessionBinding(sessionId)?.openLoopRemindedAt?.[memoryId]
|
|
1376
|
+
const at = Date.parse(String(iso || ''))
|
|
1377
|
+
if (!Number.isFinite(at)) return false
|
|
1378
|
+
return localDayKeyOf(at) === localDayKeyOf(now)
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
export function markOpenLoopReminded(sessionId, memoryId, at = new Date()) {
|
|
1382
|
+
if (!sessionId || !memoryId) return null
|
|
1383
|
+
// No binding means no conversation to remind; creating a stub from here would
|
|
1384
|
+
// write half a session into state.json.
|
|
1385
|
+
if (!getSessionBinding(sessionId)) return null
|
|
1386
|
+
const when = at instanceof Date ? at : new Date(at)
|
|
1387
|
+
const reminded = prunedOpenLoopReminded(sessionId, when)
|
|
1388
|
+
reminded[memoryId] = when.toISOString()
|
|
1389
|
+
return setSessionBinding(sessionId, { openLoopRemindedAt: reminded,
|
|
1390
|
+
injectionOwners: { ...(getSessionBinding(sessionId)?.injectionOwners || {}), [`nudge:${memoryId}`]: `legacy:${crypto.randomUUID()}` } })
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
/**
|
|
1394
|
+
* 记下"这一回合投放了哪些一次性内容",供宿主把整轮回滚时撤销记账(§3.24)。
|
|
1395
|
+
* 同一个 hostTurn 多次调用会把 ids 并起来:一步里可能同时投了锚点、纪念日与 nudge。
|
|
1396
|
+
*/
|
|
1397
|
+
export function recordInjectionRollback(sessionId, { hostTurn, ids = [], guideKey = null, nudgeIds = [], anniversaryIds = [] } = {}) {
|
|
1398
|
+
const turn = Number(hostTurn)
|
|
1399
|
+
if (!sessionId || !Number.isSafeInteger(turn) || turn < 0) return null
|
|
1400
|
+
if (!getSessionBinding(sessionId)) return null
|
|
1401
|
+
return updateState((state) => {
|
|
1402
|
+
const binding = state.sessions[sessionId]
|
|
1403
|
+
if (!binding) return state
|
|
1404
|
+
const previous = binding.injectionRollback
|
|
1405
|
+
const same = previous && previous.hostTurn === turn ? previous : { ids: [], nudgeIds: [], anniversaryIds: [] }
|
|
1406
|
+
binding.injectionRollback = {
|
|
1407
|
+
hostTurn: turn,
|
|
1408
|
+
epoch: Number(binding.injectionEpoch || 0),
|
|
1409
|
+
generation: Number(binding.scopeGeneration || 0),
|
|
1410
|
+
snapshot: { owners: { ...binding.injectionOwners }, injectedAt: { ...binding.injectedAt }, anchorPushed: binding.anchorPushed,
|
|
1411
|
+
lastInjectedUserMessageId: binding.lastInjectedUserMessageId, guideMessageAt: binding.guideMessageAt,
|
|
1412
|
+
anniversariesShown: { ...binding.anniversariesShown }, openLoopRemindedAt: { ...binding.openLoopRemindedAt } },
|
|
1413
|
+
ids: [...new Set([...(same.ids || []), ...ids])].slice(-400),
|
|
1414
|
+
nudgeIds: [...new Set([...(same.nudgeIds || []), ...nudgeIds])].slice(-40),
|
|
1415
|
+
anniversaryIds: [...new Set([...(same.anniversaryIds || []), ...anniversaryIds])].slice(-40),
|
|
1416
|
+
guideKey: guideKey || same.guideKey || null,
|
|
1417
|
+
}
|
|
1418
|
+
return state
|
|
1419
|
+
}).sessions[sessionId].injectionRollback
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/**
|
|
1423
|
+
* Roll back bookkeeping for a host turn that was returned before the request was sent.
|
|
1424
|
+
* The plugin records admission after handing messages to the host; a failed request
|
|
1425
|
+
* can therefore leave one-time guide and anchor state for messages absent from the
|
|
1426
|
+
* transcript. Roll back only the matching hostTurn, and only when the caller has
|
|
1427
|
+
* evidence from the transcript that the messages were not admitted. Return the revoked
|
|
1428
|
+
* records so the activity log can retain an observable signal.
|
|
1429
|
+
*/
|
|
1430
|
+
export function rollbackInjectionForTurn(sessionId, hostTurn, { messageIds = [], epoch = null } = {}) {
|
|
1431
|
+
const turn = Number(hostTurn)
|
|
1432
|
+
if (!sessionId || !Number.isSafeInteger(turn)) return null
|
|
1433
|
+
let rolled = null
|
|
1434
|
+
updateState((state) => {
|
|
1435
|
+
const binding = state.sessions[sessionId]
|
|
1436
|
+
if (!binding) return state
|
|
1437
|
+
// Explicit host rollback evidence can revoke individual accepted messages. A model
|
|
1438
|
+
// request failure alone must never call this branch. Preserve immutable records.
|
|
1439
|
+
const targets = (binding.acceptedMemoryMessages || []).filter(record => record.hostTurn === turn
|
|
1440
|
+
&& messageIds.includes(record.messageId) && (epoch === null || record.epoch === epoch))
|
|
1441
|
+
for (const accepted of targets.reverse()) {
|
|
1442
|
+
binding.revokedInjectionMessages = [...new Set([...(binding.revokedInjectionMessages || []), accepted.messageId])].slice(-400)
|
|
1443
|
+
if (accepted.epoch !== Number(binding.injectionEpoch || 0) || accepted.generation !== Number(binding.scopeGeneration || 0)) continue
|
|
1444
|
+
const media = accepted.media
|
|
1445
|
+
if (media?.scope && media.scope.incarnation === binding.mediaIncarnation && media.scope.libraryId === binding.libraryId
|
|
1446
|
+
&& media.scope.contextKey === JSON.stringify(normalizeMemoryContext(binding.memoryContext))) {
|
|
1447
|
+
const pendingIds = new Set((binding.pendingMedia || []).map(item => item.occurrenceId))
|
|
1448
|
+
const consumedElsewhere = new Set((binding.acceptedMemoryMessages || [])
|
|
1449
|
+
.filter(record => !binding.revokedInjectionMessages.includes(record.messageId))
|
|
1450
|
+
.flatMap(record => record.media?.occurrences?.map(item => item.occurrenceId) || []))
|
|
1451
|
+
binding.pendingMedia = [...(media.occurrences || []).filter(item => !pendingIds.has(item.occurrenceId)
|
|
1452
|
+
&& !consumedElsewhere.has(item.occurrenceId)), ...(binding.pendingMedia || [])]
|
|
1453
|
+
}
|
|
1454
|
+
for (const [key, saved] of Object.entries(accepted.effects || {})) {
|
|
1455
|
+
if (binding.injectionOwners?.[key] !== accepted.messageId) continue
|
|
1456
|
+
let previous = saved
|
|
1457
|
+
const visited = new Set()
|
|
1458
|
+
while (previous.owner && binding.revokedInjectionMessages.includes(previous.owner) && !visited.has(previous.owner)) {
|
|
1459
|
+
visited.add(previous.owner)
|
|
1460
|
+
const revoked = (binding.acceptedMemoryMessages || []).find(record => record.messageId === previous.owner)
|
|
1461
|
+
previous = revoked?.effects?.[key] || { ...previous, value: undefined, owner: null, clock: null }
|
|
1462
|
+
}
|
|
1463
|
+
const field = previous.field || key
|
|
1464
|
+
if (previous.id !== undefined && previous.id !== null) {
|
|
1465
|
+
if (previous.value === undefined) delete binding[field]?.[previous.id]
|
|
1466
|
+
else binding[field] = { ...(binding[field] || {}), [previous.id]: structuredClone(previous.value) }
|
|
1467
|
+
if (field === 'injectedAt' && previous.value === undefined) binding.injectedIds = (binding.injectedIds || []).filter(id => id !== previous.id)
|
|
1468
|
+
} else if (previous.value === undefined) delete binding[field]
|
|
1469
|
+
else binding[field] = structuredClone(previous.value)
|
|
1470
|
+
if (previous.owner) binding.injectionOwners[key] = previous.owner
|
|
1471
|
+
else delete binding.injectionOwners[key]
|
|
1472
|
+
if (previous.clock !== undefined && previous.clock !== null) binding.injectionOwnerClocks[key] = previous.clock
|
|
1473
|
+
else delete binding.injectionOwnerClocks?.[key]
|
|
1474
|
+
}
|
|
1475
|
+
for (const ref of accepted.refs) {
|
|
1476
|
+
if (accepted.effects?.[`id:${ref.id}`] || binding.injectionOwners?.[`id:${ref.id}`] !== accepted.messageId) continue
|
|
1477
|
+
delete binding.injectedAt?.[ref.id]
|
|
1478
|
+
binding.injectedIds = (binding.injectedIds || []).filter(id => id !== ref.id)
|
|
1479
|
+
delete binding.injectionOwners[`id:${ref.id}`]
|
|
1480
|
+
}
|
|
1481
|
+
for (const key of Object.keys(binding.injectionOwners || {})) {
|
|
1482
|
+
if (binding.injectionOwners[key] !== accepted.messageId) continue
|
|
1483
|
+
if (key.startsWith('anniversary:')) delete binding.anniversariesShown?.[key.slice(12)]
|
|
1484
|
+
if (key.startsWith('nudge:')) delete binding.openLoopRemindedAt?.[key.slice(6)]
|
|
1485
|
+
delete binding.injectionOwners[key]
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
if (targets.length) rolled = { ids: targets.flatMap(record => record.refs.map(ref => ref.id)), guideKey: null, anniversaries: 0, nudges: 0 }
|
|
1489
|
+
const record = binding.injectionRollback
|
|
1490
|
+
if (!record || record.hostTurn !== turn) return state
|
|
1491
|
+
const snapshot = record.snapshot || {}
|
|
1492
|
+
const owners = binding.injectionOwners || {}
|
|
1493
|
+
const sameEpoch = record.epoch === Number(binding.injectionEpoch || 0)
|
|
1494
|
+
&& Number(record.generation || 0) === Number(binding.scopeGeneration || 0)
|
|
1495
|
+
const owns = key => owners[key] === snapshot.owners?.[key] && (!owners[key] || owners[key].startsWith('legacy:'))
|
|
1496
|
+
const ids = new Set((record.ids || []).filter(id => sameEpoch && owns(`id:${id}`)
|
|
1497
|
+
&& binding.injectedAt?.[id] === snapshot.injectedAt?.[id]))
|
|
1498
|
+
binding.injectedIds = (binding.injectedIds || []).filter(id => !ids.has(id))
|
|
1499
|
+
if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
|
|
1500
|
+
if (sameEpoch && ids.has('__anchor__') && owns('anchorPushed') && binding.anchorPushed === snapshot.anchorPushed) delete binding.anchorPushed
|
|
1501
|
+
if (sameEpoch && snapshot.lastInjectedUserMessageId !== undefined && owns('lastInjectedUserMessageId')
|
|
1502
|
+
&& binding.lastInjectedUserMessageId === snapshot.lastInjectedUserMessageId) delete binding.lastInjectedUserMessageId
|
|
1503
|
+
if (sameEpoch && owns('guideRulesKey') && record.guideKey && binding.guideRulesKey === record.guideKey
|
|
1504
|
+
&& binding.guideMessageAt === snapshot.guideMessageAt) {
|
|
1505
|
+
delete binding.guideRulesKey
|
|
1506
|
+
delete binding.guideMessageAt
|
|
1507
|
+
}
|
|
1508
|
+
if (sameEpoch && binding.anniversariesShown) for (const id of record.anniversaryIds || []) {
|
|
1509
|
+
if (owns(`anniversary:${id}`) && binding.anniversariesShown[id] === snapshot.anniversariesShown?.[id]) delete binding.anniversariesShown[id]
|
|
1510
|
+
}
|
|
1511
|
+
if (sameEpoch && binding.openLoopRemindedAt) for (const id of record.nudgeIds || []) {
|
|
1512
|
+
if (owns(`nudge:${id}`) && binding.openLoopRemindedAt[id] === snapshot.openLoopRemindedAt?.[id]) delete binding.openLoopRemindedAt[id]
|
|
1513
|
+
}
|
|
1514
|
+
rolled = {
|
|
1515
|
+
ids: [...ids],
|
|
1516
|
+
guideKey: record.guideKey || null,
|
|
1517
|
+
anniversaries: (record.anniversaryIds || []).length,
|
|
1518
|
+
nudges: (record.nudgeIds || []).length,
|
|
1519
|
+
}
|
|
1520
|
+
delete binding.injectionRollback
|
|
1521
|
+
return state
|
|
1522
|
+
})
|
|
1523
|
+
return rolled
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
/**
|
|
1527
|
+
* 回合收尾、但那份记账不该作废时消费掉它(正常完成,或失败时注入的消息其实已经进了转录):
|
|
1528
|
+
* 东西已经投出去了,之后再来一条迟到的 error 事件也不该把它撤回(否则就是凭空的第二次锚点/规则消息)。
|
|
1529
|
+
*/
|
|
1530
|
+
export function consumeInjectionRollback(sessionId, hostTurn) {
|
|
1531
|
+
const turn = Number(hostTurn)
|
|
1532
|
+
if (!sessionId || !Number.isSafeInteger(turn)) return false
|
|
1533
|
+
let consumed = false
|
|
1534
|
+
updateState((state) => {
|
|
1535
|
+
const binding = state.sessions[sessionId]
|
|
1536
|
+
if (!binding?.injectionRollback || binding.injectionRollback.hostTurn !== turn) return state
|
|
1537
|
+
delete binding.injectionRollback
|
|
1538
|
+
consumed = true
|
|
1539
|
+
return state
|
|
1540
|
+
})
|
|
1541
|
+
return consumed
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
export function memoryDbPath(libraryId) {
|
|
1545
|
+
ensureDir(librariesDir())
|
|
1546
|
+
return effectiveVectorRoute() === 'managed-local' ? memuDbFor(libraryId) : path.join(librariesDir(), `${libraryId}.sqlite3`)
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
export function globalDbPath() {
|
|
1550
|
+
ensureDir(dataDir())
|
|
1551
|
+
return effectiveVectorRoute() === 'managed-local' ? memuGlobalDbFor() : GLOBAL_DB()
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// Index files are parsed on every folder in the sidebar, and the parse (full
|
|
1555
|
+
// memory text) is the expensive part. Validity is mtime+size, so an external
|
|
1556
|
+
// change is always picked up. Callers mutate the returned object and save it
|
|
1557
|
+
// straight away — that is the shape every writer already had.
|
|
1558
|
+
const indexCache = new Map()
|
|
1559
|
+
const indexBases = new WeakMap()
|
|
1560
|
+
|
|
1561
|
+
// The sidebar paints a snapshot of both indexes, and nothing used to tell it when
|
|
1562
|
+
// that snapshot had gone stale: a memory written by a tool call, or from the
|
|
1563
|
+
// settings pane, stayed invisible until the tab was remounted. Readers poll this
|
|
1564
|
+
// counter and refetch only when it moves, so the cheap path is a single number —
|
|
1565
|
+
// no entry bodies, no disk read. In-process only; it resets on restart, and that
|
|
1566
|
+
// is fine because readers compare it against the number they last painted.
|
|
1567
|
+
let sidebarRevision = 0
|
|
1568
|
+
|
|
1569
|
+
function bumpMemoryRevision() {
|
|
1570
|
+
sidebarRevision += 1
|
|
1571
|
+
return sidebarRevision
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
/** Monotonic within this process; see bumpMemoryRevision. */
|
|
1575
|
+
export function memoryRevision() {
|
|
1576
|
+
return sidebarRevision
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
// Task E observability. A heartbeat is a client poll; a write event is a save that
|
|
1580
|
+
// actually reached disk. Both are in-process timestamps (they reset with the host),
|
|
1581
|
+
// and `memu_status` prints them so "the pane is stale" can be told apart from
|
|
1582
|
+
// "nothing was written" and from "the pane never polled".
|
|
1583
|
+
let lastBeatAt = null
|
|
1584
|
+
let lastWriteEvent = null
|
|
1585
|
+
|
|
1586
|
+
export function noteMemoryBeat() {
|
|
1587
|
+
lastBeatAt = Date.now()
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
function noteMemoryWrite(kind, libraryId) {
|
|
1591
|
+
lastWriteEvent = { kind, libraryId: libraryId || null, at: Date.now() }
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
export function syncActivity() {
|
|
1595
|
+
return { lastBeatAt, lastWrite: lastWriteEvent }
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
// The counter above is per-process, and not every write happens in this process:
|
|
1599
|
+
// a tool call served by another module instance, a curator job, or a second window
|
|
1600
|
+
// can save an index while this counter stays put. That is exactly how the sidebar
|
|
1601
|
+
// ended up needing a manual Refresh — the heartbeat compared a number only the
|
|
1602
|
+
// writer's process could move. This fingerprint is the half both processes share:
|
|
1603
|
+
// size and mtime of every file a memory write touches. A handful of statSync calls
|
|
1604
|
+
// is cheaper than parsing one index, and it cannot go stale.
|
|
1605
|
+
export function memoryStamp() {
|
|
1606
|
+
const parts = []
|
|
1607
|
+
const add = (file, label) => {
|
|
1608
|
+
try {
|
|
1609
|
+
const info = fs.statSync(file)
|
|
1610
|
+
parts.push(label + ":" + info.size + ":" + Math.round(info.mtimeMs))
|
|
1611
|
+
} catch {
|
|
1612
|
+
parts.push(label + ":-")
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
add(STATE_FILE(), "state")
|
|
1616
|
+
add(GLOBAL_INDEX(), "global")
|
|
1617
|
+
let names = []
|
|
1618
|
+
try { names = fs.readdirSync(indexDir()).filter((name) => name.endsWith(".json")).sort() } catch {}
|
|
1619
|
+
for (const name of names) add(path.join(indexDir(), name), name)
|
|
1620
|
+
return parts.join("|")
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
function cachedIndex(file, loader, normalize) {
|
|
1624
|
+
const cached = indexCache.get(file)
|
|
1625
|
+
const stat = statOf(file)
|
|
1626
|
+
if (cached && stat && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return indexSnapshot(cached.index, normalize)
|
|
1627
|
+
const index = loader()
|
|
1628
|
+
// Never cache a fallback produced by a failed read: it would keep shadowing the
|
|
1629
|
+
// real file (whose mtime/size did not change) even after the read recovers.
|
|
1630
|
+
if (stat && !readFailure(file)) indexCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, index })
|
|
1631
|
+
return indexSnapshot(index, normalize)
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
// `normalize` upgrades the *view* (a level an older version stored), while the baseline
|
|
1635
|
+
// stays exactly what is on disk. That split is what lets an ordinary write persist the
|
|
1636
|
+
// upgrade: `writeIndex` diffs against the baseline, sees the change, and checks the file
|
|
1637
|
+
// still matches what we read before accepting it.
|
|
1638
|
+
function indexSnapshot(index, normalize) {
|
|
1639
|
+
const baseline = structuredClone(index)
|
|
1640
|
+
const copy = structuredClone(index)
|
|
1641
|
+
if (normalize) normalize(copy)
|
|
1642
|
+
indexBases.set(copy, baseline)
|
|
1643
|
+
return copy
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
function rememberIndex(file, index) {
|
|
1647
|
+
const stat = statOf(file)
|
|
1648
|
+
if (stat) indexCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, index: structuredClone(index) })
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
const indexWriteListeners = new Set()
|
|
1652
|
+
export function onPrivateIndexWrite(listener) {
|
|
1653
|
+
indexWriteListeners.add(listener)
|
|
1654
|
+
return () => indexWriteListeners.delete(listener)
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
function writeIndex(file, index) {
|
|
1658
|
+
return withFileLock(file, () => {
|
|
1659
|
+
const base = indexBases.get(index)
|
|
1660
|
+
let next = index
|
|
1661
|
+
if (base) {
|
|
1662
|
+
const fresh = readJson(file, { version: 1, entries: {} })
|
|
1663
|
+
if (!validIndex(fresh)) {
|
|
1664
|
+
assertJsonShape(file, fresh, validIndex)
|
|
1665
|
+
throw new Error('memory index changed to an invalid shape; restore it before writing')
|
|
1666
|
+
}
|
|
1667
|
+
next = { ...fresh, entries: { ...(fresh.entries || {}) } }
|
|
1668
|
+
const before = base.entries || {}
|
|
1669
|
+
for (const id of new Set([...Object.keys(before), ...Object.keys(index.entries || {})])) {
|
|
1670
|
+
const value = index.entries?.[id]
|
|
1671
|
+
if (JSON.stringify(before[id]) === JSON.stringify(value)) continue
|
|
1672
|
+
if (JSON.stringify(before[id]) !== JSON.stringify(next.entries[id])) {
|
|
1673
|
+
const error = new Error(`memory ${id} changed concurrently; reload and retry`)
|
|
1674
|
+
error.code = 'DSH_MEMU_CONCURRENT_MODIFICATION'
|
|
1675
|
+
throw error
|
|
1676
|
+
}
|
|
1677
|
+
if (value === undefined) delete next.entries[id]
|
|
1678
|
+
else next.entries[id] = structuredClone(value)
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
writeJson(file, next)
|
|
1682
|
+
rememberIndex(file, next)
|
|
1683
|
+
return next
|
|
1684
|
+
})
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
export function loadPrivateIndex(libraryId) {
|
|
1688
|
+
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
1689
|
+
const file = path.join(indexDir(), `${libraryId}.json`)
|
|
1690
|
+
return cachedIndex(file, () => {
|
|
1691
|
+
let raw = readJson(file, null)
|
|
1692
|
+
if (raw !== null) raw = assertJsonShape(file, raw, validIndex)
|
|
1693
|
+
return raw && typeof raw === 'object' ? { version: 1, entries: raw.entries || {} } : { version: 1, entries: {} }
|
|
1694
|
+
}, (index) => {
|
|
1695
|
+
// An older version stored `visibility: 'session'` (a lease on one conversation).
|
|
1696
|
+
// That level is gone; libraries written by it are read as `shared` here — the one
|
|
1697
|
+
// chokepoint every reader and writer passes through — so no consumer has to know
|
|
1698
|
+
// the level ever existed. Only the view is upgraded; the baseline stays the raw file
|
|
1699
|
+
// so the next ordinary write persists the conversion (see `indexSnapshot`).
|
|
1700
|
+
migrateIndexVisibility(index, stamp())
|
|
1701
|
+
})
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
/**
|
|
1705
|
+
* Persist one library index.
|
|
1706
|
+
*
|
|
1707
|
+
* `bumpRevision: false` exists for writes that cannot change what recall would find:
|
|
1708
|
+
* the injector's own bookkeeping (injectCount / lastInjectAt) runs *after* every
|
|
1709
|
+
* successful injection, so bumping the revision there guaranteed that the next turn's
|
|
1710
|
+
* recall and BM25 corpus both missed. The write still happens, still notifies
|
|
1711
|
+
* listeners and still records the write event — only the "something a cached result
|
|
1712
|
+
* depends on changed" claim is withheld, because it is not true.
|
|
1713
|
+
*/
|
|
1714
|
+
export function savePrivateIndex(libraryId, index, { bumpRevision = true } = {}) {
|
|
1715
|
+
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
1716
|
+
if (!validIndex(index)) throw new Error('invalid memory index shape')
|
|
1717
|
+
const file = path.join(indexDir(), `${libraryId}.json`)
|
|
1718
|
+
const saved = writeIndex(file, index)
|
|
1719
|
+
if (bumpRevision) bumpMemoryRevision()
|
|
1720
|
+
noteMemoryWrite('private', libraryId)
|
|
1721
|
+
for (const listener of indexWriteListeners) {
|
|
1722
|
+
try { listener(libraryId, saved) } catch (error) { warn(`memory sidecar update failed: ${error?.message || error}`) }
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
export function loadGlobalIndex() {
|
|
1727
|
+
return cachedIndex(GLOBAL_INDEX(), () => {
|
|
1728
|
+
let raw = readJson(GLOBAL_INDEX(), null)
|
|
1729
|
+
if (raw !== null) raw = assertJsonShape(GLOBAL_INDEX(), raw, validIndex)
|
|
1730
|
+
return raw && typeof raw === 'object' ? { version: 1, entries: raw.entries || {} } : { version: 1, entries: {} }
|
|
1731
|
+
})
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
function validIndex(value) {
|
|
1735
|
+
return value && typeof value === 'object' && !Array.isArray(value) && value.entries && typeof value.entries === 'object' && !Array.isArray(value.entries)
|
|
1736
|
+
&& Object.values(value.entries).every(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
export function saveGlobalIndex(index, { bumpRevision = true } = {}) {
|
|
1740
|
+
if (!validIndex(index)) throw new Error('invalid memory index shape')
|
|
1741
|
+
writeIndex(GLOBAL_INDEX(), index)
|
|
1742
|
+
if (bumpRevision) bumpMemoryRevision()
|
|
1743
|
+
noteMemoryWrite('global', null)
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
/** Counts only — no titles, no text. Cheap enough to call per folder. */
|
|
1747
|
+
export function summarizeIndex(index) {
|
|
1748
|
+
const entries = Object.values(index?.entries || {})
|
|
1749
|
+
const live = entries.filter((e) => e && !['archived', 'suppressed', 'expired', 'pending_review', 'superseded'].includes(e.status)
|
|
1750
|
+
&& (!e.expiresAt || Date.parse(e.expiresAt) > Date.now()))
|
|
1751
|
+
return {
|
|
1752
|
+
total: entries.length,
|
|
1753
|
+
active: live.length,
|
|
1754
|
+
pinned: live.filter((e) => e.layer === 'must_remember').length,
|
|
1755
|
+
marginalized: entries.filter((e) => e.marginalized === true).length,
|
|
1756
|
+
openLoop: live.filter((e) => e.openLoop === true).length,
|
|
1757
|
+
archived: entries.filter((e) => e.status === 'archived').length,
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
/**
|
|
1762
|
+
* Read-modify-write of one library index. The mutator is synchronous, so two
|
|
1763
|
+
* calls can never interleave. Callers that await a backend write (MemU commit,
|
|
1764
|
+
* a consolidation job) must reach for this *after* the await — reading before it
|
|
1765
|
+
* and saving afterward leaves a lost-update window this lock closes.
|
|
1766
|
+
*/
|
|
1767
|
+
export function updatePrivateIndex(libraryId, mutator) {
|
|
1768
|
+
if (!isSafeId(libraryId)) throw new Error('invalid library id')
|
|
1769
|
+
return withFileLock(path.join(indexDir(), `${libraryId}.json`), () => {
|
|
1770
|
+
indexCache.delete(path.join(indexDir(), `${libraryId}.json`))
|
|
1771
|
+
const index = loadPrivateIndex(libraryId)
|
|
1772
|
+
const next = mutator(index) || index
|
|
1773
|
+
if (next?.then) throw new Error('index mutators must be synchronous')
|
|
1774
|
+
savePrivateIndex(libraryId, next)
|
|
1775
|
+
return next
|
|
1776
|
+
})
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
export function updateGlobalIndex(mutator) {
|
|
1780
|
+
return withFileLock(GLOBAL_INDEX(), () => {
|
|
1781
|
+
indexCache.delete(GLOBAL_INDEX())
|
|
1782
|
+
const index = loadGlobalIndex()
|
|
1783
|
+
const next = mutator(index) || index
|
|
1784
|
+
if (next?.then) throw new Error('index mutators must be synchronous')
|
|
1785
|
+
saveGlobalIndex(next)
|
|
1786
|
+
return next
|
|
1787
|
+
})
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
export function newMemoryId(prefix = 'mem') {
|
|
1791
|
+
return `${prefix}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
/**
|
|
1795
|
+
* Creates a managed backup of the local memory stores (plugin state, indexes,
|
|
1796
|
+
* prompts, attachments, the vector journal and every MemU database), then keeps
|
|
1797
|
+
* the newest BACKUP_KEEP complete ones. Retention, staging, checksums, atomic
|
|
1798
|
+
* publish and the shared lock all live in lib/backup.js so there is exactly one
|
|
1799
|
+
* place that decides what a backup is and which backup may be deleted.
|
|
1800
|
+
*
|
|
1801
|
+
* Returns the published directory: callers (engine switch, library delete,
|
|
1802
|
+
* scripts) treat the return value as a path.
|
|
1803
|
+
*/
|
|
1804
|
+
export async function backupDatabases(options = {}) {
|
|
1805
|
+
// Pending bookkeeping changes live in memory for up to 50ms; a backup taken
|
|
1806
|
+
// before a flush would silently capture the previous state.
|
|
1807
|
+
let report
|
|
1808
|
+
try {
|
|
1809
|
+
report = await createBackup({ ...options, flushState })
|
|
1810
|
+
} catch (error) {
|
|
1811
|
+
// A refusal is the safety property working, not something to swallow: a
|
|
1812
|
+
// database the engine could not snapshot aborts the backup, and the reason
|
|
1813
|
+
// has to stay visible on the same channel the panel already reads.
|
|
1814
|
+
lastBackupReport = {
|
|
1815
|
+
at: stamp(),
|
|
1816
|
+
action: 'create',
|
|
1817
|
+
status: 'failed',
|
|
1818
|
+
code: error?.code || null,
|
|
1819
|
+
error: String(error?.message || error),
|
|
1820
|
+
name: null,
|
|
1821
|
+
dir: null,
|
|
1822
|
+
files: 0,
|
|
1823
|
+
bytes: 0,
|
|
1824
|
+
snapshots: [],
|
|
1825
|
+
pruned: [],
|
|
1826
|
+
pruneFailed: [],
|
|
1827
|
+
pendingCleanup: 0,
|
|
1828
|
+
notice: null,
|
|
1829
|
+
}
|
|
1830
|
+
throw error
|
|
1831
|
+
}
|
|
1832
|
+
lastBackupReport = { at: stamp(), action: 'create', ...report }
|
|
1833
|
+
return report.dir
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
/** What the last backup/restore/prune did, so the outcome stays observable. */
|
|
1837
|
+
export function lastBackupReportView() {
|
|
1838
|
+
return lastBackupReport ? { ...lastBackupReport } : null
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
/** Newest first, including entries that failed to complete (reported, never deleted). */
|
|
1842
|
+
export function listBackups() {
|
|
1843
|
+
return listBackupEntries()
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
/** Removes one backup directory. The name is validated, never used as a path. */
|
|
1847
|
+
export function deleteBackup(name) {
|
|
1848
|
+
const result = deleteBackupEntry(name)
|
|
1849
|
+
lastBackupReport = { at: stamp(), action: 'delete', ...result }
|
|
1850
|
+
return { deleted: result.deleted, status: result.status }
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
/**
|
|
1854
|
+
* Puts a backup back. The target is leased and its whole inventory is verified
|
|
1855
|
+
* before anything is written; the live root is saved as a safety backup next;
|
|
1856
|
+
* only then are files replaced. Failure leaves a recovery path: the safety
|
|
1857
|
+
* backup holds the state that was replaced and retention may not delete it.
|
|
1858
|
+
* A backup that predates the vector journal also retires the stale live
|
|
1859
|
+
* vector-active pointer, so recall falls back to text instead of querying
|
|
1860
|
+
* databases that no longer match the restored index.
|
|
1861
|
+
*/
|
|
1862
|
+
export async function restoreBackup(name, { beforeRestore = null, keep = undefined } = {}) {
|
|
1863
|
+
const result = await restoreFromBackup(name, { beforeRestore, flushState, clearCaches, keep })
|
|
1864
|
+
lastBackupReport = { at: stamp(), action: 'restore', ...result }
|
|
1865
|
+
return result
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
/** Drops the in-memory mirrors so the next read comes from disk. */
|
|
1869
|
+
export function clearCaches() {
|
|
1870
|
+
cache = null
|
|
1871
|
+
dirty = false
|
|
1872
|
+
if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
|
|
1873
|
+
indexCache.clear()
|
|
1874
|
+
// A restore or an external edit replaced the files under us; the sidebar must
|
|
1875
|
+
// not keep painting what it read before.
|
|
1876
|
+
bumpMemoryRevision()
|
|
1877
|
+
noteMemoryWrite('restore', null)
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
/**
|
|
1881
|
+
* Explicit session-binding cleanup. Idle time is not an automatic deletion trigger;
|
|
1882
|
+
* this is a dry-run-first maintenance call. A binding with no parseable lastTurnAt
|
|
1883
|
+
* is never a candidate.
|
|
1884
|
+
*/
|
|
1885
|
+
/**
|
|
1886
|
+
* Session-binding garbage collection.
|
|
1887
|
+
*
|
|
1888
|
+
* This deletes bindings, which is not recoverable. Three guards, because the old
|
|
1889
|
+
* version had none and a `--days 0` invocation wiped every binding in the store:
|
|
1890
|
+
*
|
|
1891
|
+
* · `olderThanDays` must be strictly positive. Zero/negative is a mistake, not a
|
|
1892
|
+
* "clean everything" request, so it throws instead of quietly becoming one.
|
|
1893
|
+
* · `isBusy(sessionId)` lets the caller veto a candidate: a session with a live
|
|
1894
|
+
* consolidation lease is in the middle of writing, and lastTurnAt is not the only
|
|
1895
|
+
* clock that matters.
|
|
1896
|
+
* · the apply pass re-reads each candidate inside `updateState`. A dry-run and an
|
|
1897
|
+
* apply are two separate loads, and a conversation that woke up in between must
|
|
1898
|
+
* not be deleted on the strength of the earlier snapshot.
|
|
1899
|
+
*/
|
|
1900
|
+
export function pruneSessionBindings({ olderThanDays = 30, dryRun = true, now = Date.now(), isBusy = null } = {}) {
|
|
1901
|
+
const days = Number(olderThanDays)
|
|
1902
|
+
if (!Number.isFinite(days) || days <= 0) throw new Error('olderThanDays must be a positive number of days')
|
|
1903
|
+
const cutoff = Number(now) - days * 86_400_000
|
|
1904
|
+
const state = loadState()
|
|
1905
|
+
const candidates = []
|
|
1906
|
+
const skipped = []
|
|
1907
|
+
for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
|
|
1908
|
+
const at = Date.parse(String(binding?.lastTurnAt || ''))
|
|
1909
|
+
if (!Number.isFinite(at) || at >= cutoff) continue
|
|
1910
|
+
if (typeof isBusy === 'function') {
|
|
1911
|
+
let busy = false
|
|
1912
|
+
try { busy = isBusy(sessionId) === true } catch (error) {
|
|
1913
|
+
// An unreadable lease file is not permission to delete: treat it as busy.
|
|
1914
|
+
busy = true
|
|
1915
|
+
warn(`prune-session-bindings: liveness check failed for ${sessionId} (${error?.message || error}); kept`)
|
|
1916
|
+
}
|
|
1917
|
+
if (busy) {
|
|
1918
|
+
skipped.push({ sessionId, reason: 'a consolidation lease is still live' })
|
|
1919
|
+
continue
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
candidates.push({ sessionId, lastTurnAt: binding.lastTurnAt, libraryId: binding.libraryId || null })
|
|
1923
|
+
}
|
|
1924
|
+
const base = {
|
|
1925
|
+
dryRun: dryRun !== false,
|
|
1926
|
+
olderThanDays: days,
|
|
1927
|
+
cutoff: new Date(cutoff).toISOString(),
|
|
1928
|
+
candidates,
|
|
1929
|
+
skipped,
|
|
1930
|
+
}
|
|
1931
|
+
if (dryRun !== false || candidates.length === 0) return { ...base, removed: [] }
|
|
1932
|
+
const removed = []
|
|
1933
|
+
const revalidated = []
|
|
1934
|
+
updateState((next) => {
|
|
1935
|
+
for (const item of candidates) {
|
|
1936
|
+
const current = next.sessions?.[item.sessionId]
|
|
1937
|
+
if (!current) continue
|
|
1938
|
+
const at = Date.parse(String(current.lastTurnAt || ''))
|
|
1939
|
+
// Same predicate as the candidate pass, on the fresh copy: `at < cutoff` alone
|
|
1940
|
+
// would still delete a binding that just came back with a stale lastTurnAt.
|
|
1941
|
+
if (!Number.isFinite(at) || at >= cutoff) { revalidated.push(item.sessionId); continue }
|
|
1942
|
+
delete next.sessions[item.sessionId]
|
|
1943
|
+
removed.push(item.sessionId)
|
|
1944
|
+
}
|
|
1945
|
+
return next
|
|
1946
|
+
})
|
|
1947
|
+
return { ...base, removed, revalidated }
|
|
1948
|
+
}
|