dsh-memu-memory 1.4.4 → 1.4.5
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 +3 -1
- package/CHANGELOG.md +11 -0
- package/README.md +33 -14
- package/README.zh.md +34 -12
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +30 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +93 -10
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
|
|
7
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-retention-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
process.env.DSH_MEMU_MEMORY_HOME = home
|
|
10
|
+
|
|
11
|
+
const state = await import('../lib/state.js')
|
|
12
|
+
const turnLog = await import('../lib/turn-log.js')
|
|
13
|
+
const retention = await import('../lib/retention.js')
|
|
14
|
+
const { pruneSessionBindings } = state
|
|
15
|
+
const consolidation = await import('../lib/consolidation-ledger.js')
|
|
16
|
+
const maintenance = await import('../lib/maintenance-ledger.js')
|
|
17
|
+
const cycle = await import('../lib/cycle.js')
|
|
18
|
+
const paths = await import('../lib/paths.js')
|
|
19
|
+
|
|
20
|
+
const DAY = 86_400_000
|
|
21
|
+
const NOW = Date.parse('2026-11-30T00:00:00.000Z')
|
|
22
|
+
const oldAt = new Date(NOW - 200 * DAY)
|
|
23
|
+
|
|
24
|
+
test.after(() => {
|
|
25
|
+
try { state.flushState() } catch {}
|
|
26
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
test.afterEach(() => {
|
|
30
|
+
for (const binding of state.listSessionBindings()) state.deleteSessionBinding(binding.sessionId)
|
|
31
|
+
try { fs.rmSync(path.join(home, 'sessions'), { recursive: true, force: true }) } catch {}
|
|
32
|
+
state.updateSettings({
|
|
33
|
+
retentionDryRun: true,
|
|
34
|
+
retentionBoundTurnLogsEnabled: true,
|
|
35
|
+
retentionBoundTurnLogDays: 30,
|
|
36
|
+
retentionOrphanTurnLogsEnabled: false,
|
|
37
|
+
retentionOrphanTurnLogDays: 90,
|
|
38
|
+
retentionMaintenanceLedgerEnabled: true,
|
|
39
|
+
retentionMaintenanceLedgerDays: 180,
|
|
40
|
+
retentionSessionBindingsEnabled: false,
|
|
41
|
+
retentionSessionBindingDays: 180,
|
|
42
|
+
retentionVectorPruneEnabled: true,
|
|
43
|
+
retentionVectorKeepGenerations: 2,
|
|
44
|
+
retentionVectorDays: 7,
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
function oldBinding(id, extra = {}) {
|
|
49
|
+
const binding = state.ensureSession(id, { cwd: path.join(home, `proj-${id}`), agentPreset: 'coding' })
|
|
50
|
+
return state.setSessionBinding(id, { lastTurnAt: oldAt.toISOString(), ...extra })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function oldTurnLog(id, seq = [0, 3]) {
|
|
54
|
+
turnLog.recordTurn(id, { seq, at: oldAt.toISOString(), user: 'old', model: 'turn' })
|
|
55
|
+
const file = turnLog.turnLogPath(id)
|
|
56
|
+
fs.utimesSync(file, oldAt, oldAt)
|
|
57
|
+
return file
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
test('settings defaults keep apply dry-run and require separate orphan/session opt-in', () => {
|
|
61
|
+
const settings = state.DEFAULT_SETTINGS
|
|
62
|
+
assert.equal(settings.retentionDryRun, true)
|
|
63
|
+
assert.equal(settings.retentionOrphanTurnLogsEnabled, false)
|
|
64
|
+
assert.equal(settings.retentionSessionBindingsEnabled, false)
|
|
65
|
+
assert.equal(settings.retentionOrphanTurnLogDays, 90)
|
|
66
|
+
assert.equal(settings.retentionBoundTurnLogDays, 30)
|
|
67
|
+
assert.equal(state.updateSettings({ retentionOrphanTurnLogDays: 0 }).retentionOrphanTurnLogDays, 1)
|
|
68
|
+
assert.throws(() => state.updateSettings({ retentionOrphanTurnLogsEnabled: 'yes' }), /boolean/)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('runRetentionPass is wired into cycle and remains non-destructive by default', async () => {
|
|
72
|
+
oldBinding('bound-dry-run', { lastSleepSeq: 10 })
|
|
73
|
+
const file = oldTurnLog('bound-dry-run')
|
|
74
|
+
const ctx = { get: () => ({ get: () => null }) }
|
|
75
|
+
const pass = retention.runRetentionPass(ctx, { now: NOW })
|
|
76
|
+
assert.equal(pass.dryRun, true)
|
|
77
|
+
assert.deepEqual(pass.boundTurnLogs.deleted, ['bound-dry-run'])
|
|
78
|
+
assert.ok(fs.existsSync(file), 'dry-run must not remove the turn log')
|
|
79
|
+
assert.equal(pass.orphanTurnLogs.skipped, 'explicit-opt-in-required')
|
|
80
|
+
|
|
81
|
+
const swept = await cycle.runCyclePasses(ctx, { now: NOW, log: () => {} })
|
|
82
|
+
assert.ok(swept.retention, 'cycle exposes the complete retention pass result')
|
|
83
|
+
assert.equal(swept.retention.dryRun, true)
|
|
84
|
+
assert.deepEqual(swept.turnLogs.deleted, ['bound-dry-run'])
|
|
85
|
+
assert.ok(fs.existsSync(file), 'cycle invocation must respect the same dry-run gate')
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test('turn logs are created mode 0600 and flushed; orphan deletion needs opt-in and age', () => {
|
|
89
|
+
const orphan = oldTurnLog('orphan-one')
|
|
90
|
+
const stat = fs.statSync(orphan)
|
|
91
|
+
if (process.platform !== 'win32') assert.equal(stat.mode & 0o777, 0o600)
|
|
92
|
+
|
|
93
|
+
let plan = turnLog.listOrphanTurnLogs([], { now: NOW, olderThanDays: 90 })
|
|
94
|
+
assert.deepEqual(plan.candidates.map(row => row.name), ['orphan-one.turnlog.jsonl'])
|
|
95
|
+
state.updateSettings({ retentionDryRun: false })
|
|
96
|
+
let pass = retention.runRetentionPass({ get: () => ({ get: () => null }) }, { now: NOW })
|
|
97
|
+
assert.equal(pass.orphanTurnLogs.skipped, 'explicit-opt-in-required')
|
|
98
|
+
assert.ok(fs.existsSync(orphan))
|
|
99
|
+
|
|
100
|
+
state.updateSettings({ retentionOrphanTurnLogsEnabled: true, retentionOrphanTurnLogDays: 90 })
|
|
101
|
+
pass = retention.runRetentionPass({ get: () => ({ get: () => null }) }, { now: NOW })
|
|
102
|
+
assert.deepEqual(pass.orphanTurnLogs.removed, ['orphan-one.turnlog.jsonl'])
|
|
103
|
+
assert.equal(fs.existsSync(orphan), false)
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
test('session-binding apply rechecks a changing lease veto under lock', () => {
|
|
107
|
+
oldBinding('lease-race')
|
|
108
|
+
let checks = 0
|
|
109
|
+
const result = pruneSessionBindings({
|
|
110
|
+
now: NOW, olderThanDays: 180, dryRun: false,
|
|
111
|
+
isBusy: () => (++checks >= 2),
|
|
112
|
+
})
|
|
113
|
+
assert.deepEqual(result.removed, [])
|
|
114
|
+
assert.deepEqual(result.revalidated, ['lease-race'])
|
|
115
|
+
assert.ok(state.getSessionBinding('lease-race'))
|
|
116
|
+
assert.equal(checks, 2)
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
test('session-binding cleanup refuses an active consolidation lease', () => {
|
|
120
|
+
const binding = oldBinding('lease-held')
|
|
121
|
+
const lease = consolidation.beginJob({
|
|
122
|
+
sessionId: 'lease-held', jobId: 'retention-test', snapshot: { throughSeq: 1 }, binding,
|
|
123
|
+
now: NOW - 1, leaseMs: DAY,
|
|
124
|
+
})
|
|
125
|
+
assert.equal(lease.ok, true)
|
|
126
|
+
state.updateSettings({ retentionDryRun: false, retentionSessionBindingsEnabled: true })
|
|
127
|
+
const pass = retention.runRetentionPass({ get: () => ({ get: () => null }) }, { now: NOW })
|
|
128
|
+
assert.deepEqual(pass.sessionBindings.removed, [])
|
|
129
|
+
assert.ok(pass.sessionBindings.skipped.some(item => /lease/.test(item.reason)))
|
|
130
|
+
assert.ok(state.getSessionBinding('lease-held'))
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
test('settled maintenance retention keeps pending/apply-intent records and never touches memory', () => {
|
|
134
|
+
const candidate = {
|
|
135
|
+
libraryId: 'library', memoryId: 'memory-id', reason: 'validity-ended',
|
|
136
|
+
entryRevision: 'rev1', sessionId: 'session',
|
|
137
|
+
}
|
|
138
|
+
maintenance.syncMaintenanceCandidates([candidate], { now: NOW - 200 * DAY, scannedLibraries: ['library'] })
|
|
139
|
+
maintenance.mutateMaintenanceLedger(ledger => {
|
|
140
|
+
const items = Object.values(ledger.items)
|
|
141
|
+
for (const item of items) {
|
|
142
|
+
item.state = 'settled'
|
|
143
|
+
item.createdAt = oldAt.toISOString()
|
|
144
|
+
item.settledAt = oldAt.toISOString()
|
|
145
|
+
item.lastCheckedAt = oldAt.toISOString()
|
|
146
|
+
item.applyIntent = null
|
|
147
|
+
}
|
|
148
|
+
ledger.items['apply-intent'] = {
|
|
149
|
+
...items[0], key: 'apply-intent', state: 'settled', applyIntent: { action: 'update' },
|
|
150
|
+
}
|
|
151
|
+
})
|
|
152
|
+
const preview = maintenance.pruneSettledMaintenanceItems({ now: NOW, olderThanDays: 180, dryRun: true })
|
|
153
|
+
assert.equal(preview.candidates.length, 1)
|
|
154
|
+
const applied = maintenance.pruneSettledMaintenanceItems({ now: NOW, olderThanDays: 180, dryRun: false })
|
|
155
|
+
assert.equal(applied.removed.length, 1)
|
|
156
|
+
assert.ok(maintenance.loadMaintenanceLedger().items['apply-intent'])
|
|
157
|
+
assert.ok(state.loadPrivateIndex('library').entries['memory-id'] === undefined, 'this pass has no memory-entry deletion path')
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
test('runRetentionPass exposes deleted-library counts and preserves the actual memory index', () => {
|
|
161
|
+
const library = state.createLibrary({ name: 'retention-memory', scopeKey: path.join(home, 'retention-memory') })
|
|
162
|
+
state.updatePrivateIndex(library.id, index => {
|
|
163
|
+
index.entries['retained-memory'] = { title: 'Retained fact', content: 'Retention never deletes this.', status: 'active' }
|
|
164
|
+
})
|
|
165
|
+
const indexFile = path.join(home, 'index', `${library.id}.json`)
|
|
166
|
+
const original = fs.readFileSync(indexFile, 'utf8')
|
|
167
|
+
maintenance.mutateMaintenanceLedger(ledger => {
|
|
168
|
+
ledger.items = Object.fromEntries([
|
|
169
|
+
['existing-metadata', library.id], ['deleted-metadata', 'deleted-library'],
|
|
170
|
+
].map(([key, libraryId]) => [key, {
|
|
171
|
+
key, libraryId, memoryId: 'retained-memory', state: 'settled', settledAt: oldAt.toISOString(),
|
|
172
|
+
}]))
|
|
173
|
+
ledger.libraries = { 'deleted-library': { lastCheckedAt: new Date(NOW).toISOString() } }
|
|
174
|
+
})
|
|
175
|
+
const dry = retention.runRetentionPass({}, { now: NOW })
|
|
176
|
+
assert.equal(dry.dryRun, true)
|
|
177
|
+
assert.deepEqual(dry.maintenanceLedger.orphanedCandidates, ['deleted-metadata'])
|
|
178
|
+
assert.equal(dry.maintenanceLedger.orphanedCandidateCount, 1)
|
|
179
|
+
assert.equal(dry.maintenanceLedger.removed.length, 0)
|
|
180
|
+
state.updateSettings({ retentionDryRun: false })
|
|
181
|
+
const applied = retention.runRetentionPass({}, { now: NOW })
|
|
182
|
+
assert.deepEqual(applied.errors, [])
|
|
183
|
+
assert.deepEqual(applied.maintenanceLedger.removed, ['existing-metadata', 'deleted-metadata'])
|
|
184
|
+
assert.equal(applied.maintenanceLedger.orphanedRemovedCount, 1)
|
|
185
|
+
assert.equal(fs.readFileSync(indexFile, 'utf8'), original)
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
test('a corrupt session registry between settings and binding reads never makes a bound turnlog orphaned', t => {
|
|
189
|
+
oldBinding('registry-read-protected')
|
|
190
|
+
const file = oldTurnLog('registry-read-protected')
|
|
191
|
+
state.updateSettings({ retentionDryRun: false, retentionBoundTurnLogsEnabled: false,
|
|
192
|
+
retentionOrphanTurnLogsEnabled: true, retentionOrphanTurnLogDays: 90,
|
|
193
|
+
retentionMaintenanceLedgerEnabled: false, retentionSessionBindingsEnabled: false, retentionVectorPruneEnabled: false })
|
|
194
|
+
state.flushState()
|
|
195
|
+
const stateFile = path.join(home, 'state.json')
|
|
196
|
+
const original = fs.readFileSync(stateFile)
|
|
197
|
+
state.clearCaches()
|
|
198
|
+
const stat = fs.statSync
|
|
199
|
+
let changed = false
|
|
200
|
+
const mock = t.mock.method(fs, 'statSync', (target, ...args) => {
|
|
201
|
+
const value = stat(target, ...args)
|
|
202
|
+
if (target === stateFile && !changed) {
|
|
203
|
+
changed = true
|
|
204
|
+
fs.writeFileSync(stateFile, '{truncated registry')
|
|
205
|
+
const later = new Date(Date.now() + 5000)
|
|
206
|
+
fs.utimesSync(stateFile, later, later)
|
|
207
|
+
}
|
|
208
|
+
return value
|
|
209
|
+
})
|
|
210
|
+
try {
|
|
211
|
+
const result = retention.runRetentionPass({}, { now: NOW })
|
|
212
|
+
assert.equal(changed, true)
|
|
213
|
+
assert.ok(paths.readFailure(stateFile))
|
|
214
|
+
assert.ok(result.errors.some(row => row.step === 'bindings-read'))
|
|
215
|
+
assert.ok(result.errors.some(row => row.step === 'orphan-turn-logs'))
|
|
216
|
+
assert.deepEqual(result.orphanTurnLogs.removed, [])
|
|
217
|
+
assert.ok(fs.existsSync(file))
|
|
218
|
+
} finally {
|
|
219
|
+
mock.mock.restore()
|
|
220
|
+
fs.writeFileSync(stateFile, original)
|
|
221
|
+
state.clearCaches()
|
|
222
|
+
state.loadState()
|
|
223
|
+
}
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
test('orphan apply rechecks registry read-failure state after planning and reports a skipped unlink', t => {
|
|
227
|
+
const file = oldTurnLog('orphan-read-race')
|
|
228
|
+
state.updateSettings({ retentionDryRun: false, retentionBoundTurnLogsEnabled: false,
|
|
229
|
+
retentionOrphanTurnLogsEnabled: true, retentionOrphanTurnLogDays: 90,
|
|
230
|
+
retentionMaintenanceLedgerEnabled: false, retentionSessionBindingsEnabled: false, retentionVectorPruneEnabled: false })
|
|
231
|
+
state.flushState()
|
|
232
|
+
const stateFile = path.join(home, 'state.json')
|
|
233
|
+
const original = fs.readFileSync(stateFile)
|
|
234
|
+
const stat = fs.lstatSync
|
|
235
|
+
let changed = false
|
|
236
|
+
const mock = t.mock.method(fs, 'lstatSync', (target, ...args) => {
|
|
237
|
+
const value = stat(target, ...args)
|
|
238
|
+
if (target === file && !changed) {
|
|
239
|
+
changed = true
|
|
240
|
+
fs.writeFileSync(stateFile, '{truncated after plan')
|
|
241
|
+
const later = new Date(Date.now() + 5000)
|
|
242
|
+
fs.utimesSync(stateFile, later, later)
|
|
243
|
+
}
|
|
244
|
+
return value
|
|
245
|
+
})
|
|
246
|
+
try {
|
|
247
|
+
const result = retention.runRetentionPass({}, { now: NOW })
|
|
248
|
+
assert.equal(changed, true)
|
|
249
|
+
assert.equal(result.orphanTurnLogs.candidates.length, 1)
|
|
250
|
+
assert.deepEqual(result.orphanTurnLogs.removed, [])
|
|
251
|
+
assert.ok(result.orphanTurnLogs.kept.some(row => row.name === path.basename(file) && /bindings-unreadable/.test(row.reason)))
|
|
252
|
+
assert.ok(result.errors.some(row => row.step === 'orphan-turn-logs'))
|
|
253
|
+
assert.ok(fs.existsSync(file))
|
|
254
|
+
} finally {
|
|
255
|
+
mock.mock.restore()
|
|
256
|
+
fs.writeFileSync(stateFile, original)
|
|
257
|
+
state.clearCaches()
|
|
258
|
+
state.loadState()
|
|
259
|
+
}
|
|
260
|
+
})
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
|
|
7
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dmm-rt-cross-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
process.env.DSH_MEMU_MEMORY_HOME = home
|
|
10
|
+
process.env.DSH_MEMU_RT_MIN_ENTRIES = '2'
|
|
11
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
12
|
+
const state = await import('../lib/state.js')
|
|
13
|
+
const paths = await import('../lib/paths.js')
|
|
14
|
+
const memory = await import('../lib/memory.js')
|
|
15
|
+
const service = await import('../lib/rt-index-service.js')
|
|
16
|
+
const { createQueryView, clearRtIndexCaches } = await import('../lib/rt-index/reader.js')
|
|
17
|
+
const { buildCorpus, bm25, tokenize } = await import('../lib/text-retrieval.js')
|
|
18
|
+
const warnings = []
|
|
19
|
+
paths.setWarnSink(text => warnings.push(text))
|
|
20
|
+
state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true, autoLinkMode: 'off', relevanceThreshold: 0 })
|
|
21
|
+
test.after(async () => {
|
|
22
|
+
await service.closeRtIndexService()
|
|
23
|
+
clearRtIndexCaches()
|
|
24
|
+
state.flushState()
|
|
25
|
+
fs.rmSync(home, { recursive: true, force: true })
|
|
26
|
+
})
|
|
27
|
+
let serial = 0
|
|
28
|
+
const entry = (content, extra = {}) => ({ title: '', content, status: 'active', layer: 'long_term', strength: 1,
|
|
29
|
+
visibility: 'shared', createdAt: new Date(Date.now() - 86400000).toISOString(), updatedAt: new Date().toISOString(), ...extra })
|
|
30
|
+
function world(primaryEntries, foreignEntries) {
|
|
31
|
+
const domain = `rt-cross-${++serial}`
|
|
32
|
+
const make = entries => {
|
|
33
|
+
const sessionId = `rt-cross-session-${++serial}`
|
|
34
|
+
const cwd = path.join(home, sessionId)
|
|
35
|
+
const binding = state.ensureSession(sessionId, { cwd })
|
|
36
|
+
state.setSessionBinding(sessionId, { domainOverride: domain, memoryContext: { characterId: 'alice' } })
|
|
37
|
+
state.savePrivateIndex(binding.libraryId, { version: 1, entries })
|
|
38
|
+
assert.equal(service.rebuildRt(binding.libraryId).ok, true)
|
|
39
|
+
return { sessionId, libraryId: binding.libraryId, exec: { agent: { session: { header: { id: sessionId, cwd } } } } }
|
|
40
|
+
}
|
|
41
|
+
const primary = make(primaryEntries)
|
|
42
|
+
const foreign = make(foreignEntries)
|
|
43
|
+
const recall = query => memory.privateRecall({ exec: primary.exec, query, topK: 20, purpose: 'automatic', relevanceThreshold: 0 })
|
|
44
|
+
return { primary, foreign, recall }
|
|
45
|
+
}
|
|
46
|
+
const projection = result => result.files.map(file => ({ libraryId: file.libraryId, id: file.name,
|
|
47
|
+
lexical: file.lexical, evidence: file.lexicalEvidence, retrievalScore: file.retrievalScore }))
|
|
48
|
+
|
|
49
|
+
test('queryPostings exposes exact integer lengths and filtered joint-corpus tf/df for same-id libraries', () => {
|
|
50
|
+
const indexes = [
|
|
51
|
+
{ entries: { 'mem-same': entry('pear pear'), 'mem-hidden': entry('pear '.repeat(1000), { visibility: 'secret' }) } },
|
|
52
|
+
{ entries: { 'mem-same': entry('pear apple peach'), 'mem-other': entry('apple') } },
|
|
53
|
+
]
|
|
54
|
+
const query = ['pear', 'apple']
|
|
55
|
+
const corpus = buildCorpus(indexes.flatMap((index, library) => Object.entries(index.entries)
|
|
56
|
+
.filter(([, row]) => row.visibility !== 'secret').map(([id, row]) => ({ id: JSON.stringify([library, id]), title: row.title, content: row.content }))))
|
|
57
|
+
const combined = { size: 0, avgdl: 0, df: new Map() }
|
|
58
|
+
const docs = new Map()
|
|
59
|
+
let totalLen = 0
|
|
60
|
+
for (let library = 0; library < indexes.length; library++) {
|
|
61
|
+
const view = createQueryView({ index: indexes[library], revision: `r${library}` }, { isVisible: row => row.visibility !== 'secret' })
|
|
62
|
+
const result = view.queryPostings(query)
|
|
63
|
+
assert.ok(Number.isSafeInteger(result.totalLen))
|
|
64
|
+
totalLen += result.totalLen
|
|
65
|
+
combined.size += result.corpus.size
|
|
66
|
+
for (const [term, n] of result.corpus.df) combined.df.set(term, (combined.df.get(term) || 0) + n)
|
|
67
|
+
for (const [id, doc] of result.docs) docs.set(JSON.stringify([library, id]), doc)
|
|
68
|
+
}
|
|
69
|
+
combined.avgdl = totalLen / combined.size
|
|
70
|
+
assert.equal(combined.avgdl, corpus.avgdl)
|
|
71
|
+
assert.deepEqual(combined.df, new Map(query.map(term => [term, corpus.df.get(term)])))
|
|
72
|
+
for (const [id, doc] of docs) assert.equal(bm25(query, doc, combined), bm25(query, corpus.docs.get(id), corpus))
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
test('actual cross-library recall uses unified statistics, same-id identity and final shadow parity', async () => {
|
|
76
|
+
const w = world({ 'mem-same': entry('orchard pear coastline telescope navigation moon stars observatory ocean wind'), 'mem-local': entry('pear apple'),
|
|
77
|
+
'mem-hidden': entry('orchard '.repeat(500), { visibility: 'secret' }) },
|
|
78
|
+
{ 'mem-same': entry('orchard orchard pear apple certificate protocol renewal proxy server deployment incident'), 'mem-other': entry('citrus garden'),
|
|
79
|
+
'mem-bob': entry('orchard '.repeat(500), { context: { characterId: 'bob' } }),
|
|
80
|
+
'mem-domain': entry('orchard '.repeat(500), { domain: 'outside-domain' }) })
|
|
81
|
+
const query = 'orchard pear apple'
|
|
82
|
+
process.env.DSH_MEMU_RT_INDEX = 'off'
|
|
83
|
+
const expected = await w.recall(query)
|
|
84
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
85
|
+
const actual = await w.recall(query)
|
|
86
|
+
assert.deepEqual(projection(actual), projection(expected))
|
|
87
|
+
assert.equal(actual.files.filter(file => file.name === 'mem-same').length, 2)
|
|
88
|
+
assert.ok(!actual.files.some(file => ['mem-hidden', 'mem-bob', 'mem-domain'].includes(file.name)))
|
|
89
|
+
const controllers = [w.primary, w.foreign].map(f => service.getRtQueryView({ index: state.readPrivateIndex(f.libraryId),
|
|
90
|
+
libraryId: f.libraryId, cacheKey: 'test-stats', isVisible: row => row.visibility !== 'secret' }).controller)
|
|
91
|
+
const comparisonsBefore = controllers.reduce((n, controller) => n + controller.diagnostics().shadowQueries, 0)
|
|
92
|
+
const serviceBefore = service.rtServiceDiagnostics()
|
|
93
|
+
process.env.DSH_MEMU_RT_INDEX = 'shadow'
|
|
94
|
+
assert.deepEqual(projection(await w.recall(query)), projection(expected))
|
|
95
|
+
assert.equal(controllers.reduce((n, controller) => n + controller.diagnostics().shadowQueries, 0), comparisonsBefore + 1)
|
|
96
|
+
assert.equal(controllers.reduce((n, controller) => n + controller.diagnostics().shadowMismatches, 0), 0)
|
|
97
|
+
assert.equal(service.rtServiceDiagnostics().shadowQueries, serviceBefore.shadowQueries + 1)
|
|
98
|
+
assert.equal(service.rtServiceDiagnostics().shadowMismatches, serviceBefore.shadowMismatches)
|
|
99
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
test('small or missing foreign derived indexes still contribute to the unified corpus', async () => {
|
|
103
|
+
for (const count of [1, 3]) {
|
|
104
|
+
const foreign = Object.fromEntries(Array.from({ length: count }, (_, i) => [`mem-foreign-${i}`, entry('orchard orchard citrus')]))
|
|
105
|
+
const w = world({ 'mem-local': entry('orchard apple'), 'mem-filler': entry('garden herbs') }, foreign)
|
|
106
|
+
process.env.DSH_MEMU_RT_INDEX = 'off'
|
|
107
|
+
const expected = await w.recall('orchard citrus')
|
|
108
|
+
if (count === 3) {
|
|
109
|
+
const root = service.indexLocation({ directory: service.rtDirectory(), libraryId: w.foreign.libraryId }).root
|
|
110
|
+
assert.ok(root.startsWith(path.resolve(home) + path.sep))
|
|
111
|
+
fs.rmSync(root, { recursive: true, force: true })
|
|
112
|
+
}
|
|
113
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
114
|
+
const actual = await w.recall('orchard citrus')
|
|
115
|
+
assert.deepEqual(projection(actual), projection(expected))
|
|
116
|
+
assert.ok(actual.files.some(file => file.libraryId === w.foreign.libraryId))
|
|
117
|
+
if (count === 3) assert.ok(actual.errors.some(error => error.includes('RT_MISSING')))
|
|
118
|
+
}
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
test('cached cross-library view corruption falls back on that query with the original ids and diagnostic', async () => {
|
|
122
|
+
const w = world({ 'mem-local': entry('orchard apple'), 'mem-filler': entry('garden herbs') },
|
|
123
|
+
{ 'mem-foreign': entry('citrus orchard'), 'mem-other': entry('pear peach') })
|
|
124
|
+
process.env.DSH_MEMU_RT_INDEX = 'off'
|
|
125
|
+
const expected = await w.recall('orchard')
|
|
126
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
127
|
+
await w.recall('orchard')
|
|
128
|
+
const root = service.indexLocation({ directory: service.rtDirectory(), libraryId: w.foreign.libraryId }).root
|
|
129
|
+
const pointer = JSON.parse(fs.readFileSync(path.join(root, 'current.json'), 'utf8'))
|
|
130
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(root, pointer.generation, 'manifest.json'), 'utf8'))
|
|
131
|
+
const file = path.join(root, 'segments', manifest.segments[0].id, 'postings.bin')
|
|
132
|
+
const bytes = fs.readFileSync(file)
|
|
133
|
+
bytes[bytes.length - 1] ^= 1
|
|
134
|
+
fs.writeFileSync(file, bytes)
|
|
135
|
+
const actual = await w.recall('orchard')
|
|
136
|
+
assert.deepEqual(projection(actual), projection(expected))
|
|
137
|
+
assert.ok(actual.errors.some(error => error.includes('RT_ARTIFACT_CHANGED')))
|
|
138
|
+
assert.match(state.getSessionBinding(w.primary.sessionId).lastRecallError, /RT_ARTIFACT_CHANGED/)
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
test('date-only candidates, tags and captions preserve cross-library boost and evidence parity', async () => {
|
|
142
|
+
const w = world({ 'mem-local': entry('certificate TLS expired'), 'mem-style': entry('请用自然简洁的语气回答') },
|
|
143
|
+
{ 'mem-date': entry('reserved telescope appointment', { absolute_date: '2026-12-04' }),
|
|
144
|
+
'mem-caption': entry('garden flowers', { tags: ['TLS'], attachments: [{ caption: 'certificate', kind: 'image' }] }) })
|
|
145
|
+
for (const query of ['certificate 2026-12-04', '请用自然简洁的语气回答。TLS 故障原因?']) {
|
|
146
|
+
process.env.DSH_MEMU_RT_INDEX = 'off'
|
|
147
|
+
const expected = await w.recall(query)
|
|
148
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
149
|
+
const actual = await w.recall(query)
|
|
150
|
+
assert.deepEqual(projection(actual), projection(expected))
|
|
151
|
+
assert.ok(actual.files.length)
|
|
152
|
+
if (query.includes('2026-12-04')) assert.ok(actual.files.some(file => file.name === 'mem-date'))
|
|
153
|
+
}
|
|
154
|
+
assert.ok(tokenize('TLS').length)
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
test('a shadow joint-score mismatch returns the oracle ids and reaches binding diagnostics', async () => {
|
|
158
|
+
const w = world({ 'mem-local': entry('orchard apple'), 'mem-filler': entry('garden herbs') },
|
|
159
|
+
{ 'mem-foreign': entry('citrus orchard'), 'mem-other': entry('pear peach') })
|
|
160
|
+
process.env.DSH_MEMU_RT_INDEX = 'off'
|
|
161
|
+
const expected = await w.recall('orchard')
|
|
162
|
+
process.env.DSH_MEMU_RT_INDEX = 'shadow'
|
|
163
|
+
// Reuse the exact permission view used by recall, then inject a derived-only
|
|
164
|
+
// missing posting. Source entries and the separate oracle view stay untouched.
|
|
165
|
+
const binding = state.getSessionBinding(w.primary.sessionId)
|
|
166
|
+
const gateKey = JSON.stringify([true, false, null, w.primary.sessionId,
|
|
167
|
+
binding.memoryContext ?? null, binding.sceneTime ?? null, binding.scopeKey ?? null,
|
|
168
|
+
binding.domainOverride ?? binding.domain ?? null])
|
|
169
|
+
const context = service.getRtQueryView({ index: state.readPrivateIndex(w.primary.libraryId),
|
|
170
|
+
libraryId: w.primary.libraryId, cacheKey: `cross:primary:${gateKey}`, isVisible: () => true })
|
|
171
|
+
const original = context.view.queryPostings
|
|
172
|
+
context.view.queryPostings = tokens => {
|
|
173
|
+
const data = original(tokens)
|
|
174
|
+
return { ...data, docs: new Map() }
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const before = service.rtServiceDiagnostics()
|
|
178
|
+
const actual = await w.recall('orchard')
|
|
179
|
+
assert.deepEqual(projection(actual), projection(expected))
|
|
180
|
+
assert.ok(actual.errors.some(error => error.includes('RT_SHADOW_MISMATCH')))
|
|
181
|
+
assert.match(state.getSessionBinding(w.primary.sessionId).lastRecallError, /RT_SHADOW_MISMATCH/)
|
|
182
|
+
assert.ok(context.controller.diagnostics().shadowMismatches > 0)
|
|
183
|
+
assert.equal(service.rtServiceDiagnostics().shadowQueries, before.shadowQueries + 1)
|
|
184
|
+
assert.equal(service.rtServiceDiagnostics().shadowMismatches, before.shadowMismatches + 1)
|
|
185
|
+
} finally {
|
|
186
|
+
context.view.queryPostings = original
|
|
187
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
188
|
+
}
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
test('evidence-only shadow differences retain source scores and reach binding diagnostics', async () => {
|
|
192
|
+
const w = world({ 'mem-local': entry('TLS certificate expired'), 'mem-style': entry('请用自然简洁的语气回答。') },
|
|
193
|
+
{ 'mem-foreign': entry('TLS proxy renewed'), 'mem-other': entry('piano garden') })
|
|
194
|
+
const query = '请用自然简洁的语气回答。TLS 故障原因?'
|
|
195
|
+
process.env.DSH_MEMU_RT_INDEX = 'off'
|
|
196
|
+
const expected = await w.recall(query)
|
|
197
|
+
assert.ok(expected.files.some(file => file.lexicalEvidence > 0))
|
|
198
|
+
process.env.DSH_MEMU_RT_INDEX = 'shadow'
|
|
199
|
+
const binding = state.getSessionBinding(w.primary.sessionId)
|
|
200
|
+
const gateKey = JSON.stringify([true, false, null, w.primary.sessionId,
|
|
201
|
+
binding.memoryContext ?? null, binding.sceneTime ?? null, binding.scopeKey ?? null,
|
|
202
|
+
binding.domainOverride ?? binding.domain ?? null])
|
|
203
|
+
const context = service.getRtQueryView({ index: state.readPrivateIndex(w.primary.libraryId),
|
|
204
|
+
libraryId: w.primary.libraryId, cacheKey: `cross:primary:${gateKey}`, isVisible: () => true })
|
|
205
|
+
const original = context.view.queryPostings
|
|
206
|
+
context.view.queryPostings = tokens => {
|
|
207
|
+
const data = original(tokens)
|
|
208
|
+
const fullQueryTerms = tokenize(query).filter(term => data.corpus.df.has(term)).length
|
|
209
|
+
const docs = new Map([...data.docs].map(([id, doc]) => {
|
|
210
|
+
let reads = 0
|
|
211
|
+
// The first BM25 call sees the original tf values. Only the subsequent
|
|
212
|
+
// topical-evidence call is faulty; final lexical scores/order stay equal.
|
|
213
|
+
return [id, { ...doc, tf: { get: term => reads++ < fullQueryTerms ? doc.tf.get(term) : 0 } }]
|
|
214
|
+
}))
|
|
215
|
+
return { ...data, docs }
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
const before = context.controller.diagnostics()
|
|
219
|
+
const serviceBefore = service.rtServiceDiagnostics()
|
|
220
|
+
const actual = await w.recall(query)
|
|
221
|
+
assert.deepEqual(projection(actual), projection(expected))
|
|
222
|
+
assert.equal(context.controller.diagnostics().shadowMismatches, before.shadowMismatches, 'score/order comparison alone cannot detect this evidence-only fault')
|
|
223
|
+
assert.ok(actual.errors.some(error => error.includes('RT_SHADOW_MISMATCH')))
|
|
224
|
+
assert.match(state.getSessionBinding(w.primary.sessionId).lastRecallError, /RT_SHADOW_MISMATCH/)
|
|
225
|
+
assert.equal(service.rtServiceDiagnostics().shadowQueries, serviceBefore.shadowQueries + 1)
|
|
226
|
+
} finally {
|
|
227
|
+
context.view.queryPostings = original
|
|
228
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
229
|
+
}
|
|
230
|
+
})
|