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/curator.js
CHANGED
|
@@ -1,1811 +1,1813 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto'
|
|
2
|
-
import {
|
|
3
|
-
globalDbPath, loadGlobalIndex, updateGlobalIndex, newMemoryId, getSettings, effectiveVectorRoute,
|
|
4
|
-
} from './state.js'
|
|
5
|
-
import { commit, forget } from './memu.js'
|
|
6
|
-
import { loadPrompt } from './prompts.js'
|
|
7
|
-
import { retryStoreWrite, redactSecrets, warn, isSafeId } from './paths.js'
|
|
8
|
-
import { record } from './activity-log.js'
|
|
9
|
-
import { activeEntryStamp, assertVectorWriteAllowed, hasActiveVectorGeneration, readVectorState, withVectorWrite } from './vector-profile.js'
|
|
10
|
-
import { upsertLexiconTerm } from './lexicon.js'
|
|
11
|
-
import { clean, bigrams, dice, similarTexts, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
|
|
12
|
-
import { estTokens } from './budget.js'
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
//
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return
|
|
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
|
-
export const
|
|
128
|
-
const
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
let
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
kept.
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
//
|
|
215
|
-
//
|
|
216
|
-
//
|
|
217
|
-
//
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
if (entry
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
const
|
|
254
|
-
const
|
|
255
|
-
const
|
|
256
|
-
take(
|
|
257
|
-
take(
|
|
258
|
-
take(byRecent.
|
|
259
|
-
take(
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
entries.
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
//
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
clusters.
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
//
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
const
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
return
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
//
|
|
410
|
-
//
|
|
411
|
-
//
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
const
|
|
415
|
-
const
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
//
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
if (memory
|
|
450
|
-
if (
|
|
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
|
-
const
|
|
476
|
-
const
|
|
477
|
-
const
|
|
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
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
*
|
|
550
|
-
*
|
|
551
|
-
*
|
|
552
|
-
*
|
|
553
|
-
*
|
|
554
|
-
*
|
|
555
|
-
*
|
|
556
|
-
*
|
|
557
|
-
*
|
|
558
|
-
*
|
|
559
|
-
*
|
|
560
|
-
*
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
if (
|
|
566
|
-
if (
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
if (
|
|
576
|
-
|
|
577
|
-
if (
|
|
578
|
-
if (op === '
|
|
579
|
-
if (m?.
|
|
580
|
-
if (
|
|
581
|
-
|
|
582
|
-
|
|
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
|
-
const
|
|
624
|
-
const
|
|
625
|
-
const
|
|
626
|
-
const
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
//
|
|
630
|
-
//
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
//
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
if (
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
//
|
|
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
|
-
const
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
const
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
const
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
//
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
const
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
// >
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
&& (best.entry?.
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
//
|
|
725
|
-
//
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
tags.
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
const
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
//
|
|
754
|
-
//
|
|
755
|
-
//
|
|
756
|
-
|
|
757
|
-
const
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
//
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
if (tags.
|
|
781
|
-
if (
|
|
782
|
-
|
|
783
|
-
//
|
|
784
|
-
|
|
785
|
-
entry.
|
|
786
|
-
entry.
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
}
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
//
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
//
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
const
|
|
820
|
-
const
|
|
821
|
-
const
|
|
822
|
-
|
|
823
|
-
//
|
|
824
|
-
//
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
*
|
|
839
|
-
*
|
|
840
|
-
*
|
|
841
|
-
* link
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
const
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
//
|
|
849
|
-
|
|
850
|
-
const
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
//
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
for (const { id, entry
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
//
|
|
869
|
-
//
|
|
870
|
-
//
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
entry.
|
|
879
|
-
entry.
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
fresh.entries[targetId].
|
|
885
|
-
fresh.entries[targetId].
|
|
886
|
-
fresh.entries[targetId].
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
//
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
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
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
+ (summary.
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
//
|
|
968
|
-
//
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
//
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
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
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
*
|
|
1040
|
-
*
|
|
1041
|
-
* ≥0.
|
|
1042
|
-
*
|
|
1043
|
-
*
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
const
|
|
1051
|
-
const
|
|
1052
|
-
const
|
|
1053
|
-
|
|
1054
|
-
const
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
const
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
result.
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
const
|
|
1085
|
-
const
|
|
1086
|
-
const
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
let
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
const
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
byOrigin.
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
result.
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
// source
|
|
1126
|
-
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
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
|
-
*
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
const
|
|
1164
|
-
const
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
const
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
const
|
|
1176
|
-
const
|
|
1177
|
-
const
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
if (
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
//
|
|
1189
|
-
|
|
1190
|
-
const
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
seenPairs.
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
.
|
|
1203
|
-
.
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
target.
|
|
1221
|
-
target.
|
|
1222
|
-
target.
|
|
1223
|
-
target.
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
appendAudit(
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
entry.
|
|
1230
|
-
entry.
|
|
1231
|
-
entry.
|
|
1232
|
-
entry.
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
}
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
*
|
|
1244
|
-
*
|
|
1245
|
-
* §
|
|
1246
|
-
*
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
const
|
|
1251
|
-
const
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
const
|
|
1257
|
-
const
|
|
1258
|
-
const
|
|
1259
|
-
const
|
|
1260
|
-
const
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
const
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
//
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
// medoid
|
|
1312
|
-
|
|
1313
|
-
const
|
|
1314
|
-
|
|
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
|
-
const
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
const
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
seenEvidence.
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
const
|
|
1358
|
-
const
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
const
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
const
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
//
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|| String(
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
if (
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
const
|
|
1409
|
-
const
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
const
|
|
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
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
const
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
const
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
//
|
|
1502
|
-
|
|
1503
|
-
const
|
|
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
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
+ (result.
|
|
1557
|
-
+ (result.
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
*
|
|
1568
|
-
*
|
|
1569
|
-
*
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
const
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
const
|
|
1581
|
-
const
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
const
|
|
1595
|
-
const
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
delete currentTarget.
|
|
1601
|
-
delete currentTarget.
|
|
1602
|
-
currentTarget.
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
current
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
delete current.
|
|
1611
|
-
delete current.
|
|
1612
|
-
current.
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
stored
|
|
1620
|
-
stored.
|
|
1621
|
-
stored.
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
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
|
-
const
|
|
1653
|
-
const
|
|
1654
|
-
const
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
if (ids.length
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
const
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
const
|
|
1687
|
-
|
|
1688
|
-
let
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
const
|
|
1693
|
-
const
|
|
1694
|
-
const
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
const
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
//
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
const
|
|
1718
|
-
const
|
|
1719
|
-
const
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
const
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
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
|
-
job.
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
job.
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
globalDbPath, loadGlobalIndex, updateGlobalIndex, newMemoryId, getSettings, effectiveVectorRoute,
|
|
4
|
+
} from './state.js'
|
|
5
|
+
import { commit, forget } from './memu.js'
|
|
6
|
+
import { loadPrompt } from './prompts.js'
|
|
7
|
+
import { retryStoreWrite, redactSecrets, warn, isSafeId } from './paths.js'
|
|
8
|
+
import { record } from './activity-log.js'
|
|
9
|
+
import { activeEntryStamp, assertVectorWriteAllowed, hasActiveVectorGeneration, readVectorState, withVectorWrite } from './vector-profile.js'
|
|
10
|
+
import { upsertLexiconTerm } from './lexicon.js'
|
|
11
|
+
import { clean, bigrams, dice, similarTexts, DUP_REJECT_DICE, TOPIC_DICE } from './text-similarity.js'
|
|
12
|
+
import { estTokens } from './budget.js'
|
|
13
|
+
import { effectiveAgentPreset } from './consolidation-snapshot.js'
|
|
14
|
+
// —— 候选检索、证据落地与全局关联 ——
|
|
15
|
+
import {
|
|
16
|
+
buildCandidateClusters,
|
|
17
|
+
buildCorpus,
|
|
18
|
+
bm25,
|
|
19
|
+
globalConflictCheck,
|
|
20
|
+
pairFeatures,
|
|
21
|
+
pairScore,
|
|
22
|
+
rankPairCandidates,
|
|
23
|
+
tokenize,
|
|
24
|
+
} from './text-retrieval.js'
|
|
25
|
+
import { buildEvidenceCorpus, groundEvidence } from './curator-evidence.js'
|
|
26
|
+
import { applyGlobalLinks, validateGlobalLink, appendAudit } from './global-graph.js'
|
|
27
|
+
import {
|
|
28
|
+
ABSORB_ABSTRACTIVE_COVERAGE,
|
|
29
|
+
ABSORB_AUTO_SOURCE_COVERAGE,
|
|
30
|
+
ABSORB_AUTO_UNION_COVERAGE,
|
|
31
|
+
ABSORB_MAX_CHARS,
|
|
32
|
+
ABSORB_MAX_SOURCES,
|
|
33
|
+
ABSORB_MIN_LENGTH_RATIO,
|
|
34
|
+
ABSORB_REVIEW_SOURCE_COVERAGE,
|
|
35
|
+
ABSORB_REVIEW_UNION_COVERAGE,
|
|
36
|
+
CLUSTER_MIN_PAIR,
|
|
37
|
+
CURATOR_CLUSTER_TOKENS,
|
|
38
|
+
CURATOR_INDEX_MAX_ENTRIES,
|
|
39
|
+
CURATOR_INDEX_TOKENS,
|
|
40
|
+
CURATOR_MAX_LINK_ABSORB,
|
|
41
|
+
EVIDENCE_MAX,
|
|
42
|
+
PAIR_ABSORB_MIN,
|
|
43
|
+
PAIR_DUPLICATE_MIN,
|
|
44
|
+
PAIR_LINK_MIN,
|
|
45
|
+
PAIR_SCAN_LIMIT,
|
|
46
|
+
} from './curator-policy.js'
|
|
47
|
+
|
|
48
|
+
const MAX_SESSIONS = 10
|
|
49
|
+
const MAX_TOTAL_CHARS = 90_000
|
|
50
|
+
const MAX_SESSION_CHARS = 14_000
|
|
51
|
+
// 转录同时受字符预算与 token 预算约束。字符预算保留原有行为;token 预算
|
|
52
|
+
// 按 estTokens 累计,超过 30k 就停——中文转录的字符数≈token 数,只靠 90k 字符
|
|
53
|
+
// 在上限时仍会送出约 90k token。
|
|
54
|
+
const MAX_TRANSCRIPT_TOKENS = 30_000
|
|
55
|
+
// curator 输出上限为 24 条,与提示词一致;超出的条目在提交前丢弃并记日志。
|
|
56
|
+
const MAX_CURATOR_MEMORIES = 24
|
|
57
|
+
const jobs = new Map()
|
|
58
|
+
|
|
59
|
+
function managedVectorIntent() {
|
|
60
|
+
if (effectiveVectorRoute() !== 'managed-local') return false
|
|
61
|
+
try {
|
|
62
|
+
const state = readVectorState({ tolerateMissing: true }).state
|
|
63
|
+
return Boolean(state && (state.active || state.requested || state.pending))
|
|
64
|
+
} catch {
|
|
65
|
+
return true
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 与 memory.js 同一条口径:受管路由还没有代际时,引擎这一步按词法处理(索引照写),
|
|
70
|
+
// 否则 MemU 会以 "managed local vector profile is not active" 拒绝整次提炼。
|
|
71
|
+
function engineRoute() {
|
|
72
|
+
const route = effectiveVectorRoute()
|
|
73
|
+
return route === 'managed-local' && !hasActiveVectorGeneration() ? 'lexical' : route
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function withManagedCuratorWrite(action) {
|
|
77
|
+
if (!managedVectorIntent()) return action()
|
|
78
|
+
// Same rule as the private write path: requested-but-never-migrated has no
|
|
79
|
+
// generation to stay consistent with, so the global index + engine still get
|
|
80
|
+
// the memories. Failing here would throw away a whole curation run.
|
|
81
|
+
if (!hasActiveVectorGeneration()) {
|
|
82
|
+
warn('managed vector write degraded to index+engine: no active vector generation; run the profile switch to enable vectors')
|
|
83
|
+
record({ kind: 'vector', level: 'warn', scope: 'global', message: '向量未激活,全局提炼已降级为索引+引擎', detail: { reason: 'no active vector generation' } })
|
|
84
|
+
return action()
|
|
85
|
+
}
|
|
86
|
+
return withVectorWrite(async () => { assertVectorWriteAllowed(); return action() })
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function textOf(blocks) {
|
|
90
|
+
if (!Array.isArray(blocks)) return ''
|
|
91
|
+
return blocks
|
|
92
|
+
.filter((b) => b?.type === 'text' && typeof b.text === 'string')
|
|
93
|
+
.map((b) => b.text)
|
|
94
|
+
.join('')
|
|
95
|
+
.trim()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function truncate(text, max) {
|
|
99
|
+
const s = String(text || '')
|
|
100
|
+
return s.length > max ? `${s.slice(0, max)}…` : s
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function argsText(value) {
|
|
104
|
+
if (value == null) return ''
|
|
105
|
+
return typeof value === 'string' ? value : JSON.stringify(value)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function toolCallKey(name, args) {
|
|
109
|
+
return `${name || '?'}\u0000${argsText(args)}`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function blockCallId(block) {
|
|
113
|
+
return typeof block?.id === 'string' && block.id ? block.id : null
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function eventCallId(event) {
|
|
117
|
+
return typeof event?.data?.callId === 'string' && event.data.callId ? event.data.callId : null
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 转录压缩:assistant/message 的 tool-call 块与独立 tool/call 事件是同一
|
|
122
|
+
* 次调用的双写,以 tool/call 事件为准——块只在没有对应事件时保留(先按 callId
|
|
123
|
+
* 配对;两侧都没有 id 时按 name+arguments 计数配对,支持重复调用)。字符预算
|
|
124
|
+
* 保留原行为,另加可选 token 预算(累计 estTokens 超预算即停)。
|
|
125
|
+
* 工具行额度可按域覆盖:编码域的修改重点在命令/错误签名/参数里,300/400 只够开头。
|
|
126
|
+
*/
|
|
127
|
+
export const CONDENSE_TOOL_RESULT_CHARS = 400
|
|
128
|
+
export const CONDENSE_TOOL_CALL_CHARS = 300
|
|
129
|
+
const CONDENSE_TOOL_RESULT_CHARS_CODING = 1_400
|
|
130
|
+
const CONDENSE_TOOL_CALL_CHARS_CODING = 700
|
|
131
|
+
|
|
132
|
+
export function condenseLimitsFor(domain) {
|
|
133
|
+
return String(domain) === 'coding'
|
|
134
|
+
? { toolResultChars: CONDENSE_TOOL_RESULT_CHARS_CODING, toolCallChars: CONDENSE_TOOL_CALL_CHARS_CODING }
|
|
135
|
+
: { toolResultChars: CONDENSE_TOOL_RESULT_CHARS, toolCallChars: CONDENSE_TOOL_CALL_CHARS }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function condenseEvents(events, maxChars = MAX_SESSION_CHARS, { maxTokens = Infinity, toolResultChars = CONDENSE_TOOL_RESULT_CHARS, toolCallChars = CONDENSE_TOOL_CALL_CHARS } = {}) {
|
|
139
|
+
// 事件侧先收一遍:callId 集合 + (name, arguments) 计数,供块侧配对。
|
|
140
|
+
const eventCallIds = new Set()
|
|
141
|
+
const eventSignatures = new Map()
|
|
142
|
+
for (const event of events || []) {
|
|
143
|
+
if (event?.type !== 'tool/call') continue
|
|
144
|
+
const id = eventCallId(event)
|
|
145
|
+
if (id) eventCallIds.add(id)
|
|
146
|
+
const key = toolCallKey(event.data?.name, event.data?.arguments)
|
|
147
|
+
eventSignatures.set(key, (eventSignatures.get(key) || 0) + 1)
|
|
148
|
+
}
|
|
149
|
+
const claimedSignatures = new Map()
|
|
150
|
+
const lines = []
|
|
151
|
+
for (const event of events || []) {
|
|
152
|
+
try {
|
|
153
|
+
const type = event?.type
|
|
154
|
+
if (type === 'user/message') {
|
|
155
|
+
if (event.data?.source?.kind !== 'user') continue
|
|
156
|
+
const text = textOf(event.data?.content)
|
|
157
|
+
if (text) lines.push(`User: ${text}`)
|
|
158
|
+
continue
|
|
159
|
+
}
|
|
160
|
+
if (type === 'assistant/message') {
|
|
161
|
+
const blocks = event.data?.message?.content || []
|
|
162
|
+
const texts = textOf(blocks)
|
|
163
|
+
if (texts) lines.push(`Assistant: ${texts}`)
|
|
164
|
+
for (const b of blocks) {
|
|
165
|
+
if (b?.type !== 'tool-call') continue
|
|
166
|
+
const id = blockCallId(b)
|
|
167
|
+
if (id && eventCallIds.has(id)) continue
|
|
168
|
+
// 无 id 或 id 未配对:用 name+arguments 计数配对,事件侧有几个就吸收几个块。
|
|
169
|
+
const key = toolCallKey(b.name, b.arguments)
|
|
170
|
+
const available = (eventSignatures.get(key) || 0) - (claimedSignatures.get(key) || 0)
|
|
171
|
+
if (available > 0) {
|
|
172
|
+
claimedSignatures.set(key, (claimedSignatures.get(key) || 0) + 1)
|
|
173
|
+
continue
|
|
174
|
+
}
|
|
175
|
+
lines.push(`Tool call: ${b.name}${b.arguments ? ` ${truncate(argsText(b.arguments), toolCallChars)}` : ''}`)
|
|
176
|
+
}
|
|
177
|
+
continue
|
|
178
|
+
}
|
|
179
|
+
if (type === 'tool/result') {
|
|
180
|
+
const text = textOf(event.data?.message?.content)
|
|
181
|
+
if (text) lines.push(`Tool result${event.data?.message?.isError ? ' (error)' : ''}: ${truncate(text, toolResultChars)}`)
|
|
182
|
+
continue
|
|
183
|
+
}
|
|
184
|
+
if (type === 'tool/call') {
|
|
185
|
+
lines.push(`Tool call: ${event.data?.name || '?'} ${truncate(argsText(event.data?.arguments), toolCallChars)}`)
|
|
186
|
+
}
|
|
187
|
+
} catch {}
|
|
188
|
+
}
|
|
189
|
+
let kept = lines
|
|
190
|
+
let tokenTruncated = false
|
|
191
|
+
if (Number.isFinite(maxTokens) && maxTokens > 0) {
|
|
192
|
+
kept = []
|
|
193
|
+
let used = 0
|
|
194
|
+
for (const line of lines) {
|
|
195
|
+
const cost = estTokens(line) + (kept.length > 0 ? 1 : 0)
|
|
196
|
+
// 永远保留第一行(与 budget.packToBudget 同口径),之后累计超预算即停。
|
|
197
|
+
if (kept.length > 0 && used + cost > maxTokens) { tokenTruncated = true; break }
|
|
198
|
+
kept.push(line)
|
|
199
|
+
used += cost
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
let joined = redactSecrets(kept.join('\n'))
|
|
203
|
+
if (tokenTruncated) {
|
|
204
|
+
joined += `\n...[truncated ${lines.length - kept.length} lines over token budget ${maxTokens}]...`
|
|
205
|
+
}
|
|
206
|
+
if (joined.length > maxChars) {
|
|
207
|
+
const head = joined.slice(0, Math.floor(maxChars * 0.6))
|
|
208
|
+
const tail = joined.slice(-Math.floor(maxChars * 0.35))
|
|
209
|
+
joined = `${head}\n...[truncated ${joined.length - maxChars} chars]...\n${tail}`
|
|
210
|
+
}
|
|
211
|
+
return joined
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// —— curator 上下文打包 ——
|
|
215
|
+
// 旧 compactGlobalIndex 是"插入顺序前 200 条 ×600 字"的平铺,第 201 条后永远不可见、
|
|
216
|
+
// 无预算。这里改为:BM25(会话文本) top80 → 追加最近 30 / universal 10 / pending 10,
|
|
217
|
+
// 去重后按 BM25 desc → updatedAt desc → id 排序,estTokens 累计超预算即停(丢低分,
|
|
218
|
+
// 不截断 JSON)。同输入同输出,不依赖对象插入顺序。
|
|
219
|
+
function renderIndexEntry(id, entry, contentCap) {
|
|
220
|
+
const links = Array.isArray(entry?.links) ? entry.links : []
|
|
221
|
+
const item = {
|
|
222
|
+
id,
|
|
223
|
+
track: entry?.track || 'memory',
|
|
224
|
+
domain: entry?.domain || 'unknown',
|
|
225
|
+
applies_to: Array.isArray(entry?.appliesTo) ? entry.appliesTo.slice(0, 20) : [],
|
|
226
|
+
title: entry?.title || '',
|
|
227
|
+
content: truncate(entry?.content || '', contentCap),
|
|
228
|
+
confidence: entry?.confidence ?? null,
|
|
229
|
+
status: entry?.status || 'active',
|
|
230
|
+
updatedAt: entry?.updatedAt || null,
|
|
231
|
+
linkCount: links.length,
|
|
232
|
+
linkedTo: links.slice(0, 5).map((l) => ({ to: l?.to || null, kind: l?.kind || null })),
|
|
233
|
+
}
|
|
234
|
+
if (Array.isArray(entry?.absorbedFrom) && entry.absorbedFrom.length) item.absorbedFrom = entry.absorbedFrom
|
|
235
|
+
return item
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function packCuratorIndexContext({ index, sessionText, tokenBudget = CURATOR_INDEX_TOKENS, maxEntries = CURATOR_INDEX_MAX_ENTRIES } = {}) {
|
|
239
|
+
const pool = []
|
|
240
|
+
for (const [id, entry] of Object.entries(index?.entries || {})) {
|
|
241
|
+
if (!entry || entry.status === 'archived') continue
|
|
242
|
+
if (entry.reviewKind) continue // 本版没有 link 伪条目;防御性过滤
|
|
243
|
+
pool.push({ id, entry, updatedAt: String(entry.updatedAt || ''), score: 0 })
|
|
244
|
+
}
|
|
245
|
+
if (pool.length) {
|
|
246
|
+
const corpus = buildCorpus(pool.map((p) => ({ ...p.entry, id: p.id })))
|
|
247
|
+
const query = tokenize(sessionText || '')
|
|
248
|
+
for (const p of pool) {
|
|
249
|
+
const doc = corpus.docs.get(p.id)
|
|
250
|
+
p.score = doc ? bm25(query, doc, corpus) : 0
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const byScore = [...pool].sort((a, b) => b.score - a.score || b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
|
|
254
|
+
const byRecent = [...pool].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
|
|
255
|
+
const selected = new Map()
|
|
256
|
+
const take = (list) => { for (const p of list) if (!selected.has(p.id)) selected.set(p.id, p) }
|
|
257
|
+
take(byScore.slice(0, 80)) // BM25 top 80
|
|
258
|
+
take(byRecent.slice(0, 30)) // 最近 30
|
|
259
|
+
take(byRecent.filter((p) => (p.entry?.domain || '') === 'universal').slice(0, 10)) // universal 10
|
|
260
|
+
take(pool.filter((p) => (p.entry?.status || '') === 'pending_review' && (p.entry?.track || 'memory') === 'memory')
|
|
261
|
+
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1)).slice(0, 10)) // pending_review 记忆 10
|
|
262
|
+
|
|
263
|
+
const ordered = [...selected.values()].sort((a, b) => b.score - a.score || b.updatedAt.localeCompare(a.updatedAt) || (a.id < b.id ? -1 : 1))
|
|
264
|
+
const entries = []
|
|
265
|
+
let tokens = 0
|
|
266
|
+
for (let i = 0; i < ordered.length && entries.length < maxEntries; i++) {
|
|
267
|
+
const item = renderIndexEntry(ordered[i].id, ordered[i].entry, i < 20 ? 900 : 600)
|
|
268
|
+
const cost = estTokens(JSON.stringify(item))
|
|
269
|
+
if (entries.length > 0 && tokens + cost > tokenBudget) break
|
|
270
|
+
entries.push(item)
|
|
271
|
+
tokens += cost
|
|
272
|
+
}
|
|
273
|
+
return { entries, tokens, omitted: Math.max(0, ordered.length - entries.length), includedIds: entries.map((e) => e.id) }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// candidate_clusters 的 prompt 打包(§4.5):预算 2000 tokens,簇内正文截 300 字,
|
|
277
|
+
// pair_scores 保留 2 位;簇已按 avg_score 降序,超预算丢低分簇。
|
|
278
|
+
export function packCuratorClusterContext(clusterResult, { tokenBudget = CURATOR_CLUSTER_TOKENS } = {}) {
|
|
279
|
+
const clusters = []
|
|
280
|
+
let tokens = 0
|
|
281
|
+
for (const cluster of clusterResult?.clusters || []) {
|
|
282
|
+
const rendered = {
|
|
283
|
+
cluster_id: cluster.cluster_id,
|
|
284
|
+
suggested_op: cluster.suggested_op,
|
|
285
|
+
medoid_id: cluster.medoid_id,
|
|
286
|
+
avg_score: cluster.avg_score,
|
|
287
|
+
pair_scores: cluster.pair_scores,
|
|
288
|
+
members: (cluster.members || []).map((m) => ({
|
|
289
|
+
id: m.id, title: m.title || '', track: m.track || 'memory',
|
|
290
|
+
domain: m.domain || 'unknown', updatedAt: m.updatedAt || null,
|
|
291
|
+
content: truncate(m.content || '', 300),
|
|
292
|
+
})),
|
|
293
|
+
}
|
|
294
|
+
const cost = estTokens(JSON.stringify(rendered))
|
|
295
|
+
if (clusters.length > 0 && tokens + cost > tokenBudget) break
|
|
296
|
+
clusters.push(rendered)
|
|
297
|
+
tokens += cost
|
|
298
|
+
}
|
|
299
|
+
const total = clusterResult?.clusters?.length || 0
|
|
300
|
+
return {
|
|
301
|
+
clusters,
|
|
302
|
+
tokens,
|
|
303
|
+
omitted: Math.max(0, total - clusters.length),
|
|
304
|
+
truncated: (clusterResult?.truncated === true) || (total - clusters.length) > 0,
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function readSession(sessionQuery, id) {
|
|
309
|
+
if (typeof sessionQuery.readSession === 'function') {
|
|
310
|
+
const snapshot = await sessionQuery.readSession(id)
|
|
311
|
+
return {
|
|
312
|
+
events: snapshot?.events || [],
|
|
313
|
+
header: snapshot?.session || null,
|
|
314
|
+
inheritedEventCount: snapshot?.inheritedEventCount ?? null,
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (typeof sessionQuery.observeSession === 'function') {
|
|
318
|
+
const observation = await sessionQuery.observeSession(id, { projectionMode: 'none' })
|
|
319
|
+
try {
|
|
320
|
+
return {
|
|
321
|
+
events: observation?.events || [],
|
|
322
|
+
header: observation?.header || null,
|
|
323
|
+
inheritedEventCount: observation?.inheritedEventCount ?? null,
|
|
324
|
+
}
|
|
325
|
+
} finally {
|
|
326
|
+
try { observation?.[Symbol.dispose]?.() } catch {}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
throw new Error('sessionQuery has neither readSession nor observeSession')
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function readSessionMeta(sessionQuery, ids) {
|
|
333
|
+
const out = new Map()
|
|
334
|
+
try {
|
|
335
|
+
const records = await sessionQuery.listSessions()
|
|
336
|
+
for (const record of records || []) {
|
|
337
|
+
// `SessionRecord` carries only header + liveness; the title arrives from
|
|
338
|
+
// readTitleSnapshots below, so keep the record and a mutable title slot.
|
|
339
|
+
out.set(record.header?.id, { ...record, title: record.header?.title || '' })
|
|
340
|
+
}
|
|
341
|
+
} catch {}
|
|
342
|
+
try {
|
|
343
|
+
if (typeof sessionQuery.readTitleSnapshots === 'function') {
|
|
344
|
+
// One result per requested id: `{ sessionId, status, value: { session, title? } }`.
|
|
345
|
+
const titles = await sessionQuery.readTitleSnapshots(ids)
|
|
346
|
+
for (const r of titles || []) {
|
|
347
|
+
if (r?.status !== 'fulfilled' || !r.sessionId || !out.has(r.sessionId)) continue
|
|
348
|
+
const title = r.value?.title?.title || r.value?.session?.title
|
|
349
|
+
if (title) out.get(r.sessionId).title = title
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
} catch {}
|
|
353
|
+
return out
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function parseJsonObject(text) {
|
|
357
|
+
const raw = String(text || '').trim()
|
|
358
|
+
try { return JSON.parse(raw) } catch {}
|
|
359
|
+
const start = raw.indexOf('{')
|
|
360
|
+
const end = raw.lastIndexOf('}')
|
|
361
|
+
if (start >= 0 && end > start) {
|
|
362
|
+
try { return JSON.parse(raw.slice(start, end + 1)) } catch {}
|
|
363
|
+
}
|
|
364
|
+
return null
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function validDomain(domain) {
|
|
368
|
+
const d = String(domain || '').trim()
|
|
369
|
+
return d === 'universal' || d === 'coding' || d === 'rp' || d === 'tooling' || d === 'personal' || d === 'general' || d.startsWith('project:')
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function agentOptionsFor(model) {
|
|
373
|
+
const value = String(model || '').trim()
|
|
374
|
+
if (!value) return undefined
|
|
375
|
+
const slash = value.indexOf('/')
|
|
376
|
+
if (slash <= 0 || slash === value.length - 1) return undefined
|
|
377
|
+
return { provider: value.slice(0, slash), model: value.slice(slash + 1) }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export function listCurationJobs() {
|
|
381
|
+
return [...jobs.values()].map((j) => ({
|
|
382
|
+
id: j.id, status: j.status, step: j.step, createdAt: j.createdAt, endedAt: j.endedAt,
|
|
383
|
+
error: j.error || null, result: j.result || null,
|
|
384
|
+
}))
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export function getCurationJob(id) {
|
|
388
|
+
const job = jobs.get(id)
|
|
389
|
+
if (!job) return null
|
|
390
|
+
return {
|
|
391
|
+
id: job.id,
|
|
392
|
+
status: job.status,
|
|
393
|
+
step: job.step,
|
|
394
|
+
logs: job.logs.slice(-80),
|
|
395
|
+
createdAt: job.createdAt,
|
|
396
|
+
endedAt: job.endedAt || null,
|
|
397
|
+
error: job.error || null,
|
|
398
|
+
result: job.result || null,
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export function cancelCurationJob(id) {
|
|
403
|
+
const job = jobs.get(id)
|
|
404
|
+
if (!job) return false
|
|
405
|
+
try { job.abort.abort(new Error('cancelled by user')) } catch {}
|
|
406
|
+
return true
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// 孤儿窗口补偿(这是补偿设计,不是事务):curator 是 commit-before-index —— 批量提交
|
|
410
|
+
// 成功而全局索引写失败时,引擎库里会留下索引不认识的孤儿行。这里对刚提交的每个 name
|
|
411
|
+
// 逐个 forget,尽力撤销;这是尽力而为,不是回滚保证:删不掉的必须可见。补偿结果(包括
|
|
412
|
+
// 哪些补上了、哪些没补上)逐条记录进活动日志 kind:'curate',绝不吞掉。
|
|
413
|
+
async function compensateCuratorCommit(originalError, { files, route }) {
|
|
414
|
+
const db = globalDbPath()
|
|
415
|
+
const compensated = []
|
|
416
|
+
const failed = []
|
|
417
|
+
for (const file of files) {
|
|
418
|
+
try {
|
|
419
|
+
const result = await forget({ db, name: file.name })
|
|
420
|
+
if (!result || typeof result !== 'object' || result.ok === false || result.error || result.parseWarning
|
|
421
|
+
|| !Number.isSafeInteger(result.deleted) || result.deleted < 0) {
|
|
422
|
+
throw new Error('backend compensation delete was not acknowledged')
|
|
423
|
+
}
|
|
424
|
+
compensated.push(file.name)
|
|
425
|
+
} catch (compensationError) {
|
|
426
|
+
failed.push({ name: file.name, error: String(compensationError?.message || compensationError) })
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (failed.length) {
|
|
430
|
+
record({
|
|
431
|
+
kind: 'curate', scope: 'global', ok: false, level: 'error',
|
|
432
|
+
message: `全局提炼索引写失败后的补偿不完整:${compensated.length}/${files.length} 条已从向量库撤销,${failed.length} 条撤销失败(引擎库残留孤儿行,需手动清理)`,
|
|
433
|
+
detail: { route, compensated, failed: failed.slice(0, 20), originalError: String(originalError?.message || originalError) },
|
|
434
|
+
refs: files.map((file) => file.name).slice(0, 20),
|
|
435
|
+
})
|
|
436
|
+
} else {
|
|
437
|
+
record({
|
|
438
|
+
kind: 'curate', scope: 'global', ok: true, level: 'warn',
|
|
439
|
+
message: `全局提炼索引写失败,已从向量库回滚刚提交的 ${compensated.length} 条记忆(补偿成功;索引未变,重跑提炼即可)`,
|
|
440
|
+
detail: { route, compensated, failed: [], originalError: String(originalError?.message || originalError) },
|
|
441
|
+
refs: files.map((file) => file.name).slice(0, 20),
|
|
442
|
+
})
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// 词典 op 识别(§2.1):op 显式标 'lexicon',或任何带 libraryId / term+kind 的提案。
|
|
447
|
+
// 全局 curator 的输出里出现这些字段只能说明模型越权,拒绝而不是猜它的意图。
|
|
448
|
+
function isLexiconOp(memory) {
|
|
449
|
+
if (!memory || typeof memory !== 'object') return false
|
|
450
|
+
if (memory.op === 'lexicon') return true
|
|
451
|
+
if (typeof memory.libraryId === 'string' && memory.libraryId.trim()) return true
|
|
452
|
+
return typeof memory.term === 'string' && memory.term.trim() && ['slang', 'meme', 'trigger', 'term'].includes(memory.kind)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* 私有整理链路的词典写入(§2.1-§2.2):validated ops 白名单校验 + 落库。
|
|
457
|
+
*
|
|
458
|
+
* 锁顺序(刻意注释,谁改谁读):本函数先拿 curator 侧的 managed 写闸
|
|
459
|
+
* (withManagedCuratorWrite —— 受管向量代际一致性),**在其内部**再让
|
|
460
|
+
* upsertLexiconTerm 拿词典自己的 withFileLock。两把锁的嵌套只有一个方向:
|
|
461
|
+
* curator(vector) → lexicon(file);lexicon.js 从不回头拿向量锁,所以无死锁环。
|
|
462
|
+
* 词典写从不跨 await 持锁——withFileLock 的 action 是同步的。
|
|
463
|
+
*
|
|
464
|
+
* 校验规则(§2.1 curator 行 + 契约):
|
|
465
|
+
* * 只接受 { op:'lexicon', action:'upsert', ... };action 其它值(尤其 delete)
|
|
466
|
+
* 一律拒绝——删除是用户/管理操作,模型没有删除路径。
|
|
467
|
+
* * 必须 evidence(quote 或 id 至少其一非空),无证据直接拒绝;
|
|
468
|
+
* "同一转录同词 ≥2 次才建议"是提示词层的事,代码层只验证据存在。
|
|
469
|
+
* * libraryId 必须显式给出且过 isSafeId;op 里带了别的 libraryId 视为越权拒绝。
|
|
470
|
+
* * needs_review === true → status:'pending',否则 'active'。
|
|
471
|
+
* * sensitive trigger 由 lexicon.js 的 LEXICON_SENSITIVE_FORBIDDEN 兜底(curator
|
|
472
|
+
* 来源理论上不该提,但来源字段在模型手里,存储层必须自己设防)。
|
|
473
|
+
*/
|
|
474
|
+
export async function commitPrivateLexiconOps(ops, { libraryId, job } = {}) {
|
|
475
|
+
const list = Array.isArray(ops) ? ops : [ops]
|
|
476
|
+
const committed = []
|
|
477
|
+
const rejected = []
|
|
478
|
+
const skipped = []
|
|
479
|
+
if (!isSafeId(libraryId)) {
|
|
480
|
+
for (const raw of list) rejected.push({ term: raw?.term || null, code: 'LEXICON_INVALID_LIBRARY_ID', reason: 'lexicon ops need a valid private library id' })
|
|
481
|
+
return { committed, rejected, skipped }
|
|
482
|
+
}
|
|
483
|
+
const run = async () => {
|
|
484
|
+
for (const raw of list) {
|
|
485
|
+
const op = raw && typeof raw === 'object' ? raw : null
|
|
486
|
+
if (!op || op.op !== 'lexicon') {
|
|
487
|
+
skipped.push({ term: op?.term || null, reason: 'not a lexicon op (op must be "lexicon")' })
|
|
488
|
+
continue
|
|
489
|
+
}
|
|
490
|
+
if (op.action !== 'upsert') {
|
|
491
|
+
rejected.push({ term: op.term || null, code: 'LEXICON_ACTION_FORBIDDEN', reason: `lexicon action "${op.action}" is not allowed for consolidation; only upsert, never delete` })
|
|
492
|
+
continue
|
|
493
|
+
}
|
|
494
|
+
const evidence = Array.isArray(op.evidence)
|
|
495
|
+
? op.evidence.filter(item => item && typeof item === 'object' && ((typeof item.quote === 'string' && item.quote.trim()) || (typeof item.id === 'string' && item.id.trim())))
|
|
496
|
+
: []
|
|
497
|
+
if (!evidence.length) {
|
|
498
|
+
rejected.push({ term: op.term || null, code: 'LEXICON_EVIDENCE_REQUIRED', reason: 'lexicon upserts need evidence from the transcript' })
|
|
499
|
+
continue
|
|
500
|
+
}
|
|
501
|
+
if (typeof op.libraryId === 'string' && op.libraryId && op.libraryId !== libraryId) {
|
|
502
|
+
rejected.push({ term: op.term || null, code: 'LEXICON_LIBRARY_MISMATCH', reason: `lexicon op targets library ${op.libraryId}, but this consolidation is bound to ${libraryId}` })
|
|
503
|
+
continue
|
|
504
|
+
}
|
|
505
|
+
// 敏感触发词不允许模型猜(§0.2/§2.1):curator 也是模型,整理链路一律不给
|
|
506
|
+
// sensitive trigger(trigger 缺省就是 sensitive,除非显式降为 normal)。
|
|
507
|
+
if (op.kind === 'trigger' && op.sensitivity !== 'normal') {
|
|
508
|
+
rejected.push({ term: op.term || null, code: 'LEXICON_SENSITIVE_FORBIDDEN', reason: 'consolidation cannot create sensitive triggers; sensitive vocabulary needs an explicit user write' })
|
|
509
|
+
continue
|
|
510
|
+
}
|
|
511
|
+
try {
|
|
512
|
+
const result = await upsertLexiconTerm({
|
|
513
|
+
libraryId,
|
|
514
|
+
term: op.term,
|
|
515
|
+
kind: op.kind,
|
|
516
|
+
meaning: op.meaning,
|
|
517
|
+
usage: op.usage,
|
|
518
|
+
aliases: op.aliases,
|
|
519
|
+
examples: op.examples,
|
|
520
|
+
context: op.context,
|
|
521
|
+
knownBy: op.knownBy,
|
|
522
|
+
visibility: op.visibility,
|
|
523
|
+
sensitivity: op.sensitivity,
|
|
524
|
+
confidence: op.confidence,
|
|
525
|
+
evidence,
|
|
526
|
+
source: 'curator',
|
|
527
|
+
status: op.needs_review === true ? 'pending' : 'active',
|
|
528
|
+
})
|
|
529
|
+
committed.push({
|
|
530
|
+
termId: result.term.termId,
|
|
531
|
+
term: result.term.term,
|
|
532
|
+
status: result.term.status,
|
|
533
|
+
created: result.created === true,
|
|
534
|
+
notOwned: result.notOwned === true,
|
|
535
|
+
pendingRevision: result.pendingRevision === true,
|
|
536
|
+
})
|
|
537
|
+
} catch (error) {
|
|
538
|
+
rejected.push({ term: op.term || null, code: error?.code || 'LEXICON_OP_FAILED', reason: String(error?.message || error) })
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return { committed, rejected, skipped }
|
|
542
|
+
}
|
|
543
|
+
if (job) job.step = 'committing lexicon ops'
|
|
544
|
+
// 先过 curator 侧 managed 写闸,再进词典自己的文件锁(顺序见函数头注释)。
|
|
545
|
+
return withManagedCuratorWrite(run)
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* 审核决策(spec §4.10):硬门 + 风险分。
|
|
550
|
+
*
|
|
551
|
+
* 硬门恒 pending,不因审核模式放宽:conflict(模型自己承认两段会话打架)、
|
|
552
|
+
* 证据为空(可回放性是底线)、merge/supersede/absorb 的 target 不存在。
|
|
553
|
+
* 非法 target 在这里返回 skip——调用方必须跳过该提案并且**不得**用同一份内容
|
|
554
|
+
* 继续 create(旧代码缺 continue,会把失败的合并悄悄变成一条重复记忆,§0.2)。
|
|
555
|
+
*
|
|
556
|
+
* 风险分只拦"会改写既有内容"的操作:merge/supersede/absorb 在 auto 下风险
|
|
557
|
+
* ≥0.70 才 pending;create 默认通过,needs_review/低置信只记进 risk 供审计与
|
|
558
|
+
* 复核排序。review-all 把全部内容操作都送进复核。风险分上限 2。
|
|
559
|
+
*
|
|
560
|
+
* @returns {{ review: boolean, risk: number, reasons: string[], hard?: boolean } |
|
|
561
|
+
* { skip: true, reason: string }}
|
|
562
|
+
*/
|
|
563
|
+
export function reviewDecision({ m, op, evidence, targetId, index, mode }) {
|
|
564
|
+
// 硬门(恒 pending;不因 mode 放宽)
|
|
565
|
+
if (op === 'conflict') return { review: true, hard: true, risk: 2, reasons: ['conflict'] }
|
|
566
|
+
if (!evidence.length) return { review: true, hard: true, risk: 2, reasons: ['missing evidence'] }
|
|
567
|
+
if (op === 'merge' || op === 'supersede' || op === 'absorb') {
|
|
568
|
+
if (!targetId || !index.entries[targetId]) {
|
|
569
|
+
return { skip: true, reason: `target not found: ${targetId || '(empty)'}` }
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
// 风险分
|
|
573
|
+
let risk = 0
|
|
574
|
+
const reasons = []
|
|
575
|
+
if (m?.needs_review === true) { risk += 0.70; reasons.push('needs_review') }
|
|
576
|
+
if (Number(m?.confidence) < 0.50) { risk += 0.70; reasons.push('confidence<0.50') }
|
|
577
|
+
else if (Number(m?.confidence) < 0.60) { risk += 0.20; reasons.push('confidence<0.60') }
|
|
578
|
+
if (op === 'merge' || op === 'supersede') { risk += 0.20; reasons.push(op) }
|
|
579
|
+
if (op === 'absorb' && (m?.source_ids?.length || 0) > 3) { risk += 0.20; reasons.push('absorb>3 sources') }
|
|
580
|
+
if (m?.review_reason) { risk += 0.20; reasons.push('review_reason') }
|
|
581
|
+
if (evidence.length === 1) { risk += 0.10; reasons.push('single evidence') }
|
|
582
|
+
|
|
583
|
+
const rewrite = op === 'merge' || op === 'supersede' || op === 'absorb'
|
|
584
|
+
const review = mode === 'review-all' || (mode === 'auto' && rewrite && risk >= 0.70)
|
|
585
|
+
return { review, risk: Math.min(2, Number(risk.toFixed(2))), reasons }
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// —— 去重门与冲突门 ——
|
|
589
|
+
// 门语料只含 active + pending_review:archived/superseded 不是"已存在的事实",
|
|
590
|
+
// 不该拦 create,也不该成为 best。LLM 只裁决;提交层用同一把 pair 尺子复核。
|
|
591
|
+
// buildCorpus 的约定是条目自带 id/title/content(track/domain/appliesTo 等
|
|
592
|
+
// 随条目一起落在 doc.entry 上),所以这里直接展开索引条目再补 id。
|
|
593
|
+
function buildGateCorpus(index) {
|
|
594
|
+
const rows = []
|
|
595
|
+
for (const [id, entry] of Object.entries(index?.entries || {})) {
|
|
596
|
+
if (!entry || (entry.status !== 'active' && entry.status !== 'pending_review')) continue
|
|
597
|
+
rows.push({ ...entry, id })
|
|
598
|
+
}
|
|
599
|
+
return buildCorpus(rows)
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const OPS_ALLOWLIST = ['create', 'merge', 'supersede', 'noop', 'conflict', 'link', 'absorb']
|
|
603
|
+
const SCORE_EPSILON = 1e-9
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* 规划阶段(spec §7.2 planCuratorOps):把模型输出拆成 writes / pendings / links /
|
|
607
|
+
* skipped 四类计划;全部语义复核在此完成,提交阶段只做事务。逐条流程:
|
|
608
|
+
* lexicon op → skipped;unknown op → skipped(绝不降级 create);noop → 静默跳过;
|
|
609
|
+
* link → validateGlobalLink 预检(快照索引 + 证据落地),事务内再复核并发面;
|
|
610
|
+
* absorb → skipped 'absorb lands in a later pass'(F2 的 commitCuratorPlans 负责,
|
|
611
|
+
* 它直接从原始输出里取 absorb ops,不受这里的 skip 影响);
|
|
612
|
+
* create/merge/supersede/conflict → 证据落地(§4.6)→ reviewDecision(§4.10)→
|
|
613
|
+
* §4.8 候选门(rankPairCandidates top1):
|
|
614
|
+
* create ≥0.90 同 track/domain → skip 'duplicate of <id>'(pending 同域 →
|
|
615
|
+
* 'duplicate of pending <id>'),warn 日志;
|
|
616
|
+
* create conflict(pairDecision 或 globalConflictCheck 预筛,absorb 带不重复查)→
|
|
617
|
+
* pending 'conflict detected';
|
|
618
|
+
* create 0.82-0.90 → duplicateOf+relatedTo;0.55-0.82 → relatedTo;
|
|
619
|
+
* merge/supersede best 是另一条且高 ≥0.05 → pending 'closest target differs';
|
|
620
|
+
* conflict 恒 pending,target 缺失时用 best。
|
|
621
|
+
*/
|
|
622
|
+
export function planCuratorOps(memories, { index, mode, corpus, sessionCorpus = null, now }) {
|
|
623
|
+
const writes = []
|
|
624
|
+
const pendings = []
|
|
625
|
+
const links = []
|
|
626
|
+
const skipped = []
|
|
627
|
+
const entries = index?.entries || {}
|
|
628
|
+
for (const m of memories) {
|
|
629
|
+
// 词典 op 是私有整理的专属面(§2.1):全局 curator 只写全局记忆。带 libraryId /
|
|
630
|
+
// lexicon 标记的条目在这里一律拒绝——不进向量提交、不进全局索引,只在 skipped 里
|
|
631
|
+
// 留下可读的原因。私有写入走 commitPrivateLexiconOps。
|
|
632
|
+
if (isLexiconOp(m)) {
|
|
633
|
+
skipped.push({ title: m?.term || m?.title, reason: 'lexicon op rejected: the global curator only writes global memory; lexicon ops belong to the private consolidation chain' })
|
|
634
|
+
continue
|
|
635
|
+
}
|
|
636
|
+
// 未知 op 一律拒绝(§4.8):allowlist 之外的 op 不得静默降级成 create——
|
|
637
|
+
// 模型写错 op 名时,降级会凭空写条目。'noop' 是模型的"无可奉告",直接跳过。
|
|
638
|
+
const op = OPS_ALLOWLIST.includes(m?.op) ? m.op : null
|
|
639
|
+
if (op === 'noop') continue
|
|
640
|
+
if (!op) {
|
|
641
|
+
skipped.push({ title: m?.title, reason: `unknown op: ${m?.op ?? '(missing)'}` })
|
|
642
|
+
continue
|
|
643
|
+
}
|
|
644
|
+
// link 分支预检通过才进入 links 计划;落库在提交事务中,
|
|
645
|
+
// 与普通 updates 同一次 updateGlobalIndex;不进 files、不触发向量提交。
|
|
646
|
+
if (op === 'link') {
|
|
647
|
+
const verdict = validateGlobalLink({
|
|
648
|
+
index,
|
|
649
|
+
fromId: m?.from_id,
|
|
650
|
+
toId: m?.to_id,
|
|
651
|
+
kind: m?.kind,
|
|
652
|
+
note: m?.note,
|
|
653
|
+
confidence: m?.confidence,
|
|
654
|
+
evidence: Array.isArray(m?.evidence) ? m.evidence : [],
|
|
655
|
+
sessionCorpus,
|
|
656
|
+
})
|
|
657
|
+
if (!verdict.ok) {
|
|
658
|
+
skipped.push({ title: m?.note || m?.to_id || m?.title, reason: `link rejected: ${verdict.reason}` })
|
|
659
|
+
continue
|
|
660
|
+
}
|
|
661
|
+
links.push({ fromId: verdict.fromId, toId: verdict.toId, kind: verdict.kind, symmetric: verdict.symmetric, link: verdict.link })
|
|
662
|
+
continue
|
|
663
|
+
}
|
|
664
|
+
// absorb 提交属于 F2 的 commitCuratorPlans(从原始 output 自取 absorb ops);
|
|
665
|
+
// 这里显式跳过——planCuratorOps 不把 absorb 当成 create 走内容提交。
|
|
666
|
+
// 注意:absorb 已接线(commitCuratorOutput 里调用 commitCuratorPlans),
|
|
667
|
+
// 这个 skip 只是内容半边的路由,不是"未实现"。
|
|
668
|
+
if (op === 'absorb') {
|
|
669
|
+
skipped.push({ title: m?.title, reason: 'absorb handled by commitCuratorPlans' })
|
|
670
|
+
continue
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// 证据落地(§4.6):quote 必须能回放到本次策划的会话转录;无 corpus(测试/直呼)
|
|
674
|
+
// 时只做形状校验,status='unverified'。有效证据为空是硬门(reviewDecision)。
|
|
675
|
+
const grounded = groundEvidence(Array.isArray(m?.evidence) ? m.evidence : [], sessionCorpus)
|
|
676
|
+
const evidence = grounded.valid.slice(0, EVIDENCE_MAX)
|
|
677
|
+
.map((item) => ({ sessionId: item.sessionId, quote: truncate(item.quote, 500) }))
|
|
678
|
+
const domain = String(m?.domain || '').trim()
|
|
679
|
+
if (!validDomain(domain)) {
|
|
680
|
+
skipped.push({ title: m?.title, reason: `invalid domain: ${domain}` })
|
|
681
|
+
continue
|
|
682
|
+
}
|
|
683
|
+
const track = m?.track === 'skill' ? 'skill' : 'memory'
|
|
684
|
+
const title = String(m?.title || '').trim()
|
|
685
|
+
const content = String(m?.content || '').trim()
|
|
686
|
+
if (!title || !content) {
|
|
687
|
+
skipped.push({ title, reason: 'missing title or content' })
|
|
688
|
+
continue
|
|
689
|
+
}
|
|
690
|
+
const targetId = String(m?.target_id || '').trim()
|
|
691
|
+
const decision = reviewDecision({ m, op, evidence, targetId, index, mode })
|
|
692
|
+
if (decision.skip) {
|
|
693
|
+
// 非法 merge/supersede target 到此为止(§0.2 修复):skipped + continue,
|
|
694
|
+
// 绝不带着同一份内容继续 create。
|
|
695
|
+
skipped.push({ title, reason: decision.reason })
|
|
696
|
+
continue
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// —— §4.8 候选复核门:每次规划用同一语料、同一把尺子。——
|
|
700
|
+
const proposal = {
|
|
701
|
+
id: '__curator_proposal__',
|
|
702
|
+
title, content, track, domain,
|
|
703
|
+
appliesTo: Array.isArray(m?.applies_to) ? m.applies_to : [],
|
|
704
|
+
}
|
|
705
|
+
const candidates = corpus && corpus.size ? rankPairCandidates({ corpus, proposal, limit: PAIR_SCAN_LIMIT }) : []
|
|
706
|
+
const best = candidates[0] || null
|
|
707
|
+
let review = decision.review
|
|
708
|
+
// reviewReason 优先级:硬门 > 候选门(conflict detected / closest target differs)
|
|
709
|
+
// > 模型 review_reason > 'risk threshold'。
|
|
710
|
+
let reviewReason = decision.hard
|
|
711
|
+
? decision.reasons[0]
|
|
712
|
+
: (String(m?.review_reason || '').trim() || 'risk threshold')
|
|
713
|
+
let conflictingWith = targetId || null
|
|
714
|
+
const tags = {}
|
|
715
|
+
if (op === 'create' && best) {
|
|
716
|
+
if (best.score >= PAIR_DUPLICATE_MIN
|
|
717
|
+
&& (best.entry?.track || 'memory') === track
|
|
718
|
+
&& (best.entry?.domain || 'unknown') === domain) {
|
|
719
|
+
const isPending = best.entry?.status === 'pending_review'
|
|
720
|
+
warn(`curator: create skipped, ${isPending ? 'duplicate of pending' : 'duplicate of'} ${best.id} (pair score ${best.score.toFixed(2)})`)
|
|
721
|
+
skipped.push({ title, reason: isPending ? `duplicate of pending ${best.id}` : `duplicate of ${best.id}` })
|
|
722
|
+
continue
|
|
723
|
+
}
|
|
724
|
+
// 冲突检测:pairDecision 的 conflict(同标题正文迥异),或 §4.8 预筛
|
|
725
|
+
// (negation/value/same_title)。duplicate/absorb 带(≥0.82)不重复查——
|
|
726
|
+
// 同标题高相似是同一事实的改写,不是冲突(§4.8 豁免条款的推广)。
|
|
727
|
+
const conflictHit = best.decision === 'conflict' || (best.score < PAIR_ABSORB_MIN
|
|
728
|
+
&& globalConflictCheck(proposal, best.entry, best.features))
|
|
729
|
+
if (conflictHit) {
|
|
730
|
+
review = true
|
|
731
|
+
reviewReason = 'conflict detected'
|
|
732
|
+
conflictingWith = best.id
|
|
733
|
+
} else if (best.score >= PAIR_ABSORB_MIN) {
|
|
734
|
+
tags.duplicateOf = best.id
|
|
735
|
+
tags.relatedTo = best.id
|
|
736
|
+
} else if (best.score >= PAIR_LINK_MIN) {
|
|
737
|
+
tags.relatedTo = best.id
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if ((op === 'merge' || op === 'supersede') && best) {
|
|
741
|
+
// best 是另一条且分数比模型 target 高 ≥0.05 → 最近目标存疑,转人审。
|
|
742
|
+
const targetEntry = entries[targetId]
|
|
743
|
+
const targetScore = targetEntry ? pairScore(pairFeatures(proposal, targetEntry)) : 0
|
|
744
|
+
if (best.id !== targetId && best.score >= targetScore + 0.05 - SCORE_EPSILON) {
|
|
745
|
+
review = true
|
|
746
|
+
reviewReason = 'closest target differs'
|
|
747
|
+
conflictingWith = targetId
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (op === 'conflict' && !targetId && best) conflictingWith = best.id
|
|
751
|
+
|
|
752
|
+
const previous = (op === 'merge' || op === 'supersede') && targetId && entries[targetId] ? entries[targetId] : null
|
|
753
|
+
// A reviewed (held) entry must never occupy the target's id: rejecting the
|
|
754
|
+
// review would archive the only copy and the original active memory would
|
|
755
|
+
// be gone. Held entries always get their own id; only a clean merge writes
|
|
756
|
+
// in place.
|
|
757
|
+
const id = newMemoryId('gmem')
|
|
758
|
+
const entry = {
|
|
759
|
+
track,
|
|
760
|
+
domain,
|
|
761
|
+
appliesTo: Array.isArray(m?.applies_to) ? m.applies_to.slice(0, 20) : [],
|
|
762
|
+
title: truncate(title, 180),
|
|
763
|
+
content: redactSecrets(content),
|
|
764
|
+
confidence: Number.isFinite(Number(m?.confidence)) ? Math.max(0, Math.min(1, Number(m.confidence))) : 0.6,
|
|
765
|
+
evidence: evidence.map((e) => ({
|
|
766
|
+
sessionId: String(e?.sessionId || ''),
|
|
767
|
+
quote: truncate(e?.quote || '', 500),
|
|
768
|
+
})),
|
|
769
|
+
status: 'active',
|
|
770
|
+
supersedes: op === 'supersede' ? targetId || null : previous?.supersedes || null,
|
|
771
|
+
// 风险分写到所有条目(active 也写,§4.10):它是审计/复核排序的统一口径,
|
|
772
|
+
// 不是 pending 的专属属性。旧条目没有这两个字段时按缺省读取,不需要迁移。
|
|
773
|
+
reviewRisk: decision.risk,
|
|
774
|
+
reviewRiskReasons: decision.reasons,
|
|
775
|
+
// 证据是否通过 grounding(§3.1):unverified(直呼/测试)时为 false。
|
|
776
|
+
evidenceVerified: grounded.status === 'grounded',
|
|
777
|
+
createdAt: previous?.createdAt || now,
|
|
778
|
+
updatedAt: now,
|
|
779
|
+
}
|
|
780
|
+
if (tags.duplicateOf) entry.duplicateOf = tags.duplicateOf
|
|
781
|
+
if (tags.relatedTo) entry.relatedTo = tags.relatedTo
|
|
782
|
+
if (review) {
|
|
783
|
+
// Held in the index only: never committed to MemU, so a contested claim
|
|
784
|
+
// cannot be recalled as shared memory until someone decides.
|
|
785
|
+
entry.status = 'pending_review'
|
|
786
|
+
entry.reviewReason = reviewReason
|
|
787
|
+
entry.conflictingWith = conflictingWith
|
|
788
|
+
pendings.push({ id, entry })
|
|
789
|
+
continue
|
|
790
|
+
}
|
|
791
|
+
writes.push({
|
|
792
|
+
id, entry, op, targetId, previous,
|
|
793
|
+
file: { name: id, track, description: truncate(title, 180), content },
|
|
794
|
+
})
|
|
795
|
+
}
|
|
796
|
+
return { writes, pendings, links, skipped }
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// Exported for the audit regression suite: merging the commit decision logic
|
|
800
|
+
// into startGlobalCuration would require standing up subagents to test it.
|
|
801
|
+
export async function commitCuratorOutput(output, { job, sessionCorpus = null } = {}) {
|
|
802
|
+
const returned = Array.isArray(output?.memories) ? output.memories : []
|
|
803
|
+
// 模型输出超过提示词规定的 24 条时,在提交前截断超出部分,并
|
|
804
|
+
// 留一条可观测日志——静默截断会让「为什么少了几条」永远查不到。
|
|
805
|
+
const memories = returned.slice(0, MAX_CURATOR_MEMORIES)
|
|
806
|
+
if (returned.length > MAX_CURATOR_MEMORIES) {
|
|
807
|
+
warn(`curator: output truncated to ${MAX_CURATOR_MEMORIES} memories (${returned.length} returned)`)
|
|
808
|
+
record({
|
|
809
|
+
kind: 'curate', scope: 'global', ok: true, level: 'warn',
|
|
810
|
+
message: `全局提炼输出超过上限,已截断 ${returned.length} → ${MAX_CURATOR_MEMORIES} 条`,
|
|
811
|
+
detail: { op: 'output-truncated', returned: returned.length, kept: memories.length, limit: MAX_CURATOR_MEMORIES },
|
|
812
|
+
})
|
|
813
|
+
}
|
|
814
|
+
if (memories.length === 0) {
|
|
815
|
+
return { files: [], created: 0, merged: 0, superseded: 0, pending: 0, linked: 0, skipped: [], reviewRisk: { max: 0, flagged: 0, reasons: {} } }
|
|
816
|
+
}
|
|
817
|
+
const index = loadGlobalIndex()
|
|
818
|
+
// 模式只在循环外读一次(§4.10):一次策划运行用同一个口径,中途改设置不影响本批。
|
|
819
|
+
const mode = getSettings().curatorReviewMode || 'auto'
|
|
820
|
+
const gateCorpus = buildGateCorpus(index)
|
|
821
|
+
const plan = planCuratorOps(memories, { index, mode, corpus: gateCorpus, sessionCorpus, now: new Date().toISOString() })
|
|
822
|
+
const contentResult = await commitPlannedOps(plan, { job })
|
|
823
|
+
// absorb 半边(F2):planCuratorOps 对 absorb 显式 skip(避免在内容提交里被误当成
|
|
824
|
+
// create),absorb ops 由 commitCuratorPlans 从原始 output 自取并直接提交;这里传
|
|
825
|
+
// 截断后的 memories,保证 24 条上限对 absorb 同样生效。
|
|
826
|
+
const absorbResult = await commitCuratorPlans({ ...(output || {}), memories }, { job })
|
|
827
|
+
return {
|
|
828
|
+
...contentResult,
|
|
829
|
+
absorbed: absorbResult.absorbed,
|
|
830
|
+
pending: contentResult.pending + absorbResult.pending,
|
|
831
|
+
held: absorbResult.held,
|
|
832
|
+
demoted: absorbResult.demoted,
|
|
833
|
+
skipped: [...contentResult.skipped, ...absorbResult.skipped],
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/**
|
|
838
|
+
* 提交阶段(spec §7.2 commitCuratorPlans 的内容操作半边;absorb 半边是 F2 的
|
|
839
|
+
* 同名函数,直接吃原始 output)。单次 updateGlobalIndex 事务内按序应用:
|
|
840
|
+
* pendings(索引 only)→ writes(held clone 检查 / merge 兜底 / supersede)→
|
|
841
|
+
* links(applyGlobalLinks,只有 link 时也要走一次索引事务,§4.9)。
|
|
842
|
+
* link 不进 files、不触发向量提交;两档审核模式都自动应用(C2)。
|
|
843
|
+
*/
|
|
844
|
+
async function commitPlannedOps({ writes, pendings, links, skipped }, { job }) {
|
|
845
|
+
const files = writes.map((w) => w.file)
|
|
846
|
+
const now = new Date().toISOString()
|
|
847
|
+
|
|
848
|
+
// 风险统计(§4.10):本批所有写入条目(active + pending)的审计口径——最高分、
|
|
849
|
+
// 达到复核阈值(≥0.70)的条目数、每类原因出现的次数。
|
|
850
|
+
const written = [...writes.map((w) => w.entry), ...pendings.map((p) => p.entry)]
|
|
851
|
+
const riskReasons = {}
|
|
852
|
+
for (const entry of written) {
|
|
853
|
+
for (const reason of entry.reviewRiskReasons || []) riskReasons[reason] = (riskReasons[reason] || 0) + 1
|
|
854
|
+
}
|
|
855
|
+
const reviewRiskSummary = {
|
|
856
|
+
max: written.length ? Math.max(...written.map((entry) => Number(entry.reviewRisk) || 0)) : 0,
|
|
857
|
+
flagged: written.filter((entry) => (Number(entry.reviewRisk) || 0) >= 0.70).length,
|
|
858
|
+
reasons: riskReasons,
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// 单事务:pendings + writes + links 一次落索引。返回本事务实际落地的 link 列表,
|
|
862
|
+
// 供活动日志逐条记录(retry 重跑时以成功那次的返回为准)。
|
|
863
|
+
const applyPlan = (fresh) => {
|
|
864
|
+
for (const { id, entry } of pendings) fresh.entries[id] = entry
|
|
865
|
+
for (const { id, entry, op, targetId, previous } of writes) {
|
|
866
|
+
if (previous && JSON.stringify(fresh.entries[targetId]) !== JSON.stringify(previous)) {
|
|
867
|
+
const heldId = newMemoryId('gmem')
|
|
868
|
+
// 提交成功的只有 `id` 这一行,held 克隆从未进过向量库——它绝不能继承
|
|
869
|
+
// "提交成功即落戳"的 entry.vector:向量库里的行名是 `id` 而不是 heldId,
|
|
870
|
+
// 带戳会让 membership 把一条不存在的行计进来,而真实存在的 `id` 行反而
|
|
871
|
+
// 无处归属(它根本不会按这个克隆写进索引)。
|
|
872
|
+
const held = { ...entry, status: 'pending_review', conflictingWith: targetId, reviewReason: 'target changed while curator was running' }
|
|
873
|
+
delete held.vector
|
|
874
|
+
fresh.entries[heldId] = held
|
|
875
|
+
continue
|
|
876
|
+
}
|
|
877
|
+
if (op === 'merge' && previous) {
|
|
878
|
+
entry.content = entry.content || previous.content
|
|
879
|
+
entry.title = entry.title || previous.title
|
|
880
|
+
entry.evidence = [...(previous.evidence || []), ...(entry.evidence || [])].slice(-40)
|
|
881
|
+
}
|
|
882
|
+
fresh.entries[id] = entry
|
|
883
|
+
if ((op === 'supersede' || op === 'merge') && targetId && fresh.entries[targetId]) {
|
|
884
|
+
fresh.entries[targetId].status = 'superseded'
|
|
885
|
+
fresh.entries[targetId].supersededBy = id
|
|
886
|
+
fresh.entries[targetId].validTo = now
|
|
887
|
+
fresh.entries[targetId].updatedAt = now
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
return applyGlobalLinks(fresh.entries, links, { now })
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
if (files.length === 0) {
|
|
894
|
+
let linkResult = { applied: [], skipped: [] }
|
|
895
|
+
if (pendings.length || links.length) {
|
|
896
|
+
// 只有 pending/link 时同样要走一次索引事务(§4.9:只有 link 也要调一次
|
|
897
|
+
// updateGlobalIndex);withManagedCuratorWrite 闸门照过,保持锁纪律一致。
|
|
898
|
+
await withManagedCuratorWrite(() => retryStoreWrite(() => updateGlobalIndex((fresh) => {
|
|
899
|
+
linkResult = applyPlan(fresh)
|
|
900
|
+
})))
|
|
901
|
+
}
|
|
902
|
+
for (const applied of linkResult.applied) {
|
|
903
|
+
record({ kind: 'curate', scope: 'global', ok: true, message: `全局关联已落地:${applied.fromId} -(${applied.kind})-> ${applied.toId}`, detail: { op: 'link', from: applied.fromId, to: applied.toId, kind: applied.kind, linkId: applied.linkId } })
|
|
904
|
+
}
|
|
905
|
+
return {
|
|
906
|
+
files: [], created: 0, merged: 0, superseded: 0, pending: pendings.length,
|
|
907
|
+
linked: linkResult.applied.length, skipped, reviewRisk: reviewRiskSummary,
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
job.step = `committing ${files.length} global memories`
|
|
912
|
+
let linkResult = { applied: [], skipped: [] }
|
|
913
|
+
await withManagedCuratorWrite(async () => {
|
|
914
|
+
// Managed agent mode still commits the exact same files to the active local
|
|
915
|
+
// vector database; only pending_review entries remain index-only.
|
|
916
|
+
const route = engineRoute()
|
|
917
|
+
let committedToBackend = false
|
|
918
|
+
try {
|
|
919
|
+
if (route !== 'lexical') {
|
|
920
|
+
await commit({
|
|
921
|
+
payload: { recall_files: files, resource: [], user: {} },
|
|
922
|
+
route, db: globalDbPath(),
|
|
923
|
+
})
|
|
924
|
+
committedToBackend = true
|
|
925
|
+
// 整理写入与单条写入同口径:提交成功就在条目上落"已入向量库"戳,否则这批
|
|
926
|
+
// 全局记忆在向量计数(membership 的戳腿)里永远缺失。pending 不提交,不戳。
|
|
927
|
+
const vector = activeEntryStamp(route)
|
|
928
|
+
if (vector) for (const write of writes) write.entry.vector = vector
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
if (job?.abort?.signal?.aborted) throw new Error('cancelled by user')
|
|
932
|
+
await retryStoreWrite(() => updateGlobalIndex((fresh) => {
|
|
933
|
+
linkResult = applyPlan(fresh)
|
|
934
|
+
}))
|
|
935
|
+
} catch (error) {
|
|
936
|
+
// 提交成功之后(abort 检查 / 索引写)的任何失败都会留下孤儿行:尽力撤销。
|
|
937
|
+
if (committedToBackend) await compensateCuratorCommit(error, { files, route })
|
|
938
|
+
throw error
|
|
939
|
+
}
|
|
940
|
+
})
|
|
941
|
+
for (const applied of linkResult.applied) {
|
|
942
|
+
record({ kind: 'curate', scope: 'global', ok: true, message: `全局关联已落地:${applied.fromId} -(${applied.kind})-> ${applied.toId}`, detail: { op: 'link', from: applied.fromId, to: applied.toId, kind: applied.kind, linkId: applied.linkId } })
|
|
943
|
+
}
|
|
944
|
+
const summary = {
|
|
945
|
+
files,
|
|
946
|
+
created: writes.filter((w) => w.op === 'create').length,
|
|
947
|
+
merged: writes.filter((w) => w.op === 'merge').length,
|
|
948
|
+
superseded: writes.filter((w) => w.op === 'supersede').length,
|
|
949
|
+
pending: pendings.length,
|
|
950
|
+
linked: linkResult.applied.length,
|
|
951
|
+
skipped,
|
|
952
|
+
reviewRisk: reviewRiskSummary,
|
|
953
|
+
}
|
|
954
|
+
record({
|
|
955
|
+
kind: 'curate',
|
|
956
|
+
scope: 'global',
|
|
957
|
+
ok: true,
|
|
958
|
+
message: `全局提炼:新增 ${summary.created} / 合并 ${summary.merged} / 待复核 ${summary.pending}`
|
|
959
|
+
+ (summary.linked ? ` / 关联 ${summary.linked}` : '')
|
|
960
|
+
+ (summary.skipped.length ? ` / 跳过 ${summary.skipped.length}` : ''),
|
|
961
|
+
detail: { ...summary, skipped: summary.skipped.slice(0, 20) },
|
|
962
|
+
refs: files.map((file) => file.name).slice(0, 20),
|
|
963
|
+
})
|
|
964
|
+
return summary
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// ============================================================================
|
|
968
|
+
// absorb 合并稿、提交事务、复核与撤销。
|
|
969
|
+
// ============================================================================
|
|
970
|
+
|
|
971
|
+
// —— absorb 常量(spec §4.12)——单点定义在 lib/curator-policy.js(文件头部 import)。
|
|
972
|
+
// 句级去重的 charDice 阈值只属于合并稿这一处,留在本地。
|
|
973
|
+
const ABSORB_SENTENCE_DICE = 0.9
|
|
974
|
+
|
|
975
|
+
// —— F1 接口(spec §4.1):tokenize/buildCorpus 已由 lib/text-retrieval.js 落地
|
|
976
|
+
//(文件头部 import)。buildCorpus 返回的是 BM25 语料(df/size),这里按 F1 的
|
|
977
|
+
// idfOf 同一公式折算成合并稿 MMR 用的 idf 表。
|
|
978
|
+
function tokensOf(text) {
|
|
979
|
+
return new Set(tokenize(text))
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
function idfMapFromCorpus(corpus) {
|
|
983
|
+
const idf = new Map()
|
|
984
|
+
if (!corpus?.df) return idf
|
|
985
|
+
for (const [term, df] of corpus.df) {
|
|
986
|
+
idf.set(term, Math.log(1 + (corpus.size - df + 0.5) / (df + 0.5)))
|
|
987
|
+
}
|
|
988
|
+
return idf
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
// idf 语料取自当前全局索引的 active 条目(与候选簇同一口径)。
|
|
992
|
+
function absorbIdf(index) {
|
|
993
|
+
const docs = Object.entries(index?.entries || {})
|
|
994
|
+
.filter(([, entry]) => entry && entry.status === 'active')
|
|
995
|
+
.map(([id, entry]) => ({ id, title: entry.title || '', content: entry.content || '' }))
|
|
996
|
+
return idfMapFromCorpus(buildCorpus(docs))
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// —— absorb 合并稿(spec §4.7)——
|
|
1000
|
+
const SENTENCE_RE = /[^。!?!?;;\n]+[。!?!?;;]?/gu
|
|
1001
|
+
|
|
1002
|
+
function splitSentences(text) {
|
|
1003
|
+
const out = []
|
|
1004
|
+
for (const raw of String(text || '').match(SENTENCE_RE) || []) {
|
|
1005
|
+
const sentence = raw.trim()
|
|
1006
|
+
if (sentence) out.push(sentence)
|
|
1007
|
+
}
|
|
1008
|
+
return out
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// token 覆盖率:source 的词元有多大比例出现在 content 里。
|
|
1012
|
+
function tokenCoverage(sourceTokens, contentTokens) {
|
|
1013
|
+
if (!sourceTokens || sourceTokens.size === 0) return 1
|
|
1014
|
+
let hit = 0
|
|
1015
|
+
for (const token of sourceTokens) if (contentTokens.has(token)) hit += 1
|
|
1016
|
+
return hit / sourceTokens.size
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// char 覆盖率:union 的字符 bigram 有多大比例出现在 proposed 里。
|
|
1020
|
+
function charCoverage(unionText, proposedText) {
|
|
1021
|
+
const unionGrams = bigrams(unionText)
|
|
1022
|
+
if (unionGrams.size === 0) return 1
|
|
1023
|
+
const proposedGrams = bigrams(proposedText)
|
|
1024
|
+
let hit = 0
|
|
1025
|
+
for (const gram of unionGrams) if (proposedGrams.has(gram)) hit += 1
|
|
1026
|
+
return hit / unionGrams.size
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
function sentenceInfo(sentence, idf, coveredTokens = null) {
|
|
1030
|
+
let sum = 0
|
|
1031
|
+
for (const token of tokensOf(sentence)) {
|
|
1032
|
+
if (coveredTokens && coveredTokens.has(token)) continue
|
|
1033
|
+
sum += Number(idf?.get?.(token) ?? 1)
|
|
1034
|
+
}
|
|
1035
|
+
return sum
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/**
|
|
1039
|
+
* 吸收合并稿(spec §4.7)。输入 target、sources、模型的 proposed 稿;
|
|
1040
|
+
* 输出 { content, mode, coverage, sourceCoverage, unionCoverage, truncated, omitted }。
|
|
1041
|
+
* 句级去重(charDice ≥0.90 或互含丢弃)→ union(target 在前)→ proposed 覆盖
|
|
1042
|
+
* ≥0.75 且不超长时用 proposed(abstractive),否则 extractive(放得下直接拼接,
|
|
1043
|
+
* 放不下做句子级 MMR:info − 0.7·redundancy·maxInfo 贪心,被丢关键句记 truncated)。
|
|
1044
|
+
* idf 由调用方通过 buildCorpus 提供(F1);缺省按 1 计(spec 已兼容 idf=null)。
|
|
1045
|
+
*/
|
|
1046
|
+
export function composeAbsorbContent({ target, sources = [], proposed = '', maxChars = ABSORB_MAX_CHARS, idf = null } = {}) {
|
|
1047
|
+
const result = { content: '', mode: 'extractive', coverage: 0, sourceCoverage: 1, unionCoverage: 1, truncated: false, omitted: [] }
|
|
1048
|
+
// 1-3. 句子切分 + 句级去重;target 在前,构成 union。origin 记录每个句子的出处
|
|
1049
|
+
//(-1 = target,其余 = sources 下标),供关键句判定使用。
|
|
1050
|
+
const union = []
|
|
1051
|
+
const origins = []
|
|
1052
|
+
const keptKeys = []
|
|
1053
|
+
const pushSentence = (raw, origin) => {
|
|
1054
|
+
const sentence = String(raw || '').trim()
|
|
1055
|
+
const key = clean(sentence)
|
|
1056
|
+
if (!key) return
|
|
1057
|
+
for (const kept of keptKeys) {
|
|
1058
|
+
if (kept === key || kept.includes(key) || key.includes(kept) || dice(bigrams(key), bigrams(kept)) >= ABSORB_SENTENCE_DICE) return
|
|
1059
|
+
}
|
|
1060
|
+
keptKeys.push(key)
|
|
1061
|
+
union.push(sentence)
|
|
1062
|
+
origins.push(origin)
|
|
1063
|
+
}
|
|
1064
|
+
const sourceList = Array.isArray(sources) ? sources : []
|
|
1065
|
+
for (const sentence of splitSentences(target?.content)) pushSentence(sentence, -1)
|
|
1066
|
+
sourceList.forEach((source, index) => {
|
|
1067
|
+
for (const sentence of splitSentences(source?.content)) pushSentence(sentence, index)
|
|
1068
|
+
})
|
|
1069
|
+
if (!union.length) return result
|
|
1070
|
+
const unionText = union.join('')
|
|
1071
|
+
const proposedText = String(proposed || '').trim()
|
|
1072
|
+
|
|
1073
|
+
// 4. proposed 覆盖足够且不超长 → abstractive。
|
|
1074
|
+
if (proposedText) {
|
|
1075
|
+
result.coverage = Math.max(charCoverage(unionText, proposedText), tokenCoverage(tokensOf(unionText), tokensOf(proposedText)))
|
|
1076
|
+
if (result.coverage >= ABSORB_ABSTRACTIVE_COVERAGE && proposedText.length <= maxChars) {
|
|
1077
|
+
result.content = proposedText
|
|
1078
|
+
result.mode = 'abstractive'
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// 5. extractive:总长放得下直接拼接;否则句子级 MMR 贪心到 maxChars。
|
|
1083
|
+
if (result.mode === 'extractive') {
|
|
1084
|
+
const infos = union.map((sentence) => sentenceInfo(sentence, idf))
|
|
1085
|
+
const maxInfo = infos.reduce((acc, value) => Math.max(acc, value), 0)
|
|
1086
|
+
const picked = []
|
|
1087
|
+
const covered = new Set()
|
|
1088
|
+
let length = 0
|
|
1089
|
+
const remaining = new Set(union.map((_, index) => index))
|
|
1090
|
+
while (remaining.size > 0) {
|
|
1091
|
+
let bestIndex = -1
|
|
1092
|
+
let bestScore = -Infinity
|
|
1093
|
+
for (const index of remaining) {
|
|
1094
|
+
let redundancy = 0
|
|
1095
|
+
for (const chosen of picked) redundancy = Math.max(redundancy, dice(bigrams(union[index]), bigrams(union[chosen])))
|
|
1096
|
+
const score = sentenceInfo(union[index], idf, covered) - 0.7 * redundancy * maxInfo
|
|
1097
|
+
if (score > bestScore) { bestScore = score; bestIndex = index }
|
|
1098
|
+
}
|
|
1099
|
+
remaining.delete(bestIndex)
|
|
1100
|
+
if (length + union[bestIndex].length > maxChars) continue
|
|
1101
|
+
picked.push(bestIndex)
|
|
1102
|
+
length += union[bestIndex].length
|
|
1103
|
+
for (const token of tokensOf(union[bestIndex])) covered.add(token)
|
|
1104
|
+
}
|
|
1105
|
+
if (!picked.length && union.length) picked.push(0)
|
|
1106
|
+
// 关键句:target 全部句子 + 每条 source 的 info 前 3 句;被 MMR 丢掉即 truncated。
|
|
1107
|
+
const byOrigin = new Map()
|
|
1108
|
+
union.forEach((_, index) => {
|
|
1109
|
+
if (!byOrigin.has(origins[index])) byOrigin.set(origins[index], [])
|
|
1110
|
+
byOrigin.get(origins[index]).push(index)
|
|
1111
|
+
})
|
|
1112
|
+
const keyIndices = new Set(byOrigin.get(-1) || [])
|
|
1113
|
+
for (const [origin, indices] of byOrigin) {
|
|
1114
|
+
if (origin === -1) continue
|
|
1115
|
+
for (const index of [...indices].sort((a, b) => infos[b] - infos[a]).slice(0, 3)) keyIndices.add(index)
|
|
1116
|
+
}
|
|
1117
|
+
const missingKeys = [...keyIndices].filter((index) => !picked.includes(index)).sort((a, b) => a - b)
|
|
1118
|
+
if (missingKeys.length) {
|
|
1119
|
+
result.truncated = true
|
|
1120
|
+
result.omitted = missingKeys.slice(0, 10).map((index) => union[index])
|
|
1121
|
+
}
|
|
1122
|
+
result.content = picked.sort((a, b) => a - b).map((index) => union[index]).join('')
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// 6. 覆盖率:sourceCoverage = 每条 source 的 token 覆盖率取最小;unionCoverage = 全部
|
|
1126
|
+
// source 词元并集的覆盖率。coverage 是 proposed 对 union 的覆盖(§4.7.4)。
|
|
1127
|
+
const contentTokens = tokensOf(result.content)
|
|
1128
|
+
const presentSources = sourceList.filter((source) => String(source?.content || '').trim())
|
|
1129
|
+
if (presentSources.length) {
|
|
1130
|
+
result.sourceCoverage = Math.min(...presentSources.map((source) => tokenCoverage(tokensOf(String(source.content || '')), contentTokens)))
|
|
1131
|
+
const unionSourceTokens = new Set()
|
|
1132
|
+
for (const source of presentSources) {
|
|
1133
|
+
for (const token of tokensOf(String(source.content || ''))) unionSourceTokens.add(token)
|
|
1134
|
+
}
|
|
1135
|
+
result.unionCoverage = tokenCoverage(unionSourceTokens, contentTokens)
|
|
1136
|
+
}
|
|
1137
|
+
return result
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// absorbOpId(spec §3.1):sha1('absorb|' + sortedIds + '|' + clean(content)).slice(0,16)。
|
|
1141
|
+
// 内容用脱敏后的合并稿,保证从已存条目重算能得到同一个 opId(幂等门靠它对账)。
|
|
1142
|
+
function absorbOpIdOf(sortedIds, content) {
|
|
1143
|
+
return createHash('sha1').update('absorb|' + [...sortedIds].sort().join(',') + '|' + clean(content)).digest('hex').slice(0, 16)
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
function appliesToSubset(sourceApplies, targetApplies) {
|
|
1147
|
+
const target = Array.isArray(targetApplies) ? targetApplies.filter(Boolean) : []
|
|
1148
|
+
if (target.length === 0) return true // target 不限 ⇒ 更宽,任何 source 都算子集
|
|
1149
|
+
const source = Array.isArray(sourceApplies) ? sourceApplies.filter(Boolean) : []
|
|
1150
|
+
return source.every((item) => target.includes(item) || target.includes('all'))
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
const round4 = (value) => Math.round(Number(value) * 10000) / 10000
|
|
1154
|
+
|
|
1155
|
+
/**
|
|
1156
|
+
* absorb 的索引单事务(spec §4.11 auto absorb 步骤 3b-3f)。在 updateGlobalIndex 的
|
|
1157
|
+
* 同步 mutator 里运行;expectedUpdatedAt 任一不匹配时不做任何修改并返回
|
|
1158
|
+
* { landed:false, changed }(调用方决定 held clone 还是抛 'review changed')。
|
|
1159
|
+
* 匹配时:merged 入索引(含出边并入 + absorbSnapshot)、target superseded +
|
|
1160
|
+
* absorbedInto、sources archived + absorbedBy、簇外入边改指 mergedId。
|
|
1161
|
+
*/
|
|
1162
|
+
export function applyAbsorbIndexTransaction(fresh, { mergedId, merged, targetId, sourceIds = [], expectedUpdatedAt = {}, now }) {
|
|
1163
|
+
const entries = fresh.entries
|
|
1164
|
+
const memberIds = [targetId, ...sourceIds].filter(Boolean)
|
|
1165
|
+
const changed = []
|
|
1166
|
+
for (const memberId of memberIds) {
|
|
1167
|
+
const current = entries[memberId]
|
|
1168
|
+
const expected = expectedUpdatedAt[memberId]
|
|
1169
|
+
if (!current || current.status !== 'active' || (expected !== undefined && current.updatedAt !== expected)) {
|
|
1170
|
+
changed.push(memberId || '(missing id)')
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
if (changed.length) return { landed: false, changed }
|
|
1174
|
+
|
|
1175
|
+
const target = entries[targetId]
|
|
1176
|
+
const sourceRefs = sourceIds.map((id) => ({ id, entry: entries[id] }))
|
|
1177
|
+
const clusterIds = new Set(memberIds)
|
|
1178
|
+
const linksOf = (entry) => (Array.isArray(entry?.links) ? entry.links : [])
|
|
1179
|
+
|
|
1180
|
+
// 吸收前状态快照(§4.11 f):rewired 存簇外条目的完整 links,撤销整体恢复。
|
|
1181
|
+
const rewired = []
|
|
1182
|
+
for (const [otherId, other] of Object.entries(entries)) {
|
|
1183
|
+
if (clusterIds.has(otherId) || otherId === mergedId) continue
|
|
1184
|
+
if (linksOf(other).some((link) => clusterIds.has(link?.to))) {
|
|
1185
|
+
rewired.push({ id: otherId, links: structuredClone(linksOf(other)) })
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
// 出边并入 merged:target/sources 自己的 links 按 (to,kind) 去重、cap 20;
|
|
1189
|
+
// 指向簇内的边在吸收后是悬挂边,改指 mergedId,自环直接丢。
|
|
1190
|
+
const outbound = []
|
|
1191
|
+
const seenPairs = new Set()
|
|
1192
|
+
for (const member of [target, ...sourceRefs.map((ref) => ref.entry)]) {
|
|
1193
|
+
for (const link of linksOf(member)) {
|
|
1194
|
+
if (!link || !link.to) continue
|
|
1195
|
+
const key = `${link.to}|${link.kind || 'related'}`
|
|
1196
|
+
if (seenPairs.has(key)) continue
|
|
1197
|
+
seenPairs.add(key)
|
|
1198
|
+
outbound.push(structuredClone(link))
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
const mergedLinks = outbound
|
|
1202
|
+
.map((link) => (clusterIds.has(link.to) ? { ...link, to: mergedId } : link))
|
|
1203
|
+
.filter((link) => link.to !== mergedId)
|
|
1204
|
+
.slice(0, CURATOR_MAX_LINK_ABSORB)
|
|
1205
|
+
|
|
1206
|
+
const mergedEntry = {
|
|
1207
|
+
...merged,
|
|
1208
|
+
links: mergedLinks,
|
|
1209
|
+
updatedAt: now,
|
|
1210
|
+
absorbSnapshot: {
|
|
1211
|
+
target: { id: targetId, status: target.status, links: structuredClone(linksOf(target)), updatedAt: target.updatedAt },
|
|
1212
|
+
sources: sourceRefs.map(({ id, entry }) => ({ id, status: entry.status, links: structuredClone(linksOf(entry)), updatedAt: entry.updatedAt })),
|
|
1213
|
+
rewired,
|
|
1214
|
+
mergedLinks: structuredClone(mergedLinks),
|
|
1215
|
+
at: now,
|
|
1216
|
+
},
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
entries[mergedId] = mergedEntry
|
|
1220
|
+
target.status = 'superseded'
|
|
1221
|
+
target.supersededBy = mergedId
|
|
1222
|
+
target.absorbedInto = mergedId
|
|
1223
|
+
target.validTo = now
|
|
1224
|
+
target.updatedAt = now
|
|
1225
|
+
const audit = { op: 'absorb', at: now, mergedId, targetId, sourceIds: [...sourceIds] }
|
|
1226
|
+
appendAudit(mergedEntry, audit)
|
|
1227
|
+
appendAudit(target, audit)
|
|
1228
|
+
for (const { entry } of sourceRefs) {
|
|
1229
|
+
entry.status = 'archived'
|
|
1230
|
+
entry.absorbedBy = mergedId
|
|
1231
|
+
entry.absorbedAt = now
|
|
1232
|
+
entry.validTo = now
|
|
1233
|
+
entry.updatedAt = now
|
|
1234
|
+
appendAudit(entry, audit)
|
|
1235
|
+
}
|
|
1236
|
+
for (const { id } of rewired) {
|
|
1237
|
+
entries[id].links = entries[id].links.map((link) => (clusterIds.has(link?.to) ? { ...link, to: mergedId } : link))
|
|
1238
|
+
}
|
|
1239
|
+
return { landed: true, at: now }
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
/**
|
|
1243
|
+
* absorb 计划提交(spec §6.7 + §4.7 + §4.10 + §4.11)。输入 curator 输出,只处理
|
|
1244
|
+
* op === 'absorb' 的条目;每条走完 协议校验 → 降级(domain/appliesTo)→ medoid →
|
|
1245
|
+
* 合并稿 → 覆盖率分段 → 重复门 → 风险门,auto 直接落 §4.11 事务,其余生成
|
|
1246
|
+
* §3.3 pendingAbsorb 提案(只进索引,不进向量库)。
|
|
1247
|
+
* 并发变化:不落 active,held pending clone,已提交向量行锁外 best-effort forget。
|
|
1248
|
+
*/
|
|
1249
|
+
export async function commitCuratorPlans(output, { job } = {}) {
|
|
1250
|
+
const memories = Array.isArray(output?.memories) ? output.memories : []
|
|
1251
|
+
const plans = memories.filter((m) => m && m.op === 'absorb')
|
|
1252
|
+
const result = { absorbed: 0, pending: 0, held: 0, skipped: [], demoted: [] }
|
|
1253
|
+
if (!plans.length) return result
|
|
1254
|
+
const index = loadGlobalIndex()
|
|
1255
|
+
// 模式只在循环外读一次(§4.10)。
|
|
1256
|
+
const mode = getSettings().curatorReviewMode || 'auto'
|
|
1257
|
+
const now = new Date().toISOString()
|
|
1258
|
+
const confOf = (value) => (Number.isFinite(Number(value)) ? Number(value) : 0.6)
|
|
1259
|
+
const pendingEntries = []
|
|
1260
|
+
const autoCommits = []
|
|
1261
|
+
const heldNames = []
|
|
1262
|
+
|
|
1263
|
+
for (const plan of plans) {
|
|
1264
|
+
const label = String(plan?.title || plan?.target_id || '(absorb)')
|
|
1265
|
+
// —— 协议校验(§6.7):target active;source 1–5;target 不在 source_ids。——
|
|
1266
|
+
const targetId = String(plan?.target_id || '').trim()
|
|
1267
|
+
const target = targetId ? index.entries[targetId] : null
|
|
1268
|
+
if (!target || target.status !== 'active') {
|
|
1269
|
+
result.skipped.push({ title: label, reason: `absorb target not found or not active: ${targetId || '(empty)'}` })
|
|
1270
|
+
continue
|
|
1271
|
+
}
|
|
1272
|
+
const requestedSources = [...new Set((Array.isArray(plan?.source_ids) ? plan.source_ids : [])
|
|
1273
|
+
.map((id) => String(id || '').trim()).filter(Boolean))]
|
|
1274
|
+
if (requestedSources.length < 1 || requestedSources.length > ABSORB_MAX_SOURCES) {
|
|
1275
|
+
result.skipped.push({ title: label, reason: `absorb needs 1-${ABSORB_MAX_SOURCES} distinct source ids, got ${requestedSources.length}` })
|
|
1276
|
+
continue
|
|
1277
|
+
}
|
|
1278
|
+
if (requestedSources.includes(targetId)) {
|
|
1279
|
+
result.skipped.push({ title: label, reason: 'absorb target must not appear in source_ids' })
|
|
1280
|
+
continue
|
|
1281
|
+
}
|
|
1282
|
+
// —— 降级(§4.7.11):source 的 appliesTo 必须是 target 子集;最终只允许同 domain。
|
|
1283
|
+
// 不满足的 source 不 absorb,降级 link(link 落地由 F1 的 commitCuratorOutput link 分支做)。
|
|
1284
|
+
const sourceRefs = []
|
|
1285
|
+
for (const sourceId of requestedSources) {
|
|
1286
|
+
const source = index.entries[sourceId]
|
|
1287
|
+
if (!source || source.status !== 'active') {
|
|
1288
|
+
result.demoted.push({ targetId, sourceId, reason: 'source not found or not active' })
|
|
1289
|
+
continue
|
|
1290
|
+
}
|
|
1291
|
+
if ((source.track || 'memory') !== (target.track || 'memory')) {
|
|
1292
|
+
result.demoted.push({ targetId, sourceId, reason: 'track differs' })
|
|
1293
|
+
continue
|
|
1294
|
+
}
|
|
1295
|
+
if ((source.domain || 'unknown') !== (target.domain || 'unknown')) {
|
|
1296
|
+
result.demoted.push({ targetId, sourceId, reason: 'domain differs; absorb is same-domain only (link candidate)' })
|
|
1297
|
+
continue
|
|
1298
|
+
}
|
|
1299
|
+
if (!appliesToSubset(source.appliesTo, target.appliesTo)) {
|
|
1300
|
+
result.demoted.push({ targetId, sourceId, reason: 'source appliesTo is not a subset of target; demoted to link candidate' })
|
|
1301
|
+
continue
|
|
1302
|
+
}
|
|
1303
|
+
sourceRefs.push({ id: sourceId, entry: source })
|
|
1304
|
+
}
|
|
1305
|
+
if (!sourceRefs.length) {
|
|
1306
|
+
result.skipped.push({ title: label, reason: 'no eligible source left after domain/appliesTo demotion' })
|
|
1307
|
+
continue
|
|
1308
|
+
}
|
|
1309
|
+
const sources = sourceRefs.map((ref) => ({ ...ref.entry, id: ref.id }))
|
|
1310
|
+
|
|
1311
|
+
// —— medoid/representative(C4):算 medoid,模型 target 只作 provenance,
|
|
1312
|
+
// medoid 平均相似度 <0.55 整簇跳过。——
|
|
1313
|
+
const members = [{ id: targetId, entry: target }, ...sourceRefs.map((ref) => ({ id: ref.id, entry: ref.entry }))]
|
|
1314
|
+
const memberText = new Map(members.map((member) => [member.id, `${member.entry.title || ''} ${member.entry.content || ''}`]))
|
|
1315
|
+
let medoid = null
|
|
1316
|
+
for (const member of members) {
|
|
1317
|
+
let sum = 0
|
|
1318
|
+
for (const other of members) {
|
|
1319
|
+
if (other.id === member.id) continue
|
|
1320
|
+
sum += similarTexts(memberText.get(member.id), memberText.get(other.id))
|
|
1321
|
+
}
|
|
1322
|
+
const avg = sum / Math.max(1, members.length - 1)
|
|
1323
|
+
if (!medoid || avg > medoid.avg) medoid = { id: member.id, avg }
|
|
1324
|
+
}
|
|
1325
|
+
if (!medoid || medoid.avg < CLUSTER_MIN_PAIR) {
|
|
1326
|
+
result.skipped.push({ title: label, reason: `medoid average similarity ${medoid ? medoid.avg.toFixed(2) : 'n/a'} is below the pair floor` })
|
|
1327
|
+
continue
|
|
1328
|
+
}
|
|
1329
|
+
const representativeId = medoid.id
|
|
1330
|
+
|
|
1331
|
+
// —— evidence(§4.6/§4.7.8):plan 证据(带 sourceId)优先,簇内既有证据并集,
|
|
1332
|
+
// 去重 ≤20;每条 source 至少一条 plan 证据覆盖,否则只进复核。——
|
|
1333
|
+
const planEvidence = (Array.isArray(plan?.evidence) ? plan.evidence : [])
|
|
1334
|
+
.filter((item) => typeof item?.session_id === 'string' && item.session_id && typeof item?.quote === 'string' && item.quote.trim())
|
|
1335
|
+
.map((item) => ({
|
|
1336
|
+
sessionId: item.session_id,
|
|
1337
|
+
quote: truncate(item.quote, 500),
|
|
1338
|
+
sourceId: typeof item?.source_id === 'string' && item.source_id.trim() ? item.source_id.trim() : null,
|
|
1339
|
+
}))
|
|
1340
|
+
.slice(0, 20)
|
|
1341
|
+
const clusterEvidence = []
|
|
1342
|
+
const seenEvidence = new Set()
|
|
1343
|
+
for (const item of [...planEvidence, ...members.flatMap((member) => (Array.isArray(member.entry.evidence) ? member.entry.evidence : [])
|
|
1344
|
+
.map((e) => ({ sessionId: e?.sessionId, quote: e?.quote, sourceId: member.id })))] ) {
|
|
1345
|
+
if (clusterEvidence.length >= 20) break
|
|
1346
|
+
const sessionId = typeof item?.sessionId === 'string' ? item.sessionId : null
|
|
1347
|
+
const quote = typeof item?.quote === 'string' ? item.quote : ''
|
|
1348
|
+
if (!sessionId || !quote.trim()) continue
|
|
1349
|
+
const key = `${sessionId}|${clean(quote)}|${item.sourceId || ''}`
|
|
1350
|
+
if (seenEvidence.has(key)) continue
|
|
1351
|
+
seenEvidence.add(key)
|
|
1352
|
+
clusterEvidence.push({ sessionId, quote: truncate(quote, 500), sourceId: item.sourceId || null })
|
|
1353
|
+
}
|
|
1354
|
+
const uncoveredSources = sourceRefs.filter((ref) => !planEvidence.some((item) => item.sourceId === ref.id))
|
|
1355
|
+
|
|
1356
|
+
// —— 合并稿 + 覆盖率分段(§4.7.6)。——
|
|
1357
|
+
const idf = absorbIdf(index)
|
|
1358
|
+
const composed = composeAbsorbContent({ target, sources, proposed: plan?.content, maxChars: ABSORB_MAX_CHARS, idf })
|
|
1359
|
+
const mergedContent = redactSecrets(composed.content)
|
|
1360
|
+
if (!mergedContent.trim()) {
|
|
1361
|
+
result.skipped.push({ title: label, reason: 'absorb produced an empty merged draft' })
|
|
1362
|
+
continue
|
|
1363
|
+
}
|
|
1364
|
+
if (composed.sourceCoverage < ABSORB_REVIEW_SOURCE_COVERAGE || composed.unionCoverage < ABSORB_REVIEW_UNION_COVERAGE) {
|
|
1365
|
+
result.skipped.push({ title: label, reason: `absorb coverage below floor (source ${composed.sourceCoverage.toFixed(2)} / union ${composed.unionCoverage.toFixed(2)})` })
|
|
1366
|
+
continue
|
|
1367
|
+
}
|
|
1368
|
+
const longestSource = Math.max(0, ...sourceRefs.map((ref) => String(ref.entry.content || '').length))
|
|
1369
|
+
const belowLengthFloor = mergedContent.length < ABSORB_MIN_LENGTH_RATIO * longestSource
|
|
1370
|
+
|
|
1371
|
+
// —— 幂等门(§6.7):同 opId 的提案/合并稿已存在 → skip。——
|
|
1372
|
+
const memberIdsSorted = [targetId, ...sourceRefs.map((ref) => ref.id)].sort()
|
|
1373
|
+
const opId = absorbOpIdOf(memberIdsSorted, mergedContent)
|
|
1374
|
+
if (Object.values(index.entries).some((e) => e?.absorbOpId === opId || e?.pendingAbsorb?.opId === opId)) {
|
|
1375
|
+
result.skipped.push({ title: label, reason: `duplicate absorb opId ${opId}; already proposed or absorbed` })
|
|
1376
|
+
continue
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
// —— title(§4.7.7)与重复门(§6.7):与簇外 active 条目 similarTexts ≥0.90 →
|
|
1380
|
+
// pending 'absorb duplicate of <id>';0.55–0.90 → 新条目打 duplicateOf。——
|
|
1381
|
+
const titleCandidate = String(target.title || '').trim()
|
|
1382
|
+
|| String(plan?.title || '').trim()
|
|
1383
|
+
|| String(index.entries[representativeId]?.title || '').trim()
|
|
1384
|
+
const title = truncate(titleCandidate || label, 180)
|
|
1385
|
+
let absorbDuplicate = null
|
|
1386
|
+
for (const [otherId, other] of Object.entries(index.entries || {})) {
|
|
1387
|
+
if (memberIdsSorted.includes(otherId)) continue
|
|
1388
|
+
if (other?.status !== 'active') continue
|
|
1389
|
+
const similarity = similarTexts(`${title} ${mergedContent}`, `${other.title || ''} ${other.content || ''}`)
|
|
1390
|
+
if (similarity > (absorbDuplicate?.similarity ?? 0)) absorbDuplicate = { id: otherId, similarity }
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
// —— 风险分(§4.10):写到所有条目(active 也写)。——
|
|
1394
|
+
const decision = reviewDecision({ m: plan, op: 'absorb', evidence: planEvidence, targetId, index, mode })
|
|
1395
|
+
|
|
1396
|
+
let reviewReason = null
|
|
1397
|
+
if (composed.sourceCoverage < ABSORB_AUTO_SOURCE_COVERAGE || composed.unionCoverage < ABSORB_AUTO_UNION_COVERAGE
|
|
1398
|
+
|| belowLengthFloor || (composed.truncated && composed.omitted.length)) {
|
|
1399
|
+
reviewReason = 'absorb coverage'
|
|
1400
|
+
} else if (absorbDuplicate && absorbDuplicate.similarity >= DUP_REJECT_DICE) {
|
|
1401
|
+
reviewReason = `absorb duplicate of ${absorbDuplicate.id}`
|
|
1402
|
+
} else if (uncoveredSources.length || !planEvidence.length) {
|
|
1403
|
+
reviewReason = decision.hard ? decision.reasons[0] : 'evidence not grounded'
|
|
1404
|
+
} else if (decision.review) {
|
|
1405
|
+
reviewReason = decision.hard ? decision.reasons[0] : (String(plan?.review_reason || '').trim() || 'risk threshold')
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
const confidence = Math.min(0.95, Math.max(confOf(target.confidence), ...sourceRefs.map((ref) => confOf(ref.entry.confidence)), confOf(plan?.confidence)))
|
|
1409
|
+
const clusterCreatedAt = members.map((member) => member.entry.createdAt).filter(Boolean).sort()[0] || now
|
|
1410
|
+
const expectedUpdatedAt = {
|
|
1411
|
+
[targetId]: target.updatedAt,
|
|
1412
|
+
...Object.fromEntries(sourceRefs.map((ref) => [ref.id, ref.entry.updatedAt])),
|
|
1413
|
+
}
|
|
1414
|
+
const reviewRiskReasons = reviewReason === 'absorb coverage' ? [...decision.reasons, 'absorb coverage'] : decision.reasons
|
|
1415
|
+
const entryBase = {
|
|
1416
|
+
track: target.track || 'memory',
|
|
1417
|
+
domain: target.domain || 'general',
|
|
1418
|
+
appliesTo: Array.isArray(target.appliesTo) ? structuredClone(target.appliesTo).slice(0, 20) : [],
|
|
1419
|
+
title,
|
|
1420
|
+
content: mergedContent,
|
|
1421
|
+
confidence,
|
|
1422
|
+
evidence: clusterEvidence,
|
|
1423
|
+
status: 'active',
|
|
1424
|
+
absorbedFrom: memberIdsSorted,
|
|
1425
|
+
absorbedAt: now,
|
|
1426
|
+
absorbOpId: opId,
|
|
1427
|
+
representativeId,
|
|
1428
|
+
mergeMode: composed.mode,
|
|
1429
|
+
mergeCoverage: round4(composed.coverage),
|
|
1430
|
+
sourceCoverage: round4(composed.sourceCoverage),
|
|
1431
|
+
unionCoverage: round4(composed.unionCoverage),
|
|
1432
|
+
reviewRisk: decision.risk,
|
|
1433
|
+
reviewRiskReasons,
|
|
1434
|
+
createdAt: clusterCreatedAt,
|
|
1435
|
+
updatedAt: now,
|
|
1436
|
+
}
|
|
1437
|
+
if (absorbDuplicate && absorbDuplicate.similarity >= TOPIC_DICE && absorbDuplicate.similarity < DUP_REJECT_DICE) {
|
|
1438
|
+
entryBase.duplicateOf = absorbDuplicate.id
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
if (reviewReason) {
|
|
1442
|
+
// pending absorb(§3.3):只进索引,绝不进向量库;accept 时才提交提案 id 本身。
|
|
1443
|
+
pendingEntries.push({
|
|
1444
|
+
id: newMemoryId('gmem'),
|
|
1445
|
+
entry: {
|
|
1446
|
+
...entryBase,
|
|
1447
|
+
status: 'pending_review',
|
|
1448
|
+
reviewReason,
|
|
1449
|
+
conflictingWith: targetId,
|
|
1450
|
+
pendingAbsorb: { targetId, sourceIds: sourceRefs.map((ref) => ref.id), opId, representativeId, expectedUpdatedAt },
|
|
1451
|
+
source: 'curator',
|
|
1452
|
+
},
|
|
1453
|
+
})
|
|
1454
|
+
result.pending += 1
|
|
1455
|
+
continue
|
|
1456
|
+
}
|
|
1457
|
+
autoCommits.push({
|
|
1458
|
+
mergedId: newMemoryId('gmem'),
|
|
1459
|
+
entry: entryBase,
|
|
1460
|
+
targetId,
|
|
1461
|
+
sourceIds: sourceRefs.map((ref) => ref.id),
|
|
1462
|
+
expectedUpdatedAt,
|
|
1463
|
+
})
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
if (pendingEntries.length) {
|
|
1467
|
+
if (job) job.step = `writing ${pendingEntries.length} pending absorb proposals`
|
|
1468
|
+
await withManagedCuratorWrite(() => retryStoreWrite(() => updateGlobalIndex((fresh) => {
|
|
1469
|
+
for (const { id, entry } of pendingEntries) fresh.entries[id] = entry
|
|
1470
|
+
})))
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
if (autoCommits.length) {
|
|
1474
|
+
if (job) job.step = `committing ${autoCommits.length} absorb merges`
|
|
1475
|
+
await withManagedCuratorWrite(async () => {
|
|
1476
|
+
const route = engineRoute()
|
|
1477
|
+
const committedNames = []
|
|
1478
|
+
try {
|
|
1479
|
+
// 先向量后索引(§4.11 auto absorb 步骤 2→3):索引失败时能补偿已提交行。
|
|
1480
|
+
if (route !== 'lexical') {
|
|
1481
|
+
await commit({
|
|
1482
|
+
payload: {
|
|
1483
|
+
recall_files: autoCommits.map(({ mergedId, entry }) => ({ name: mergedId, track: entry.track, description: entry.title, content: entry.content })),
|
|
1484
|
+
resource: [],
|
|
1485
|
+
user: {},
|
|
1486
|
+
},
|
|
1487
|
+
route,
|
|
1488
|
+
db: globalDbPath(),
|
|
1489
|
+
})
|
|
1490
|
+
for (const c of autoCommits) committedNames.push(c.mergedId)
|
|
1491
|
+
const vector = activeEntryStamp(route)
|
|
1492
|
+
if (vector) for (const c of autoCommits) c.entry.vector = vector
|
|
1493
|
+
}
|
|
1494
|
+
await retryStoreWrite(() => updateGlobalIndex((fresh) => {
|
|
1495
|
+
for (const c of autoCommits) {
|
|
1496
|
+
const outcome = applyAbsorbIndexTransaction(fresh, {
|
|
1497
|
+
mergedId: c.mergedId, merged: c.entry, targetId: c.targetId,
|
|
1498
|
+
sourceIds: c.sourceIds, expectedUpdatedAt: c.expectedUpdatedAt, now,
|
|
1499
|
+
})
|
|
1500
|
+
if (!outcome.landed) {
|
|
1501
|
+
// 并发变化(§4.11 步骤 5):不落 active,生成 held pending clone;
|
|
1502
|
+
// expectedUpdatedAt 刷新为当前值,人审时再做快照校验。
|
|
1503
|
+
const heldId = newMemoryId('gmem')
|
|
1504
|
+
const refreshed = {}
|
|
1505
|
+
for (const memberId of [c.targetId, ...c.sourceIds]) {
|
|
1506
|
+
refreshed[memberId] = fresh.entries[memberId]?.updatedAt || c.expectedUpdatedAt[memberId]
|
|
1507
|
+
}
|
|
1508
|
+
const held = {
|
|
1509
|
+
...c.entry,
|
|
1510
|
+
status: 'pending_review',
|
|
1511
|
+
reviewReason: 'cluster changed while curator was running',
|
|
1512
|
+
conflictingWith: c.targetId,
|
|
1513
|
+
pendingAbsorb: { targetId: c.targetId, sourceIds: c.sourceIds, opId: c.entry.absorbOpId, representativeId: c.entry.representativeId, expectedUpdatedAt: refreshed },
|
|
1514
|
+
updatedAt: now,
|
|
1515
|
+
}
|
|
1516
|
+
// 已提交向量库的是 mergedId 这一行;held 克隆从未进过向量库,
|
|
1517
|
+
// entry.vector 必须由当前向量写入结果生成,不能继承旧条目的戳。
|
|
1518
|
+
delete held.vector
|
|
1519
|
+
fresh.entries[heldId] = held
|
|
1520
|
+
heldNames.push(c.mergedId)
|
|
1521
|
+
result.held += 1
|
|
1522
|
+
continue
|
|
1523
|
+
}
|
|
1524
|
+
result.absorbed += 1
|
|
1525
|
+
}
|
|
1526
|
+
}))
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
if (committedNames.length) await compensateCuratorCommit(error, { files: committedNames.map((name) => ({ name })), route })
|
|
1529
|
+
throw error
|
|
1530
|
+
}
|
|
1531
|
+
// held clone 的已提交行 best-effort forget(锁外 await,修 D11);只在向量路由
|
|
1532
|
+
// 真的提交过行时才需要。删不掉必须可见。
|
|
1533
|
+
if (route !== 'lexical') {
|
|
1534
|
+
for (const name of heldNames) {
|
|
1535
|
+
try {
|
|
1536
|
+
await forget({ db: globalDbPath(), name })
|
|
1537
|
+
} catch (forgetError) {
|
|
1538
|
+
record({
|
|
1539
|
+
kind: 'curate', scope: 'global', ok: false, level: 'error',
|
|
1540
|
+
message: `集合吸收并发保护:held clone 已生成,但向量行 ${name} 撤销失败(引擎库残留孤儿行,需手动清理)`,
|
|
1541
|
+
detail: { op: 'absorb', heldForgetFailed: true, name, error: String(forgetError?.message || forgetError) },
|
|
1542
|
+
refs: [name],
|
|
1543
|
+
})
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
})
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
if (result.absorbed || result.pending || result.held || result.skipped.length || result.demoted.length) {
|
|
1551
|
+
record({
|
|
1552
|
+
kind: 'curate',
|
|
1553
|
+
scope: 'global',
|
|
1554
|
+
ok: true,
|
|
1555
|
+
message: `集合吸收:合并 ${result.absorbed} / 待复核 ${result.pending}`
|
|
1556
|
+
+ (result.held ? ` / 并发暂扣 ${result.held}` : '')
|
|
1557
|
+
+ (result.skipped.length ? ` / 跳过 ${result.skipped.length}` : '')
|
|
1558
|
+
+ (result.demoted.length ? ` / 降级 link ${result.demoted.length}` : ''),
|
|
1559
|
+
detail: { op: 'absorb', ...result, skipped: result.skipped.slice(0, 20), demoted: result.demoted.slice(0, 20) },
|
|
1560
|
+
refs: autoCommits.map((c) => c.mergedId).slice(0, 20),
|
|
1561
|
+
})
|
|
1562
|
+
}
|
|
1563
|
+
return result
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* 撤销集合吸收(spec §4.11 undo-absorb)。merged 必须 active 且带 absorbSnapshot;
|
|
1568
|
+
* 同一事务恢复 target/sources/rewired,merged 归档(保留正文)。吸收后又被人工改过
|
|
1569
|
+
* (updatedAt > absorbedAt)的成员拒绝整体撤销并返回可读错误——部分恢复比不恢复更
|
|
1570
|
+
* 难对账。不删除、不写向量。
|
|
1571
|
+
*/
|
|
1572
|
+
export async function undoGlobalAbsorb({ id } = {}) {
|
|
1573
|
+
const mergedId = String(id || '').trim()
|
|
1574
|
+
if (!mergedId) throw new Error('undo-absorb needs the merged entry id')
|
|
1575
|
+
const index = loadGlobalIndex()
|
|
1576
|
+
const merged = index.entries[mergedId]
|
|
1577
|
+
if (!merged || merged.status !== 'active' || !merged.absorbSnapshot) {
|
|
1578
|
+
throw new Error('undo-absorb needs an active merged entry with an absorb snapshot')
|
|
1579
|
+
}
|
|
1580
|
+
const snapshot = merged.absorbSnapshot
|
|
1581
|
+
const memberRefs = [snapshot.target, ...(Array.isArray(snapshot.sources) ? snapshot.sources : [])].filter(Boolean)
|
|
1582
|
+
const changedMembers = []
|
|
1583
|
+
for (const member of memberRefs) {
|
|
1584
|
+
const current = index.entries[member.id]
|
|
1585
|
+
if (!current) continue
|
|
1586
|
+
const absorbedAt = Date.parse(current.absorbedAt || '') || Date.parse(snapshot.at || '') || 0
|
|
1587
|
+
if ((Date.parse(current.updatedAt || '') || 0) > absorbedAt) changedMembers.push(member.id)
|
|
1588
|
+
}
|
|
1589
|
+
if (changedMembers.length) {
|
|
1590
|
+
throw new Error(`absorb undo refused: ${changedMembers.join(', ')} changed after absorption; restore them manually or resolve each edit first`)
|
|
1591
|
+
}
|
|
1592
|
+
await retryStoreWrite(() => updateGlobalIndex((fresh) => {
|
|
1593
|
+
if (JSON.stringify(fresh.entries[mergedId]) !== JSON.stringify(merged)) throw new Error('absorb entry changed; reload and retry')
|
|
1594
|
+
const at = new Date().toISOString()
|
|
1595
|
+
const targetSnap = snapshot.target
|
|
1596
|
+
const currentTarget = targetSnap?.id ? fresh.entries[targetSnap.id] : null
|
|
1597
|
+
if (currentTarget && currentTarget.status === 'superseded' && currentTarget.supersededBy === mergedId) {
|
|
1598
|
+
currentTarget.status = targetSnap.status || 'active'
|
|
1599
|
+
if (Array.isArray(targetSnap.links)) currentTarget.links = structuredClone(targetSnap.links)
|
|
1600
|
+
delete currentTarget.supersededBy
|
|
1601
|
+
delete currentTarget.absorbedInto
|
|
1602
|
+
delete currentTarget.validTo
|
|
1603
|
+
currentTarget.updatedAt = at
|
|
1604
|
+
}
|
|
1605
|
+
for (const sourceSnap of Array.isArray(snapshot.sources) ? snapshot.sources : []) {
|
|
1606
|
+
const current = fresh.entries[sourceSnap.id]
|
|
1607
|
+
if (!current || current.status !== 'archived' || current.absorbedBy !== mergedId) continue
|
|
1608
|
+
current.status = sourceSnap.status || 'active'
|
|
1609
|
+
if (Array.isArray(sourceSnap.links)) current.links = structuredClone(sourceSnap.links)
|
|
1610
|
+
delete current.absorbedBy
|
|
1611
|
+
delete current.absorbedAt
|
|
1612
|
+
delete current.validTo
|
|
1613
|
+
current.updatedAt = at
|
|
1614
|
+
}
|
|
1615
|
+
for (const rewiredSnap of Array.isArray(snapshot.rewired) ? snapshot.rewired : []) {
|
|
1616
|
+
const current = fresh.entries[rewiredSnap.id]
|
|
1617
|
+
if (current && Array.isArray(rewiredSnap.links)) current.links = structuredClone(rewiredSnap.links)
|
|
1618
|
+
}
|
|
1619
|
+
const stored = fresh.entries[mergedId]
|
|
1620
|
+
stored.status = 'archived'
|
|
1621
|
+
stored.absorbUndoneAt = at
|
|
1622
|
+
stored.updatedAt = at
|
|
1623
|
+
const audit = { op: 'undo-absorb', at, mergedId }
|
|
1624
|
+
appendAudit(currentTarget, audit)
|
|
1625
|
+
for (const sourceSnap of Array.isArray(snapshot.sources) ? snapshot.sources : []) {
|
|
1626
|
+
appendAudit(fresh.entries[sourceSnap.id], audit)
|
|
1627
|
+
}
|
|
1628
|
+
appendAudit(stored, audit)
|
|
1629
|
+
}))
|
|
1630
|
+
// 活动日志 CURATOR_ABSORB_UNDO(§4.11 撤销 4):以 detail.op 标记,kind 仍是 curate。
|
|
1631
|
+
record({
|
|
1632
|
+
kind: 'curate',
|
|
1633
|
+
scope: 'global',
|
|
1634
|
+
ok: true,
|
|
1635
|
+
message: `撤销集合吸收 ${mergedId}:target 与来源记忆已恢复,merged 已归档`,
|
|
1636
|
+
detail: { op: 'undo-absorb', id: mergedId, snapshotAt: snapshot.at || null },
|
|
1637
|
+
refs: [mergedId],
|
|
1638
|
+
})
|
|
1639
|
+
return { id: mergedId, status: 'archived', undone: true }
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// —— 宿主契约兼容(docs/host-adaptation.md §3.4:形状变化用能力探测,不按版本号分支)——
|
|
1643
|
+
// 0.2.2-rc.2 随 SubagentActivationSpec 扁平化(parent/cwd/prompt/agentOptions 平铺到
|
|
1644
|
+
// 顶层,无 request 外层)同批在 SubagentService 上新增了树内省方法 rootOf/namesOf/
|
|
1645
|
+
// resolveName/waitForTreeWork(0.2.1-rc.5 与 0.2.2-rc.1 上四者均不存在)。用标记方法
|
|
1646
|
+
// 探测形态,避免向宿主提交不匹配的激活字段。
|
|
1647
|
+
export function activationUsesFlatSpec(subagents) {
|
|
1648
|
+
return typeof subagents?.rootOf === 'function' || typeof subagents?.namesOf === 'function'
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
export function startGlobalCuration(ctx, { sessionIds, parentSessionId, model } = {}) {
|
|
1652
|
+
const ids = [...new Set((Array.isArray(sessionIds) ? sessionIds : []).filter((s) => typeof s === 'string' && s.trim()))]
|
|
1653
|
+
const jobId = `curate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
|
|
1654
|
+
const abort = new AbortController()
|
|
1655
|
+
const job = {
|
|
1656
|
+
id: jobId,
|
|
1657
|
+
status: 'running',
|
|
1658
|
+
step: 'queued',
|
|
1659
|
+
logs: [],
|
|
1660
|
+
createdAt: new Date().toISOString(),
|
|
1661
|
+
endedAt: null,
|
|
1662
|
+
error: null,
|
|
1663
|
+
result: null,
|
|
1664
|
+
abort,
|
|
1665
|
+
}
|
|
1666
|
+
jobs.set(jobId, job)
|
|
1667
|
+
const log = (line) => {
|
|
1668
|
+
job.logs.push(`[${new Date().toISOString()}] ${line}`)
|
|
1669
|
+
if (job.logs.length > 200) job.logs.splice(0, job.logs.length - 200)
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
void (async () => {
|
|
1673
|
+
try {
|
|
1674
|
+
if (ids.length === 0) throw new Error('select at least one conversation')
|
|
1675
|
+
if (ids.length > MAX_SESSIONS) throw new Error(`at most ${MAX_SESSIONS} conversations per curation`)
|
|
1676
|
+
const sessionQuery = ctx.get?.('sessionQuery')
|
|
1677
|
+
if (!sessionQuery) throw new Error('sessionQuery is unavailable')
|
|
1678
|
+
const agents = ctx.get?.('agents')
|
|
1679
|
+
const parent = agents?.get?.(parentSessionId)
|
|
1680
|
+
if (!parent) throw new Error('the current conversation is not live; open a live conversation and retry')
|
|
1681
|
+
const subagents = ctx.get?.('subagents')
|
|
1682
|
+
if (!subagents?.startActivation) throw new Error('subagents service is unavailable')
|
|
1683
|
+
|
|
1684
|
+
job.step = 'reading sessions'
|
|
1685
|
+
log(`reading ${ids.length} session(s)`)
|
|
1686
|
+
const meta = await readSessionMeta(sessionQuery, ids)
|
|
1687
|
+
const sessions = []
|
|
1688
|
+
let total = 0
|
|
1689
|
+
let transcriptTokens = 0
|
|
1690
|
+
for (const id of ids) {
|
|
1691
|
+
if (abort.signal.aborted) throw new Error('cancelled by user')
|
|
1692
|
+
const snapshot = await readSession(sessionQuery, id)
|
|
1693
|
+
const record = meta.get(id)
|
|
1694
|
+
const header = snapshot.header || record?.header || {}
|
|
1695
|
+
const remaining = Math.max(2000, Math.min(MAX_SESSION_CHARS, MAX_TOTAL_CHARS - total))
|
|
1696
|
+
// token 预算跨会话累计(30k),与字符预算同时生效;任一耗尽即停止。
|
|
1697
|
+
const tokenRemaining = Math.max(500, MAX_TRANSCRIPT_TOKENS - transcriptTokens)
|
|
1698
|
+
const transcript = condenseEvents(snapshot.events, remaining, { maxTokens: tokenRemaining })
|
|
1699
|
+
total += transcript.length
|
|
1700
|
+
transcriptTokens += estTokens(transcript)
|
|
1701
|
+
sessions.push({
|
|
1702
|
+
id,
|
|
1703
|
+
title: record?.title || record?.displayTitle || header.title || '',
|
|
1704
|
+
createdAt: header.createdAt || null,
|
|
1705
|
+
cwd: header.cwd || '',
|
|
1706
|
+
// 实际在跑的预设(投影口径),不是 header 的创建事实。
|
|
1707
|
+
agentPreset: effectiveAgentPreset(header, snapshot.events) || '',
|
|
1708
|
+
live: record?.live === true,
|
|
1709
|
+
transcript,
|
|
1710
|
+
})
|
|
1711
|
+
if (total >= MAX_TOTAL_CHARS || transcriptTokens >= MAX_TRANSCRIPT_TOKENS) break
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
// 按相关性打包索引(4000 tokens)与候选簇(2000 tokens),
|
|
1715
|
+
// 取代旧 compactGlobalIndex 的"插入顺序前 200 条"平铺。sessionCorpus 同步构建,
|
|
1716
|
+
// 提交层证据落地(§4.6)用同一份转录做回放校验。
|
|
1717
|
+
const globalIndex = loadGlobalIndex()
|
|
1718
|
+
const sessionText = sessions.map((s) => s.transcript).join('\n')
|
|
1719
|
+
const packedIndex = packCuratorIndexContext({ index: globalIndex, sessionText })
|
|
1720
|
+
const packedClusters = packCuratorClusterContext(buildCandidateClusters(globalIndex))
|
|
1721
|
+
const input = JSON.stringify({
|
|
1722
|
+
sessions,
|
|
1723
|
+
existing_global_index: packedIndex.entries,
|
|
1724
|
+
index_truncated: packedIndex.omitted > 0,
|
|
1725
|
+
candidate_clusters: packedClusters.clusters,
|
|
1726
|
+
clusters_truncated: packedClusters.truncated,
|
|
1727
|
+
})
|
|
1728
|
+
const prompt = loadPrompt('global-curator', { input }).text
|
|
1729
|
+
job.step = 'curator running'
|
|
1730
|
+
log('starting non-main curator subagent')
|
|
1731
|
+
const curatorModel = model || getSettings().curatorModel
|
|
1732
|
+
const agentOptions = agentOptionsFor(curatorModel)
|
|
1733
|
+
const task = {
|
|
1734
|
+
parent,
|
|
1735
|
+
cwd: parent.session?.header?.cwd,
|
|
1736
|
+
prompt: [{ type: 'text', text: prompt }],
|
|
1737
|
+
...(agentOptions ? { agentOptions } : {}),
|
|
1738
|
+
}
|
|
1739
|
+
const base = {
|
|
1740
|
+
provider: 'spawn',
|
|
1741
|
+
label: 'dsh-memu-memory global curator',
|
|
1742
|
+
delivery: 'caller',
|
|
1743
|
+
signal: abort.signal,
|
|
1744
|
+
}
|
|
1745
|
+
const flat = activationUsesFlatSpec(subagents)
|
|
1746
|
+
let activation
|
|
1747
|
+
try {
|
|
1748
|
+
activation = await subagents.startActivation(flat ? { ...base, ...task } : { ...base, request: task })
|
|
1749
|
+
} catch (error) {
|
|
1750
|
+
// 零副作用兜底:两代宿主都在产生任何副作用(建子会话、落盘)之前读取形态
|
|
1751
|
+
// 不符的字段并抛 TypeError——旧契约 src/index.ts 读 spec.request.maxDepth
|
|
1752
|
+
//(0.2.1-rc.5:274 / 0.2.2-rc.1:276),0.2.2-rc.2+:275 读 spec.parent.id。遇到
|
|
1753
|
+
// 极简 mock(只提供 startActivation,无从探测)或未来宿主移除标记方法时,catch
|
|
1754
|
+
// 后换另一种形态重试一次是安全的。仅 TypeError 且未被取消时重试,且只重试一次。
|
|
1755
|
+
if (!(error instanceof TypeError) || abort.signal.aborted) throw error
|
|
1756
|
+
log(`activation shape mismatch (${flat ? 'flat' : 'nested'} rejected by TypeError); retrying with ${flat ? 'nested' : 'flat'} shape`)
|
|
1757
|
+
activation = await subagents.startActivation(flat ? { ...base, request: task } : { ...base, ...task })
|
|
1758
|
+
}
|
|
1759
|
+
let result
|
|
1760
|
+
try {
|
|
1761
|
+
result = await activation.result
|
|
1762
|
+
} finally {
|
|
1763
|
+
try { await activation.dispose() } catch {}
|
|
1764
|
+
}
|
|
1765
|
+
if (result?.stopReason !== 'completed') {
|
|
1766
|
+
throw new Error(`curator stopped: ${result?.stopReason || 'unknown'}`)
|
|
1767
|
+
}
|
|
1768
|
+
const text = textOf(result.output)
|
|
1769
|
+
const output = parseJsonObject(text)
|
|
1770
|
+
if (!output || !Array.isArray(output.memories)) {
|
|
1771
|
+
throw new Error(`curator did not return valid JSON: ${truncate(text, 800)}`)
|
|
1772
|
+
}
|
|
1773
|
+
job.step = 'committing'
|
|
1774
|
+
// 生产调用必须传会话语料(§4.6.6):证据 quote 要能在本次策划的转录里回放,
|
|
1775
|
+
// 否则一律 pending。transcripts 已在 condenseEvents 里脱敏。
|
|
1776
|
+
const committed = await commitCuratorOutput(output, {
|
|
1777
|
+
job,
|
|
1778
|
+
sessionCorpus: buildEvidenceCorpus(sessions.map((s) => ({ id: s.id, transcript: s.transcript }))),
|
|
1779
|
+
})
|
|
1780
|
+
job.status = 'completed'
|
|
1781
|
+
job.endedAt = new Date().toISOString()
|
|
1782
|
+
job.result = {
|
|
1783
|
+
sessions: output.sessions || [],
|
|
1784
|
+
domainSummary: output.domain_summary || {},
|
|
1785
|
+
created: committed.created,
|
|
1786
|
+
merged: committed.merged,
|
|
1787
|
+
superseded: committed.superseded,
|
|
1788
|
+
linked: committed.linked || 0,
|
|
1789
|
+
skipped: committed.skipped,
|
|
1790
|
+
}
|
|
1791
|
+
log(`done: ${committed.created} created, ${committed.merged} merged, ${committed.superseded} superseded, ${committed.linked || 0} linked`)
|
|
1792
|
+
} catch (error) {
|
|
1793
|
+
const aborted = abort.signal.aborted || /cancelled by user/.test(String(error?.message || ''))
|
|
1794
|
+
job.status = aborted ? 'cancelled' : 'error'
|
|
1795
|
+
job.error = String(error?.message || error)
|
|
1796
|
+
job.endedAt = new Date().toISOString()
|
|
1797
|
+
log(`${job.status}: ${job.error}`)
|
|
1798
|
+
// 失败落活动日志:此前只写内存 job.error,宿主重启后失败原因无从追溯
|
|
1799
|
+
//(issue #3 附带观察)。取消不记——那不是故障。
|
|
1800
|
+
if (!aborted) {
|
|
1801
|
+
record({
|
|
1802
|
+
kind: 'curate', scope: 'global', ok: false, level: 'error',
|
|
1803
|
+
message: '全局提炼失败:' + job.error,
|
|
1804
|
+
detail: { jobId, model: model || getSettings().curatorModel, sessions: ids.length, step: job.step || null },
|
|
1805
|
+
})
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
})()
|
|
1809
|
+
|
|
1810
|
+
return getCurationJob(jobId)
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
export { readSession as readSessionSnapshot }
|