dsh-memu-memory 1.4.2 → 1.4.4
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 +173 -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 +85 -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 +1020 -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 +1587 -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 +132 -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 +1522 -1429
package/lib/cycle.js
CHANGED
|
@@ -1,513 +1,524 @@
|
|
|
1
|
-
import {
|
|
2
|
-
getSettings, listSessionBindings, getLastSleepAt, setLastSleepAt,
|
|
3
|
-
getCycleState, setCycleState, listLibrariesAll, archiveLibrary, setSessionBinding,
|
|
4
|
-
deleteLibrary, restoreLibrary, normalizeCwd, inUseLibraryIds, archivedWhileInUse,
|
|
5
|
-
} from './state.js'
|
|
6
|
-
import { expireShortTerm, archiveExpiredDrafts, overdueOpenCommitments, EXPIRED_DRAFT_RETENTION_DAYS } from './memory.js'
|
|
7
|
-
import { requestPrivateConsolidation, archivedSessionIdsOf, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
|
|
8
|
-
import { gcTurnLogs } from './turn-log.js'
|
|
9
|
-
import { startGlobalCuration } from './curator.js'
|
|
10
|
-
import { runVisibilityMigrationPass } from './migrate.js'
|
|
11
|
-
import { runSalientWakePass } from './salient-wake.js'
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return null
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
})
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
//
|
|
144
|
-
//
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
//
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
if (
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
const
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
//
|
|
195
|
-
//
|
|
196
|
-
if (
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
//
|
|
206
|
-
|
|
207
|
-
//
|
|
208
|
-
//
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
if (
|
|
212
|
-
//
|
|
213
|
-
//
|
|
214
|
-
|
|
215
|
-
//
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
//
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
//
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
//
|
|
290
|
-
//
|
|
291
|
-
if (!result.
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
if (isGoneSessionError(error
|
|
303
|
-
setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, sleepFrozenUntil: null, sleepFrozenAt: null, lastSleepError: String(error
|
|
304
|
-
try { clearSessionState(binding.sessionId) } catch {}
|
|
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
|
-
if (
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
return { ran: 0,
|
|
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
|
-
|
|
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
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
if (
|
|
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
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
//
|
|
463
|
-
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
//
|
|
473
|
-
//
|
|
474
|
-
//
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
timer.
|
|
512
|
-
|
|
513
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
getSettings, listSessionBindings, getLastSleepAt, setLastSleepAt,
|
|
3
|
+
getCycleState, setCycleState, listLibrariesAll, archiveLibrary, setSessionBinding,
|
|
4
|
+
deleteLibrary, restoreLibrary, normalizeCwd, inUseLibraryIds, archivedWhileInUse,
|
|
5
|
+
} from './state.js'
|
|
6
|
+
import { expireShortTerm, archiveExpiredDrafts, overdueOpenCommitments, EXPIRED_DRAFT_RETENTION_DAYS } from './memory.js'
|
|
7
|
+
import { requestPrivateConsolidation, archivedSessionIdsOf, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
|
|
8
|
+
import { gcTurnLogs } from './turn-log.js'
|
|
9
|
+
import { startGlobalCuration } from './curator.js'
|
|
10
|
+
import { runVisibilityMigrationPass } from './migrate.js'
|
|
11
|
+
import { runSalientWakePass } from './salient-wake.js'
|
|
12
|
+
import { runMaintenancePass } from './maintenance-runner.js'
|
|
13
|
+
export { runMaintenancePass } from './maintenance-runner.js'
|
|
14
|
+
import { record } from './activity-log.js'
|
|
15
|
+
import { ACTIVE_MEMORY_POLICY, suppressionReason } from './active-memory.js'
|
|
16
|
+
import { clearSessionState, loadLedger, sessionState } from './consolidation-ledger.js'
|
|
17
|
+
|
|
18
|
+
const SWEEP_MS = 5 * 60 * 1000
|
|
19
|
+
// Long enough that the host has restored its session list and the agent objects
|
|
20
|
+
// the fork needs, short enough that a user who opens the app and reads for a minute
|
|
21
|
+
// still gets the catch-up before they type their next message.
|
|
22
|
+
const STARTUP_SWEEP_MS = 8000
|
|
23
|
+
// 「inbound 队列非空就跳过整理」只该挡住「会话马上要进下一回合」的抢跑(issue #5)。
|
|
24
|
+
// 队列只在用户再次发言时才被排空(inject.js 在召回错误/abort/超预算时都会留下
|
|
25
|
+
// pending + 30s retryAt),一次召回异常 + 用户从此不再发言 = pending 永久残留。
|
|
26
|
+
// 所以只有队列非空 **且** 最近一次入站活动在热窗内才让路;凉掉的残骸不再永久阻断。
|
|
27
|
+
const INBOUND_PENDING_HOT_MS = 15 * 60 * 1000
|
|
28
|
+
|
|
29
|
+
function liveAgent(ctx, sessionId) {
|
|
30
|
+
try {
|
|
31
|
+
const agents = ctx.get?.('agents')
|
|
32
|
+
return agents?.get?.(sessionId) || null
|
|
33
|
+
} catch {
|
|
34
|
+
return null
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function older(a, b) {
|
|
39
|
+
const ta = Date.parse(a || '') || 0
|
|
40
|
+
const tb = Date.parse(b || '') || 0
|
|
41
|
+
return ta - tb
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Short-term expiry. Runs before the sleep pass on purpose: a draft that is already
|
|
45
|
+
// past its deadline must not be offered to consolidation as something worth keeping,
|
|
46
|
+
// and promoting a dead entry would resurrect text nobody asked for again.
|
|
47
|
+
// 过期之后的保留期也在同一趟里结算:超期草稿改标 archived(不删除),
|
|
48
|
+
// 免得"第二机会"变成永久占位。
|
|
49
|
+
export function runShortTermPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
|
|
50
|
+
try {
|
|
51
|
+
const result = expireShortTerm({ now })
|
|
52
|
+
if (result.expired.length > 0) {
|
|
53
|
+
log(`expired ${result.expired.length} short-term memor${result.expired.length === 1 ? 'y' : 'ies'} in ${result.libraries.length} library(ies)`)
|
|
54
|
+
}
|
|
55
|
+
let archived = { archived: [], libraries: [], skipped: 0 }
|
|
56
|
+
try {
|
|
57
|
+
archived = archiveExpiredDrafts({ now })
|
|
58
|
+
if (archived.archived.length > 0) {
|
|
59
|
+
log(`archived ${archived.archived.length} expired draft(s) past the retention window`)
|
|
60
|
+
record({
|
|
61
|
+
kind: 'check',
|
|
62
|
+
scope: 'private',
|
|
63
|
+
ok: true,
|
|
64
|
+
message: `过期草稿归档 · ${archived.archived.length} 条(保留期 ${EXPIRED_DRAFT_RETENTION_DAYS} 天,不删除正文)`,
|
|
65
|
+
detail: { ids: archived.archived.map((row) => row.id), libraries: archived.libraries },
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
} catch (error) {
|
|
69
|
+
log(`expired draft archiving failed: ${error?.message || error}`)
|
|
70
|
+
}
|
|
71
|
+
return { ...result, archived }
|
|
72
|
+
} catch (error) {
|
|
73
|
+
log(`short-term expiry failed: ${error?.message || error}`)
|
|
74
|
+
return { expired: [], libraries: [], skipped: 0, archived: { archived: [], libraries: [], skipped: 0 }, error: String(error?.message || error) }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 逾期承诺的周期提醒:只写一条活动日志提示"该结案了",绝不改 status。
|
|
79
|
+
// 承诺有没有兑现要靠转录证据(由整理任务书交给 worker),清理策略不替人裁决。
|
|
80
|
+
// 同一条承诺 7 天内只提示一次,避免每天刷屏。
|
|
81
|
+
const OVERDUE_REVIEW_DAYS = 7
|
|
82
|
+
const OVERDUE_REVIEW_REPEAT_MS = 7 * 86_400_000
|
|
83
|
+
const OVERDUE_REVIEW_KEYS = 500
|
|
84
|
+
|
|
85
|
+
export function runOverdueReviewPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
|
|
86
|
+
try {
|
|
87
|
+
const seen = { ...(getCycleState().overdueReviewAt || {}) }
|
|
88
|
+
const cursors = { ...(getCycleState().overdueReviewCursor || {}) }
|
|
89
|
+
const noted = []
|
|
90
|
+
const liveKeys = new Set()
|
|
91
|
+
for (const lib of listLibrariesAll()) {
|
|
92
|
+
if (lib.archived === true) continue
|
|
93
|
+
const rows = overdueOpenCommitments({ libraryId: lib.id, now, minOverdueDays: OVERDUE_REVIEW_DAYS, allCandidates: true })
|
|
94
|
+
.sort((a, b) => a.id.localeCompare(b.id))
|
|
95
|
+
for (const row of rows) liveKeys.add(`${lib.id}:${row.id}`)
|
|
96
|
+
let cursor = cursors[lib.id] || {}
|
|
97
|
+
// The traversal survives the capped seen table without repeating prefixes.
|
|
98
|
+
if (cursor.completedAt && now - Date.parse(cursor.completedAt) < OVERDUE_REVIEW_REPEAT_MS) continue
|
|
99
|
+
if (cursor.completedAt) cursor = {}
|
|
100
|
+
const remaining = rows.filter(row => !cursor.lastId || row.id.localeCompare(cursor.lastId) > 0)
|
|
101
|
+
const due = remaining.filter((row) => {
|
|
102
|
+
const last = Date.parse(seen[`${lib.id}:${row.id}`] || '') || 0
|
|
103
|
+
return !last || now - last >= OVERDUE_REVIEW_REPEAT_MS
|
|
104
|
+
}).slice(0, 20)
|
|
105
|
+
const lastId = due.at(-1)?.id || cursor.lastId || null
|
|
106
|
+
cursors[lib.id] = { lastId, completedAt: !due.length || !rows.some(row => lastId && row.id.localeCompare(lastId) > 0) ? new Date(now).toISOString() : null }
|
|
107
|
+
if (due.length === 0) continue
|
|
108
|
+
const at = new Date(now).toISOString()
|
|
109
|
+
for (const row of due) {
|
|
110
|
+
seen[`${lib.id}:${row.id}`] = at
|
|
111
|
+
noted.push({ libraryId: lib.id, id: row.id, daysOverdue: row.daysOverdue })
|
|
112
|
+
}
|
|
113
|
+
record({
|
|
114
|
+
kind: 'check',
|
|
115
|
+
scope: 'private',
|
|
116
|
+
libraryId: lib.id,
|
|
117
|
+
ok: true,
|
|
118
|
+
message: `欠账待结案 · ${due.length} 条承诺逾期 ≥${OVERDUE_REVIEW_DAYS} 天(整理时按证据结案)`,
|
|
119
|
+
detail: { ids: due.map((row) => row.id), daysOverdue: due.map((row) => row.daysOverdue) },
|
|
120
|
+
})
|
|
121
|
+
log(`overdue commitments in ${lib.id}: ${due.length} past ${OVERDUE_REVIEW_DAYS} days`)
|
|
122
|
+
}
|
|
123
|
+
// 标记表只留还欠着的 + 60 天内的记录,上限 500,避免无限长。
|
|
124
|
+
const cutoff = now - 60 * 86_400_000
|
|
125
|
+
const kept = Object.entries(seen)
|
|
126
|
+
.filter(([key, at]) => liveKeys.has(key) || (Date.parse(at) || 0) >= cutoff)
|
|
127
|
+
.sort((a, b) => (Date.parse(b[1]) || 0) - (Date.parse(a[1]) || 0))
|
|
128
|
+
.slice(0, OVERDUE_REVIEW_KEYS)
|
|
129
|
+
if (noted.length > 0 || kept.length !== Object.keys(seen).length || JSON.stringify(cursors) !== JSON.stringify(getCycleState().overdueReviewCursor || {})) {
|
|
130
|
+
setCycleState({ overdueReviewAt: Object.fromEntries(kept), overdueReviewCursor: cursors })
|
|
131
|
+
}
|
|
132
|
+
return { noted: noted.length, rows: noted }
|
|
133
|
+
} catch (error) {
|
|
134
|
+
log(`overdue commitment review failed: ${error?.message || error}`)
|
|
135
|
+
return { noted: 0, rows: [], error: String(error?.message || error) }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// The host's answer when a conversation has been deleted: `session "<id>" not
|
|
140
|
+
// found`. It is not transient — retrying it is how a dead session used to be woken
|
|
141
|
+
// up once an hour forever.
|
|
142
|
+
//
|
|
143
|
+
// `ENOENT` is deliberately not part of this list. A missing file is what a failed
|
|
144
|
+
// *read* looks like, and captureSessionSnapshot marks every read failure retryable on
|
|
145
|
+
// purpose (`consolidation-snapshot.js` failed(): "读失败,可重试" → retryable: true).
|
|
146
|
+
// Matching the bare word here turned one unreadable transcript into `sessionGone`,
|
|
147
|
+
// and the sweep then skips that conversation (`if (binding.sessionGone) continue`)
|
|
148
|
+
// until `lib/inbound.js` clears the mark on some later human message — so a
|
|
149
|
+
// quiet-but-alive conversation silently stopped being consolidated.
|
|
150
|
+
export function isGoneSessionError(message) {
|
|
151
|
+
return /session[^"]*".*" not found|no such session|session .*does not exist/i.test(String(message || ''))
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Sleep consolidation: after a conversation has been quiet for a while, the agent
|
|
155
|
+
// gets one instruction to tidy the library it wrote during it. Failed attempts
|
|
156
|
+
// back off, but never pretend that an unread transcript was consolidated.
|
|
157
|
+
//
|
|
158
|
+
// Two things this pass must not do. It must not wake a conversation that no longer
|
|
159
|
+
// exists: the host answers "session not found" for it forever, and the retry curve
|
|
160
|
+
// tops out at one hour, so one deleted chat used to be retried for the life of the
|
|
161
|
+
// install. And it must not read "there are new turns" as "there is something worth
|
|
162
|
+
// remembering" — `assessConsolidationValue` inspects the transcript first, and a
|
|
163
|
+
// session that only exchanged greetings is marked asleep instead of being forked.
|
|
164
|
+
export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limit = 2 } = {}) {
|
|
165
|
+
const settings = getSettings()
|
|
166
|
+
if (settings.sleepConsolidation !== true) return { ran: 0, skipped: 'disabled' }
|
|
167
|
+
const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) || 2) * 60_000
|
|
168
|
+
const probeMs = Math.max(1, Number(CONSOLIDATION_PROBE_MINUTES) || 15) * 60_000
|
|
169
|
+
// One ledger read per sweep: pending backlog is the cheap水位 signal that does
|
|
170
|
+
// not need a transcript read.
|
|
171
|
+
let ledger = null
|
|
172
|
+
try { ledger = loadLedger() } catch { ledger = null }
|
|
173
|
+
// 宿主会在 agent/pre-step 拒绝祖先含归档会话的 subagent;提前过滤,
|
|
174
|
+
// 避免将确定不可执行的整理记为 snapshot-failed。
|
|
175
|
+
// 在候选阶段直接 continue:不占 budget 名额、不计失败、不推进游标。空注册表 =
|
|
176
|
+
// 无成员信息,与 rpc.js 的读法一致,不当成「全是归档」。
|
|
177
|
+
const archived = archivedSessionIdsOf(ctx)
|
|
178
|
+
// 归档库同样不该再整理:宿主侧 archivedSessionIds 只覆盖「会话被归档」,拿不到
|
|
179
|
+
// workspaceRegistry 时它为空集,因此还需检查库的归档状态,防止向归档库继续写入。
|
|
180
|
+
const libraries = new Map(listLibrariesAll().map(lib => [lib.id, lib]))
|
|
181
|
+
const candidates = []
|
|
182
|
+
for (const binding of listSessionBindings()) {
|
|
183
|
+
if (binding.consolidationFork || !binding.lastTurnAt) continue
|
|
184
|
+
if (binding.sessionGone) continue
|
|
185
|
+
if (binding.libraryId && libraries.get(binding.libraryId)?.archived === true) continue
|
|
186
|
+
if (archived?.size && archived.has(String(binding.sessionId))) continue
|
|
187
|
+
const lastSleepAt = getLastSleepAt(binding.sessionId)
|
|
188
|
+
const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 0)
|
|
189
|
+
const idle = now - activeAt >= idleMs
|
|
190
|
+
const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
|
|
191
|
+
const state = ledger ? sessionState(binding.sessionId, ledger) : null
|
|
192
|
+
// The ledger's backoff used to be write-only: failJob stored retryAt and nothing
|
|
193
|
+
// ever read it, so a session that failed three times was retried on the very next
|
|
194
|
+
// sweep, five minutes later, forever. `sleepRetryAt` below is a different clock —
|
|
195
|
+
// that one delays the next *window*, this one delays the retry after a *failure*.
|
|
196
|
+
if ((Date.parse(state?.retryAt || '') || 0) > now) continue
|
|
197
|
+
const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
|
|
198
|
+
? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
|
|
199
|
+
: 0
|
|
200
|
+
const backlog = pendingEvents >= CONSOLIDATION_BACKLOG_EVENTS
|
|
201
|
+
const neverSlept = !lastSleepAt
|
|
202
|
+
const lastProbe = Date.parse(binding.lastConsolidationProbeAt || '') || 0
|
|
203
|
+
const probeDue = newActivity && now - lastProbe >= probeMs
|
|
204
|
+
// Idle time alone is not new evidence: after a successful window the sleep
|
|
205
|
+
// stamp already covers the transcript, so a quiet idle sweep must not fork it again.
|
|
206
|
+
if (!newActivity && !backlog) continue
|
|
207
|
+
// Three independent reasons to look: idle (normal), a real pending backlog
|
|
208
|
+
// (watermark), or a bounded probe when new activity has arrived but not enough
|
|
209
|
+
// to know its size yet. The probe reads the transcript and decides without a
|
|
210
|
+
// fork, so it costs CPU, not tokens.
|
|
211
|
+
if (!idle && !backlog && !neverSlept && !probeDue) continue
|
|
212
|
+
// Running includes a long-lived asynchronous tool. Waiting is not proof that
|
|
213
|
+
// the conversation ended, and a fork should not race its active agent.
|
|
214
|
+
if (liveAgent(ctx, binding.sessionId)?.status === 'running') continue
|
|
215
|
+
// Fresh inbound queue = a step may be about to race the fork. A queue that has
|
|
216
|
+
// gone cold (no inbound activity within INBOUND_PENDING_HOT_MS) is residue from
|
|
217
|
+
// a recall error that only the user's next message would drain — it must not
|
|
218
|
+
// block idle consolidation forever (issue #5).
|
|
219
|
+
const inboundFreshAt = Math.max(Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastInboundOutcome?.at) || 0)
|
|
220
|
+
if (binding.inbound?.pending?.length && now - inboundFreshAt < INBOUND_PENDING_HOT_MS) continue
|
|
221
|
+
if ((Date.parse(binding.sleepRetryAt || '') || 0) > now) continue
|
|
222
|
+
// 冻结退避(1.3.10):snapshot-failed 熔断期不再每扫重读快照/种子、不占 budget 名额。
|
|
223
|
+
// 但冻结后来了新真人回合(lastTurnAt 越过 frozenAt)立刻让路——新事件改快照哈希、
|
|
224
|
+
// 闸门本就会放行;退避只挡「无新活动的重复扫入」,不惩罚新活动。独立字段,不碰
|
|
225
|
+
// sleepRetryAt(后者不因新消息清零,复用它会挡死冻结期新活动)。
|
|
226
|
+
const frozenUntil = Date.parse(binding.sleepFrozenUntil || '') || 0
|
|
227
|
+
if (frozenUntil > now && (Date.parse(binding.lastTurnAt) || 0) <= (Date.parse(binding.sleepFrozenAt) || 0)) continue
|
|
228
|
+
// Backlog first, then real idle, then cheap probes: a sweep with a limited
|
|
229
|
+
// budget must not let probe-only sessions crowd out work that is actually due.
|
|
230
|
+
candidates.push({ binding, activeAt, trigger: idle ? 'idle' : 'backlog', priority: backlog ? 3 : idle ? 2 : 1 })
|
|
231
|
+
}
|
|
232
|
+
// Newest first within the same priority: a catch-up run after the app was closed
|
|
233
|
+
// should tidy what the user just lived through, not a week-old chat that has
|
|
234
|
+
// already waited this long.
|
|
235
|
+
candidates.sort((a, b) => (b.priority - a.priority) || (b.activeAt - a.activeAt))
|
|
236
|
+
const budget = Math.max(1, Math.min(10, Number(limit) || 2))
|
|
237
|
+
let ran = 0
|
|
238
|
+
for (const { binding, trigger } of candidates.slice(0, budget)) {
|
|
239
|
+
if (binding.useLibrary === false) {
|
|
240
|
+
setLastSleepAt(binding.sessionId)
|
|
241
|
+
continue
|
|
242
|
+
}
|
|
243
|
+
// One path for every session: both backends now read the transcript
|
|
244
|
+
// themselves and neither touches the user's own chat — remote through the
|
|
245
|
+
// configured endpoint, agent through a seeded fork (requestHistoricalConsolidation).
|
|
246
|
+
// A live session used to be consolidated in place, which is exactly what put
|
|
247
|
+
// a queued draft above the user's composer and then left a housekeeping turn
|
|
248
|
+
// in their transcript for good.
|
|
249
|
+
const suppression = suppressionReason({
|
|
250
|
+
now,
|
|
251
|
+
lastSleepAt: getLastSleepAt(binding.sessionId),
|
|
252
|
+
lastInjectedAt: binding.lastInjectedAt || null,
|
|
253
|
+
consolidatedCooldownMinutes: Number(settings.activeMemoryCooldownMinutes ?? ACTIVE_MEMORY_POLICY.consolidatedCooldownMinutes),
|
|
254
|
+
recallCooldownMinutes: Number(settings.activeMemoryRecallCooldownMinutes ?? ACTIVE_MEMORY_POLICY.recallCooldownMinutes),
|
|
255
|
+
})
|
|
256
|
+
// 「刚注入过记忆」只压空闲收尾,不压水位/探针:后者先读转录再决定,不合并不 fork。
|
|
257
|
+
const blocked = suppression && !(trigger === 'backlog' && suppression === 'recent-recall')
|
|
258
|
+
if (blocked) {
|
|
259
|
+
log(`sleep consolidation suppressed for ${binding.sessionId}: ${suppression}`)
|
|
260
|
+
record({
|
|
261
|
+
kind: 'check', scope: 'private', sessionId: binding.sessionId, libraryId: binding.libraryId || null, ok: true,
|
|
262
|
+
message: '闲时检查抑制:' + suppression,
|
|
263
|
+
detail: { trigger, reason: suppression, lastSleepAt: getLastSleepAt(binding.sessionId), lastInjectedAt: binding.lastInjectedAt || null },
|
|
264
|
+
})
|
|
265
|
+
continue
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
const result = await requestPrivateConsolidation(ctx, binding.sessionId, { trigger })
|
|
269
|
+
if (result?.ok) {
|
|
270
|
+
// 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
|
|
271
|
+
// 或后续证据变多再检查。否则这句话会被永久跳过。
|
|
272
|
+
if (result.settled === false) {
|
|
273
|
+
// 任何没结算的结果都要记探针时间,不只是「水位不足」那两种:low-score 也
|
|
274
|
+
// 会读一遍转录并打分,不记就会在每次 5 分钟扫描里把同一段重读一遍。
|
|
275
|
+
const patch = { lastConsolidationProbeAt: new Date(now).toISOString(), sleepFrozenUntil: null, sleepFrozenAt: null }
|
|
276
|
+
// snapshot-failed 冻结:写独立退避字段,候选阶段守卫据此跳过无新活动的重复
|
|
277
|
+
// 扫入;新真人回合到来即让路。非冻结的 deferral 顺手清掉可能残留的冻结字段。
|
|
278
|
+
if (result.reasonCode === 'snapshot-failed-too-many' && result.cooldownUntil) {
|
|
279
|
+
patch.sleepFrozenUntil = result.cooldownUntil
|
|
280
|
+
patch.sleepFrozenAt = result.frozenAt || null
|
|
281
|
+
}
|
|
282
|
+
setSessionBinding(binding.sessionId, patch)
|
|
283
|
+
log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
|
|
284
|
+
continue
|
|
285
|
+
}
|
|
286
|
+
// Only cover activity this pass began with, not new messages during it.
|
|
287
|
+
// 多窗收口(issue #4 缺陷 2):`settled` 是「本窗完成」的语义,ledger 的
|
|
288
|
+
// lastSleepSeq 已随本窗回执推进(private.js advanceSleepCursor),不会重扫;
|
|
289
|
+
// 但粗游标 lastSleepAt 只有在整段(remaining === 0)扫完时才推平——否则
|
|
290
|
+
// 尾段 < 200 事件(backlog 够不着)的会话会在候选阶段 `!newActivity && !backlog` 处被永久跳过。
|
|
291
|
+
if (!(Number(result.remaining) > 0)) {
|
|
292
|
+
setLastSleepAt(binding.sessionId, binding.lastTurnAt)
|
|
293
|
+
}
|
|
294
|
+
setSessionBinding(binding.sessionId, {
|
|
295
|
+
sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null,
|
|
296
|
+
sleepFrozenUntil: null, sleepFrozenAt: null,
|
|
297
|
+
lastConsolidationProbeAt: new Date(now).toISOString(),
|
|
298
|
+
})
|
|
299
|
+
// A terminal policy skip (greetings, no new events) advances the sleep stamp
|
|
300
|
+
// but is not a verified worker run; `ran` must keep that distinction.
|
|
301
|
+
if (!result.skipped) ran += 1
|
|
302
|
+
} else if (isGoneSessionError(result?.error)) {
|
|
303
|
+
setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, sleepFrozenUntil: null, sleepFrozenAt: null, lastSleepError: String(result.error) })
|
|
304
|
+
try { clearSessionState(binding.sessionId) } catch {}
|
|
305
|
+
log(`sleep consolidation dropped ${binding.sessionId}: the conversation no longer exists`)
|
|
306
|
+
} else {
|
|
307
|
+
const attempts = Number(binding.sleepAttempts || 0) + 1
|
|
308
|
+
setSessionBinding(binding.sessionId, { sleepAttempts: attempts, lastSleepError: result?.error || 'not settled', sleepRetryAt: new Date(now + Math.min(60, 2 ** Math.min(attempts, 6)) * 60_000).toISOString() })
|
|
309
|
+
log(`sleep consolidation skipped for ${binding.sessionId}: ${result?.error || 'not queued'}`)
|
|
310
|
+
}
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (isGoneSessionError(error?.message)) {
|
|
313
|
+
setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, sleepFrozenUntil: null, sleepFrozenAt: null, lastSleepError: String(error.message) })
|
|
314
|
+
try { clearSessionState(binding.sessionId) } catch {}
|
|
315
|
+
continue
|
|
316
|
+
}
|
|
317
|
+
// A missing service or transient file failure can heal without a new turn.
|
|
318
|
+
const attempts = Number(binding.sleepAttempts || 0) + 1
|
|
319
|
+
setSessionBinding(binding.sessionId, { sleepAttempts: attempts, lastSleepError: String(error?.message || error), sleepRetryAt: new Date(now + Math.min(60, 2 ** Math.min(attempts, 6)) * 60_000).toISOString() })
|
|
320
|
+
log(`sleep consolidation failed for ${binding.sessionId}: ${error?.message || error}`)
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return { ran, considered: candidates.length }
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// 休眠 GC 的 turn-log 分配(设计文档 §3.4):对每个绑定做两条件检查——日志无未结算
|
|
327
|
+
// 增量(max seqEnd ≤ lastSleepSeq)且会话 ≥30 天无任何活动 → 删缓存文件。便宜检查:
|
|
328
|
+
// 只读绑定表 + 文件 stat/mtime,仅对已闲置满期的少数绑定才读日志内容找 max seqEnd;
|
|
329
|
+
// 没有日志文件的绑定直接跳过。异常只 warn,绝不绊倒 sweep 的其他 pass。
|
|
330
|
+
export function runTurnLogGcPass(_ctx, { now = Date.now(), log = () => {} } = {}) {
|
|
331
|
+
try {
|
|
332
|
+
const result = gcTurnLogs(listSessionBindings(), { now })
|
|
333
|
+
if (result.deleted.length > 0) log(`turn-log gc deleted ${result.deleted.length} idle turn log(s)`)
|
|
334
|
+
return result
|
|
335
|
+
} catch (error) {
|
|
336
|
+
log(`turn-log gc failed: ${error?.message || error}`)
|
|
337
|
+
return { deleted: [], kept: [], error: String(error?.message || error) }
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Background global curation: turn the conversations that happened since the last
|
|
342
|
+
// run into shared memory, using whichever session is live as the curator's parent.
|
|
343
|
+
export async function runCurationPass(ctx, { now = Date.now(), log = () => {} } = {}) {
|
|
344
|
+
const settings = getSettings()
|
|
345
|
+
const hours = Number(settings.autoCurateEveryHours) || 0
|
|
346
|
+
if (!(hours > 0)) return { ran: 0, skipped: 'disabled' }
|
|
347
|
+
const lastRunAt = Date.parse(getCycleState().lastCurateAt || '') || 0
|
|
348
|
+
if (now - lastRunAt < hours * 3_600_000) return { ran: 0, skipped: 'not-due' }
|
|
349
|
+
|
|
350
|
+
const limit = Math.max(1, Math.min(30, Number(settings.autoCurateSessionLimit) || 8))
|
|
351
|
+
const due = listSessionBindings()
|
|
352
|
+
.filter((b) => !b.consolidationFork && b.lastTurnAt && older(b.lastTurnAt, new Date(lastRunAt).toISOString()) > 0)
|
|
353
|
+
.sort((a, b) => String(b.lastTurnAt).localeCompare(String(a.lastTurnAt)))
|
|
354
|
+
.slice(0, limit)
|
|
355
|
+
.map((b) => b.sessionId)
|
|
356
|
+
if (due.length === 0) return { ran: 0, skipped: 'no-new-sessions' }
|
|
357
|
+
|
|
358
|
+
const parent = due.find((id) => liveAgent(ctx, id))
|
|
359
|
+
|| listSessionBindings().filter((b) => !b.consolidationFork).map((b) => b.sessionId).find((id) => liveAgent(ctx, id))
|
|
360
|
+
if (!parent) {
|
|
361
|
+
// Deliberately not recording the attempt: the next sweep retries, and a run
|
|
362
|
+
// that never started must not push the schedule forward.
|
|
363
|
+
log('auto curation waiting for a live session to host the curator')
|
|
364
|
+
return { ran: 0, skipped: 'no-live-parent' }
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
const job = await startGlobalCuration(ctx, { sessionIds: due, parentSessionId: parent, model: settings.curatorModel })
|
|
368
|
+
setCycleState({ lastCurateAt: new Date(now).toISOString(), lastCurateJob: job?.id || null })
|
|
369
|
+
record({ kind: 'curate', scope: 'global', ok: true, message: `自动提炼启动:${due.length} 个会话`, detail: { sessions: due.length, jobId: job?.id || null, parent } })
|
|
370
|
+
return { ran: due.length, job }
|
|
371
|
+
} catch (error) {
|
|
372
|
+
log(`auto curation failed: ${error?.message || error}`)
|
|
373
|
+
record({ kind: 'curate', scope: 'global', ok: false, level: 'error', message: '自动提炼失败:' + String(error?.message || error), detail: { sessions: due.length } })
|
|
374
|
+
return { ran: 0, error: String(error?.message || error) }
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// A library leaves daily use when its workspace is removed from DSH — which is a
|
|
379
|
+
// pure unregister: the folder and every session log stay on disk. So the trigger is
|
|
380
|
+
// the workspace registry, never `fs.existsSync`. A deleted folder is not "removed
|
|
381
|
+
// from DSH", and a folder taken out of the sidebar still exists.
|
|
382
|
+
function registeredScopes(ctx) {
|
|
383
|
+
let registry = null
|
|
384
|
+
try { registry = ctx.get?.('workspaceRegistry') } catch { return null }
|
|
385
|
+
if (!registry || typeof registry.list !== 'function') return null
|
|
386
|
+
let list
|
|
387
|
+
try { list = registry.list() } catch { return null }
|
|
388
|
+
if (!Array.isArray(list)) return null
|
|
389
|
+
// An empty registry is not trusted: a fresh install with no workspace yet must not
|
|
390
|
+
// archive every library ever created.
|
|
391
|
+
const scopes = list.map((ws) => normalizeCwd(ws?.path)).filter(Boolean)
|
|
392
|
+
return { scopes: new Set(scopes), trustworthy: scopes.length > 0 }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// 同一个库每 5 分钟重复一条「因为在用所以没归档」只会把宿主日志淹掉,说一次就够;
|
|
396
|
+
// 归档或复活都会清掉这个标记。
|
|
397
|
+
const inUseSkipNotified = new Set()
|
|
398
|
+
|
|
399
|
+
function noteInUseSkip(libraryId, scopeKey, log) {
|
|
400
|
+
if (inUseSkipNotified.has(libraryId)) return
|
|
401
|
+
inUseSkipNotified.add(libraryId)
|
|
402
|
+
log(`kept library ${libraryId}: workspace ${scopeKey} is not in the DSH registry, but a live conversation still uses it`)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export function runLibraryHousekeeping(ctx, { now = Date.now(), log = () => {} } = {}) {
|
|
406
|
+
const settings = getSettings()
|
|
407
|
+
const archived = []
|
|
408
|
+
const revived = []
|
|
409
|
+
const purged = []
|
|
410
|
+
const skippedInUse = []
|
|
411
|
+
const purgeCandidates = []
|
|
412
|
+
const registry = registeredScopes(ctx)
|
|
413
|
+
// 一次读盘算出「哪些库还有存活绑定」。这是归档判定缺的那一半:注册表只回答
|
|
414
|
+
// 「这个目录是不是 DSH 工作区」,不回答「这个库还有没有人用」。
|
|
415
|
+
const inUse = inUseLibraryIds()
|
|
416
|
+
|
|
417
|
+
for (const lib of listLibrariesAll()) {
|
|
418
|
+
const used = inUse.has(lib.id)
|
|
419
|
+
if (lib.archived === true) {
|
|
420
|
+
const scopeBack = Boolean(registry?.trustworthy && registry.scopes.has(lib.scopeKey))
|
|
421
|
+
// 误归档(旧版扫描把在用的非工作区库归档了):库还在被读取写入,就该回到列表。
|
|
422
|
+
// 用户主动归档(archivedBy === 'user')不动——那是用户的决定。
|
|
423
|
+
const misArchived = archivedWhileInUse(lib, { inUse: used, now })
|
|
424
|
+
if (scopeBack || misArchived) {
|
|
425
|
+
if (restoreLibrary(lib.id).ok) {
|
|
426
|
+
revived.push(lib.id)
|
|
427
|
+
inUseSkipNotified.delete(lib.id)
|
|
428
|
+
if (misArchived && !scopeBack) log(`revived library ${lib.id}: a live conversation still uses it`)
|
|
429
|
+
}
|
|
430
|
+
continue
|
|
431
|
+
}
|
|
432
|
+
const days = Number(settings.purgeArchivedAfterDays) || 0
|
|
433
|
+
// 在用的库永不进入清理候选:purge 只看年龄,一旦把活跃库算进去就是数据丢失。
|
|
434
|
+
if (days > 0 && !used && lib.archivedAt && (now - (Date.parse(lib.archivedAt) || now)) / 86_400_000 >= days) {
|
|
435
|
+
purgeCandidates.push(lib.id)
|
|
436
|
+
}
|
|
437
|
+
continue
|
|
438
|
+
}
|
|
439
|
+
if (!registry?.trustworthy) continue
|
|
440
|
+
if (!lib.scopeKey || lib.scopeKey === '__default__') continue
|
|
441
|
+
if (!registry.scopes.has(lib.scopeKey)) {
|
|
442
|
+
// 关键判据:不在工作区注册表 ≠ 没人用。IM 插件数据目录、profile 下的目录都不在
|
|
443
|
+
// 注册表里,却可能有会话正在高频读写(2026-11-21 报告:建成 176 秒被归档,之后
|
|
444
|
+
// 9 小时 172 条活动、6 次召回全成功,而 UI 里库已消失)。
|
|
445
|
+
if (used) {
|
|
446
|
+
skippedInUse.push(lib.id)
|
|
447
|
+
noteInUseSkip(lib.id, lib.scopeKey, log)
|
|
448
|
+
continue
|
|
449
|
+
}
|
|
450
|
+
archiveLibrary(lib.id, { by: 'sweep' })
|
|
451
|
+
inUseSkipNotified.delete(lib.id)
|
|
452
|
+
archived.push(lib.id)
|
|
453
|
+
log(`archived library ${lib.id}: workspace ${lib.scopeKey} is no longer registered in DSH`)
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return { archived, revived, purged, purgeCandidates, skippedInUse, registrySeen: Boolean(registry?.trustworthy) }
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export async function runCyclePasses(ctx, options = {}) {
|
|
460
|
+
const shortTerm = runShortTermPass(ctx, options)
|
|
461
|
+
const overdue = runOverdueReviewPass(ctx, options)
|
|
462
|
+
// turn-log GC 挂在 sweep 顺带跑(§3.4),只做 stat/绑定表级别的便宜检查。
|
|
463
|
+
const turnLogs = runTurnLogGcPass(ctx, options)
|
|
464
|
+
const maintenance = await runMaintenancePass(ctx, options)
|
|
465
|
+
const sleep = await runSleepPass(ctx, options)
|
|
466
|
+
const curate = await runCurationPass(ctx, options)
|
|
467
|
+
const libraries = runLibraryHousekeeping(ctx, options)
|
|
468
|
+
// A library can still be on disk in the removed `session` format when the plugin
|
|
469
|
+
// updated mid-flight. Reads are already normalized, so this only keeps the files in
|
|
470
|
+
// step with the code (see lib/migrate.js); it is cheap and idempotent.
|
|
471
|
+
const migrated = runVisibilityMigrationPass({ log: options.log })
|
|
472
|
+
// 日期唤醒放在最后:它使用可选的宿主 schedule 服务,宿主没有
|
|
473
|
+
// 这个服务时只返回 `{skipped:'service'}`;即使它整体失败,上面的短期过期、睡眠整理、
|
|
474
|
+
// 自动提炼和库迁移已经跑完,下一次 sweep 照常重试。
|
|
475
|
+
const salientWake = await runSalientWakePass(ctx, { now: options.now ?? new Date(), log: options.log }).catch((error) => {
|
|
476
|
+
try { options.log?.(`salient wake pass failed: ${error?.message || error}`) } catch {}
|
|
477
|
+
return { created: 0, cleaned: 0, skipped: 0, errors: 1 }
|
|
478
|
+
})
|
|
479
|
+
return { shortTerm, overdue, turnLogs, maintenance, sleep, curate, libraries, migrated, salientWake }
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// DSH has no host scheduler a plugin can register a *global* job with
|
|
483
|
+
// (`ctx.schedule` is session-bound and delivers a prompt into that session, which
|
|
484
|
+
// is the wrong shape for a plugin-wide sweep), so this owns a plain interval.
|
|
485
|
+
// Cordis' own `ctx.interval` is preferred because the host disposes it with the
|
|
486
|
+
// plugin scope; the raw fallback is unref'd so a plugin timer can never be the
|
|
487
|
+
// reason the app stays alive. Everything this reads is a persisted timestamp, so a
|
|
488
|
+
// missed sweep is recovered on the next one.
|
|
489
|
+
export function registerCycle(ctx, { log = () => {} } = {}) {
|
|
490
|
+
let running = false
|
|
491
|
+
const tick = async () => {
|
|
492
|
+
if (running) return
|
|
493
|
+
running = true
|
|
494
|
+
try {
|
|
495
|
+
await runCyclePasses(ctx, { log })
|
|
496
|
+
} catch (error) {
|
|
497
|
+
log(`cycle sweep failed: ${error?.message || error}`)
|
|
498
|
+
} finally {
|
|
499
|
+
running = false
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
// One catch-up sweep shortly after load. The sweep timer only exists while the app
|
|
503
|
+
// is open, so a conversation that ended while it was closed used to wait for the
|
|
504
|
+
// next idle window — and the next message always resets that clock, which is how a
|
|
505
|
+
// whole evening could pass without a single consolidation. The delay lets the host
|
|
506
|
+
// finish restoring sessions and agents first; the pass itself is bounded (two
|
|
507
|
+
// sessions) so a long list of stale bindings cannot turn startup into a stampede.
|
|
508
|
+
const startup = setTimeout(() => { void tick() }, STARTUP_SWEEP_MS)
|
|
509
|
+
startup.unref?.()
|
|
510
|
+
// Property access on an uninjected service throws in cordis, so the probe itself
|
|
511
|
+
// is guarded; a host without the timer service falls back instead of failing.
|
|
512
|
+
let scoped = null
|
|
513
|
+
try { scoped = typeof ctx.interval === 'function' ? ctx : null } catch { scoped = null }
|
|
514
|
+
if (scoped) {
|
|
515
|
+
// cordis' ctx.interval returns a *disposer function*, not a Node timer id —
|
|
516
|
+
// clearInterval() on it is a silent no-op and the sweep would keep running
|
|
517
|
+
// after plugin unload/HMR. Call the disposer.
|
|
518
|
+
const dispose = scoped.interval(() => { void tick() }, SWEEP_MS)
|
|
519
|
+
return () => { try { clearTimeout(startup) } catch {} try { dispose?.() } catch {} }
|
|
520
|
+
}
|
|
521
|
+
const timer = setInterval(() => { void tick() }, SWEEP_MS)
|
|
522
|
+
timer.unref?.()
|
|
523
|
+
return () => { clearTimeout(startup); clearInterval(timer) }
|
|
524
|
+
}
|