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.
Files changed (180) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +33 -14
  4. package/README.zh.md +34 -12
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/private.js +47 -21
  63. package/lib/recall-cache.js +20 -34
  64. package/lib/retention.js +173 -0
  65. package/lib/rpc.js +135 -52
  66. package/lib/rt-index/builder.js +209 -0
  67. package/lib/rt-index/format.js +231 -0
  68. package/lib/rt-index/manifest.js +105 -0
  69. package/lib/rt-index/reader.js +673 -0
  70. package/lib/rt-index-retention.js +151 -0
  71. package/lib/rt-index-service.js +283 -0
  72. package/lib/rt-index-worker.js +21 -0
  73. package/lib/salient-wake.js +55 -4
  74. package/lib/state.js +195 -24
  75. package/lib/temporal.js +39 -13
  76. package/lib/token-measurement.js +126 -0
  77. package/lib/tools.js +101 -6
  78. package/lib/turn-log.js +108 -3
  79. package/lib/webui/graph-layout-worker.js +68 -0
  80. package/lib/webui/graph-local-physics.js +390 -0
  81. package/lib/webui/graph-spatial-grid.js +64 -0
  82. package/lib/webui/graph-view.bundle.js +6 -1
  83. package/lib/webui/graph-view.js +478 -135
  84. package/lib/webui/graph-webgl-renderer.js +74 -0
  85. package/lib/webui/standalone.js +1 -1
  86. package/lib/worker-pool.js +30 -4
  87. package/package.json +3 -2
  88. package/scripts/acceptance-local.mjs +4 -10
  89. package/scripts/bench-all-libraries.mjs +47 -0
  90. package/scripts/check-classic-graph-browser.mjs +189 -0
  91. package/scripts/check-client-browser.mjs +929 -0
  92. package/scripts/check-graph-browser.mjs +6 -0
  93. package/scripts/check-graph-elastic-browser.mjs +139 -0
  94. package/scripts/check-memory-review-browser.mjs +124 -0
  95. package/scripts/entity-dedupe.mjs +19 -3
  96. package/scripts/graph-artifact-provenance.mjs +30 -0
  97. package/scripts/graph-freeze-manifest.mjs +129 -0
  98. package/scripts/graph-geometry-fixture.mjs +40 -0
  99. package/scripts/graph-physics-bench.mjs +218 -0
  100. package/scripts/graph-scale-bench.mjs +213 -0
  101. package/scripts/graph-scale-memory.mjs +48 -0
  102. package/scripts/graph-service-bench.mjs +72 -0
  103. package/scripts/make-readme-shots.mjs +17 -5
  104. package/scripts/preview.mjs +1 -0
  105. package/scripts/rebuild-rt.mjs +18 -0
  106. package/scripts/scale-bench.mjs +183 -0
  107. package/scripts/simulate-injection.mjs +47 -8
  108. package/scripts/verify-host-fixtures.mjs +108 -0
  109. package/scripts/verify-host-recovery.mjs +565 -0
  110. package/scripts/verify-vector-recovery.mjs +740 -0
  111. package/tests/auto-link-candidates.test.mjs +20 -0
  112. package/tests/browser.test.mjs +16 -2
  113. package/tests/client-export.test.mjs +16 -1
  114. package/tests/client-pagination.test.mjs +1495 -0
  115. package/tests/client-render.test.mjs +223 -28
  116. package/tests/consolidation-fork.test.mjs +93 -10
  117. package/tests/consolidation-ledger.test.mjs +17 -1
  118. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  119. package/tests/diagnostic-report.test.mjs +429 -0
  120. package/tests/diagnostic-wiring.test.mjs +88 -0
  121. package/tests/diagnostics.test.mjs +27 -0
  122. package/tests/embedding-download.test.mjs +44 -0
  123. package/tests/engine-source-settings.test.mjs +69 -0
  124. package/tests/engine-sources.test.mjs +145 -0
  125. package/tests/entity-dedupe.test.mjs +143 -0
  126. package/tests/entity-merge-review.test.mjs +363 -0
  127. package/tests/entity-merge.test.mjs +12 -4
  128. package/tests/entity-review.test.mjs +87 -0
  129. package/tests/environment-check.test.mjs +51 -1
  130. package/tests/feedback.test.mjs +95 -0
  131. package/tests/graph-adjacency-index.test.mjs +536 -0
  132. package/tests/graph-cascade.test.mjs +229 -0
  133. package/tests/graph-import-diagnostic.test.mjs +25 -0
  134. package/tests/graph-overview.test.mjs +709 -0
  135. package/tests/graph-session-authorization.test.mjs +419 -0
  136. package/tests/graph-view-geometry.test.mjs +426 -0
  137. package/tests/graph-view-scale.test.mjs +88 -0
  138. package/tests/graph-view.test.mjs +444 -5
  139. package/tests/graph.test.mjs +43 -0
  140. package/tests/help-page.test.mjs +128 -54
  141. package/tests/inbound.test.mjs +19 -0
  142. package/tests/index-pagination.test.mjs +113 -0
  143. package/tests/index-read-view.test.mjs +212 -0
  144. package/tests/inject-guide.test.mjs +9 -0
  145. package/tests/injection-dedupe.test.mjs +213 -0
  146. package/tests/lexicon-recall.test.mjs +641 -0
  147. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  148. package/tests/lexicon-rt.test.mjs +468 -0
  149. package/tests/local-embedding-worker.test.mjs +38 -0
  150. package/tests/local-vector-service.test.mjs +32 -3
  151. package/tests/maintenance-compat.test.mjs +128 -0
  152. package/tests/maintenance-settlement.test.mjs +1003 -0
  153. package/tests/managed-memory.test.mjs +39 -11
  154. package/tests/managed-runtime.test.mjs +109 -0
  155. package/tests/memory-fields.test.mjs +24 -12
  156. package/tests/observed-evidence.test.mjs +52 -0
  157. package/tests/port-surface.test.mjs +93 -1
  158. package/tests/recall-cache.test.mjs +56 -3
  159. package/tests/recall-dedup.test.mjs +63 -2
  160. package/tests/retention.test.mjs +260 -0
  161. package/tests/rt-index-cross-library.test.mjs +230 -0
  162. package/tests/rt-index-integration.test.mjs +194 -0
  163. package/tests/rt-index-retention.test.mjs +552 -0
  164. package/tests/rt-index-scale.test.mjs +204 -0
  165. package/tests/rt-index.test.mjs +705 -0
  166. package/tests/salient-date-boundaries.test.mjs +121 -0
  167. package/tests/salient-wake.test.mjs +29 -0
  168. package/tests/scale-bench.test.mjs +53 -0
  169. package/tests/settings-plumbing.test.mjs +25 -0
  170. package/tests/simulate-injection.test.mjs +15 -1
  171. package/tests/standalone-navigation.test.mjs +44 -0
  172. package/tests/state.test.mjs +51 -0
  173. package/tests/temporal-precision.test.mjs +102 -0
  174. package/tests/temporal.test.mjs +10 -6
  175. package/tests/token-measurement.test.mjs +98 -0
  176. package/tests/tool-schema.test.mjs +41 -5
  177. package/tests/tools.test.mjs +6 -3
  178. package/tests/turn-token-budget.test.mjs +149 -0
  179. package/tests/webui-auth.test.mjs +57 -1
  180. package/tests/webui.test.mjs +40 -15
@@ -0,0 +1,552 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import os from 'node:os'
6
+ import crypto from 'node:crypto'
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-rt-retention-'))
9
+ process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
11
+ const state = await import('../lib/state.js')
12
+ const { createRtIndex, indexLocation } = await import('../lib/rt-index/reader.js')
13
+ const { pruneRtArtifacts } = await import('../lib/rt-index-retention.js')
14
+ const { createLexiconRtSource, lexiconDocumentText, LEXICON_DOCUMENT_VERSION } = await import('../lib/lexicon-rt-source.js')
15
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
16
+ test.afterEach(() => fs.rmSync(path.join(home, 'rt'), { recursive: true, force: true }))
17
+
18
+ const DAY = 86400000
19
+ const NOW = Date.now()
20
+ const OLD = new Date(NOW - 30 * DAY)
21
+ let nextFixture = 0
22
+
23
+ function fixture({ global = false } = {}) {
24
+ const scopeKey = path.join(home, `fixture-${++nextFixture}`)
25
+ const library = global ? null : state.createLibrary({ name: 'rt retention fixture', scopeKey })
26
+ const libraryId = library?.id ?? null
27
+ const index = { version: 1, entries: { 'mem-kept': { title: 'violet', content: 'violet quartz' } } }
28
+ if (library) state.savePrivateIndex(libraryId, index)
29
+ const source = { index, revision: 'retention-fixture' }
30
+ const directory = path.join(home, 'rt')
31
+ const controller = createRtIndex({ directory, libraryId, mode: 'on' })
32
+ assert.equal(controller.rebuild(source).ok, true)
33
+ const { root, identity } = indexLocation({ directory, libraryId })
34
+ const pointer = path.join(root, 'current.json')
35
+ const truth = library ? path.join(home, 'index', `${libraryId}.json`) : null
36
+ return { scopeKey, libraryId, index, source, controller, root, identity, pointer, truth }
37
+ }
38
+
39
+ function lexiconFixture(libraryId, { truth = true } = {}) {
40
+ const options = { directory: path.join(home, 'rt'), libraryId, namespace: 'lexicon', mode: 'on',
41
+ documentVersion: LEXICON_DOCUMENT_VERSION, documentText: lexiconDocumentText }
42
+ const terms = { 'lex-kept': { term: 'violet', meaning: 'quartz' } }
43
+ const source = createLexiconRtSource({ terms })
44
+ const controller = createRtIndex(options)
45
+ assert.equal(controller.rebuild(source).ok, true)
46
+ assert.equal(controller.rebuild(source).ok, true)
47
+ const location = indexLocation(options)
48
+ const file = path.join(home, 'lexicon', `${libraryId}.json`)
49
+ if (truth) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify({ terms })) }
50
+ return { ...location, source, controller, pointer: path.join(location.root, 'current.json'), truth: file }
51
+ }
52
+
53
+ function ageTree(file, at = OLD) {
54
+ const stat = fs.lstatSync(file)
55
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
56
+ for (const name of fs.readdirSync(file)) ageTree(path.join(file, name), at)
57
+ }
58
+ if (!stat.isSymbolicLink()) fs.utimesSync(file, at, at)
59
+ }
60
+
61
+ function deleteLibrary(item) {
62
+ assert.equal(state.archiveLibrary(item.libraryId), true)
63
+ assert.equal(state.deleteLibrary(item.libraryId).ok, true)
64
+ assert.equal(fs.existsSync(item.truth), false)
65
+ }
66
+
67
+ function rowsFor(rows, item) {
68
+ return rows.filter(row => row.identity === item.identity)
69
+ }
70
+
71
+ function rewriteManifest(item, change) {
72
+ const pointer = JSON.parse(fs.readFileSync(item.pointer, 'utf8'))
73
+ const file = path.join(item.root, pointer.generation, 'manifest.json')
74
+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8'))
75
+ change(manifest)
76
+ const bytes = JSON.stringify(manifest)
77
+ fs.writeFileSync(file, bytes)
78
+ pointer.sha256 = crypto.createHash('sha256').update(bytes).digest('hex')
79
+ fs.writeFileSync(item.pointer, JSON.stringify(pointer))
80
+ }
81
+
82
+ test('retention previews and removes old unreferenced artifacts while preserving current recall', () => {
83
+ const library = state.createLibrary({ name: 'retention', cwd: path.join(home, 'workspace') })
84
+ state.savePrivateIndex(library.id, { version: 1, entries: { 'mem-kept': { title: 'violet', content: 'violet quartz' } } })
85
+ const directory = path.join(home, 'rt')
86
+ const index = state.readPrivateIndex(library.id)
87
+ const source = { index, revision: state.indexDataRevision(index) }
88
+ const controller = createRtIndex({ directory, libraryId: library.id, mode: 'on' })
89
+ assert.equal(controller.rebuild(source).ok, true)
90
+ const first = controller.listArtifacts()
91
+ assert.equal(controller.rebuild(source).ok, true)
92
+ const old = new Date(Date.now() - 30 * 86400000)
93
+ for (const artifact of first.artifacts) fs.utimesSync(artifact.path, old, old)
94
+ const preview = pruneRtArtifacts()
95
+ assert.equal(preview.candidates.length, 2)
96
+ assert.equal(preview.removed.length, 0)
97
+ const applied = pruneRtArtifacts({ dryRun: false })
98
+ assert.equal(applied.removed.length, 2)
99
+ assert.deepEqual(controller.search(source, 'violet', { visibleIds: ['mem-kept'] }).hits.map(hit => hit.id), ['mem-kept'])
100
+ assert.ok(fs.existsSync(path.join(home, 'index', `${library.id}.json`)))
101
+ const root = indexLocation({ directory, libraryId: library.id }).root
102
+ fs.writeFileSync(path.join(root, 'current.json'), '{}')
103
+ assert.ok(pruneRtArtifacts({ dryRun: false }).kept.some(item => item.reason === 'references-unreadable'))
104
+ })
105
+
106
+ test('deleted-library current artifacts and pointer have identical preview/apply plans and release the lock before rmdir', t => {
107
+ const item = fixture()
108
+ deleteLibrary(item)
109
+ ageTree(item.root)
110
+ const preview = pruneRtArtifacts({ now: NOW })
111
+ assert.deepEqual(rowsFor(preview.candidates, item).map(row => row.kind).sort(), ['generation', 'pointer', 'segment'])
112
+ assert.deepEqual(preview.removed, [])
113
+ assert.ok(fs.existsSync(item.pointer))
114
+ const lock = `${item.pointer}.lock`
115
+ const remove = fs.rmSync
116
+ const rmdir = fs.rmdirSync
117
+ let checkedRootRemoval = false
118
+ t.mock.method(fs, 'rmSync', (file, ...args) => {
119
+ const target = path.resolve(file)
120
+ assert.notEqual(target, item.root, 'the publication lock root is never removed recursively')
121
+ assert.ok(fs.existsSync(lock), 'artifact deletion holds the publication lock')
122
+ return remove(file, ...args)
123
+ })
124
+ t.mock.method(fs, 'rmdirSync', (file, ...args) => {
125
+ if (path.resolve(file) === item.root) {
126
+ checkedRootRemoval = true
127
+ assert.equal(fs.existsSync(lock), false)
128
+ assert.equal(args[0]?.recursive, undefined)
129
+ }
130
+ return rmdir(file, ...args)
131
+ })
132
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
133
+ assert.deepEqual(applied.candidates, preview.candidates)
134
+ assert.deepEqual(applied.removed, preview.candidates)
135
+ assert.equal(checkedRootRemoval, true)
136
+ assert.equal(fs.existsSync(item.root), false)
137
+ t.mock.restoreAll()
138
+ })
139
+
140
+ test('archived registry entries keep published artifacts even when their truth file is missing', () => {
141
+ const item = fixture()
142
+ assert.equal(state.archiveLibrary(item.libraryId), true)
143
+ fs.unlinkSync(item.truth)
144
+ ageTree(item.root)
145
+ const preview = pruneRtArtifacts({ now: NOW })
146
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
147
+ assert.deepEqual(preview.candidates, [])
148
+ assert.deepEqual(applied.candidates, [])
149
+ assert.deepEqual(applied.removed, [])
150
+ assert.ok(fs.existsSync(item.pointer))
151
+ assert.ok(state.listLibrariesAll().some(row => row.id === item.libraryId && row.archived))
152
+ })
153
+
154
+ test('unregistered libraries with truth present and the global namespace are never orphans', () => {
155
+ const item = fixture()
156
+ deleteLibrary(item)
157
+ fs.writeFileSync(item.truth, JSON.stringify(item.index))
158
+ const global = fixture({ global: true })
159
+ ageTree(item.root)
160
+ ageTree(global.root)
161
+ const truthBefore = fs.readFileSync(item.truth)
162
+ for (const dryRun of [true, false]) {
163
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
164
+ assert.deepEqual(result.candidates, [])
165
+ assert.ok(result.kept.some(row => row.identity === item.identity && row.reason === 'unregistered-truth-present'))
166
+ assert.ok(fs.existsSync(global.pointer))
167
+ assert.deepEqual(fs.readFileSync(item.truth), truthBefore)
168
+ }
169
+ })
170
+
171
+ test('orphan current retirement waits for every referenced artifact and pointer to expire, including the exact cutoff', async t => {
172
+ for (const fresh of ['pointer', 'generation', 'segment', 'cutoff']) await t.test(fresh, () => {
173
+ const item = fixture()
174
+ deleteLibrary(item)
175
+ ageTree(item.root)
176
+ const target = fresh === 'pointer' || fresh === 'cutoff' ? item.pointer
177
+ : item.controller.listArtifacts().artifacts.find(row => row.kind === fresh).path
178
+ const at = new Date(fresh === 'cutoff' ? NOW - 7 * DAY : NOW - DAY)
179
+ fs.utimesSync(target, at, at)
180
+ const preview = pruneRtArtifacts({ now: NOW })
181
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
182
+ assert.deepEqual(rowsFor(preview.candidates, item), [])
183
+ assert.deepEqual(rowsFor(applied.candidates, item), [])
184
+ assert.ok(fs.existsSync(item.pointer))
185
+ })
186
+ })
187
+
188
+ test('orphan cleanup can retire old unused artifacts while a newer published generation remains protected', () => {
189
+ const item = fixture()
190
+ const first = item.controller.listArtifacts()
191
+ assert.equal(item.controller.rebuild(item.source).ok, true)
192
+ for (const row of first.artifacts) ageTree(row.path)
193
+ deleteLibrary(item)
194
+ const preview = pruneRtArtifacts({ now: NOW })
195
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
196
+ assert.equal(preview.candidates.length, 2)
197
+ assert.deepEqual(applied.candidates, preview.candidates)
198
+ assert.deepEqual(applied.removed, preview.candidates)
199
+ assert.ok(fs.existsSync(item.pointer))
200
+ assert.equal(item.controller.listArtifacts().state, 'ready')
201
+ })
202
+
203
+ test('newer unreferenced artifacts keep the orphan ownership pointer available for a later pass', () => {
204
+ const item = fixture()
205
+ deleteLibrary(item)
206
+ ageTree(item.root)
207
+ const newer = path.join(item.root, `g-${crypto.randomUUID()}`)
208
+ fs.mkdirSync(newer)
209
+ fs.writeFileSync(path.join(newer, 'manifest.json'), '{}')
210
+ const preview = pruneRtArtifacts({ now: NOW })
211
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
212
+ assert.deepEqual(preview.candidates, [])
213
+ assert.deepEqual(applied.candidates, [])
214
+ assert.ok(fs.existsSync(item.pointer))
215
+ ageTree(newer)
216
+ const laterPreview = pruneRtArtifacts({ now: NOW })
217
+ const later = pruneRtArtifacts({ now: NOW, dryRun: false })
218
+ assert.equal(laterPreview.candidates.length, 4)
219
+ assert.deepEqual(later.removed, laterPreview.candidates)
220
+ assert.equal(fs.existsSync(item.root), false)
221
+ })
222
+
223
+ test('malformed, traversing and checksum-invalid pointers never authorize orphan cleanup', async t => {
224
+ const corruptions = [
225
+ ['malformed', () => '{'],
226
+ ['empty', () => '{}'],
227
+ ['traversal', pointer => JSON.stringify({ ...pointer, generation: '../outside' })],
228
+ ['checksum', pointer => JSON.stringify({ ...pointer, sha256: '0'.repeat(64) })],
229
+ ]
230
+ for (const [name, corrupt] of corruptions) await t.test(name, () => {
231
+ const item = fixture()
232
+ deleteLibrary(item)
233
+ const pointer = JSON.parse(fs.readFileSync(item.pointer, 'utf8'))
234
+ fs.writeFileSync(item.pointer, corrupt(pointer))
235
+ ageTree(item.root)
236
+ for (const dryRun of [true, false]) {
237
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
238
+ assert.deepEqual(rowsFor(result.candidates, item), [])
239
+ assert.ok(rowsFor(result.kept, item).length)
240
+ assert.ok(fs.existsSync(item.pointer))
241
+ }
242
+ })
243
+ })
244
+
245
+ test('unknown, legacy and corrupt manifest identities are retained even with a matching pointer checksum', async t => {
246
+ const corruptions = [
247
+ ['namespace', manifest => { manifest.namespace = 'other' }],
248
+ ['missing-owner', manifest => { delete manifest.libraryId }],
249
+ ['owner-mismatch', manifest => { manifest.libraryId = 'different-library' }],
250
+ ['identity', manifest => { manifest.identity = '0'.repeat(64) }],
251
+ ['manifest-version', manifest => { manifest.version = -1 }],
252
+ ['unsafe-owner', manifest => { manifest.libraryId = '../truth' }],
253
+ ]
254
+ for (const [name, corrupt] of corruptions) await t.test(name, () => {
255
+ const item = fixture()
256
+ deleteLibrary(item)
257
+ rewriteManifest(item, corrupt)
258
+ ageTree(item.root)
259
+ const result = pruneRtArtifacts({ now: NOW, dryRun: false })
260
+ assert.deepEqual(rowsFor(result.candidates, item), [])
261
+ assert.deepEqual(rowsFor(result.removed, item), [])
262
+ assert.ok(rowsFor(result.kept, item).length)
263
+ assert.ok(fs.existsSync(item.pointer))
264
+ })
265
+ })
266
+
267
+ test('registry restoration including archive is rechecked after acquiring the publication lock', t => {
268
+ const item = fixture()
269
+ deleteLibrary(item)
270
+ ageTree(item.root)
271
+ const open = fs.openSync
272
+ let restored = false
273
+ t.mock.method(fs, 'openSync', (file, ...args) => {
274
+ const fd = open(file, ...args)
275
+ if (file === `${item.pointer}.lock` && !restored) {
276
+ restored = true
277
+ assert.equal(state.createLibrary({ name: 'restored', scopeKey: item.scopeKey }).id, item.libraryId)
278
+ state.archiveLibrary(item.libraryId)
279
+ }
280
+ return fd
281
+ })
282
+ const result = pruneRtArtifacts({ now: NOW, dryRun: false })
283
+ assert.equal(restored, true)
284
+ assert.deepEqual(rowsFor(result.candidates, item), [])
285
+ assert.ok(fs.existsSync(item.pointer))
286
+ })
287
+
288
+ test('truth restoration is rechecked after acquiring the publication lock', t => {
289
+ const item = fixture()
290
+ deleteLibrary(item)
291
+ ageTree(item.root)
292
+ const open = fs.openSync
293
+ let restored = false
294
+ t.mock.method(fs, 'openSync', (file, ...args) => {
295
+ const fd = open(file, ...args)
296
+ if (file === `${item.pointer}.lock` && !restored) {
297
+ restored = true
298
+ fs.writeFileSync(item.truth, JSON.stringify(item.index))
299
+ }
300
+ return fd
301
+ })
302
+ const result = pruneRtArtifacts({ now: NOW, dryRun: false })
303
+ assert.equal(restored, true)
304
+ assert.deepEqual(rowsFor(result.candidates, item), [])
305
+ assert.ok(fs.existsSync(item.pointer))
306
+ assert.deepEqual(JSON.parse(fs.readFileSync(item.truth, 'utf8')), item.index)
307
+ })
308
+
309
+ test('directory symlinks at the rt root, identity, generation, segment or nested artifact are never followed', async t => {
310
+ for (const kind of ['rt', 'identity', 'generation', 'segments', 'segment', 'nested']) await t.test(kind, () => {
311
+ const item = fixture()
312
+ deleteLibrary(item)
313
+ ageTree(item.root)
314
+ const outside = fs.mkdtempSync(path.join(home, 'link-target-'))
315
+ const sentinel = path.join(outside, 'source-truth.json')
316
+ fs.writeFileSync(sentinel, 'must survive')
317
+ const inventory = item.controller.listArtifacts()
318
+ const segment = inventory.artifacts.find(row => row.kind === 'segment').path
319
+ const target = kind === 'rt' ? path.join(home, 'rt') : kind === 'identity' ? item.root
320
+ : kind === 'generation' ? inventory.artifacts.find(row => row.kind === 'generation').path
321
+ : kind === 'segments' ? path.join(item.root, 'segments') : kind === 'segment' ? segment : path.join(segment, 'external')
322
+ if (kind !== 'nested') fs.rmSync(target, { recursive: true, force: true })
323
+ fs.symlinkSync(outside, target, 'junction')
324
+ for (const dryRun of [true, false]) {
325
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
326
+ assert.deepEqual(rowsFor(result.candidates, item), [])
327
+ assert.deepEqual(rowsFor(result.removed, item), [])
328
+ assert.equal(fs.readFileSync(sentinel, 'utf8'), 'must survive')
329
+ assert.ok(fs.lstatSync(target).isSymbolicLink())
330
+ }
331
+ fs.unlinkSync(target)
332
+ })
333
+ })
334
+
335
+ test('pointer file symlinks are retained without touching the target', t => {
336
+ const item = fixture()
337
+ deleteLibrary(item)
338
+ const outside = path.join(home, 'external-pointer.json')
339
+ fs.copyFileSync(item.pointer, outside)
340
+ fs.unlinkSync(item.pointer)
341
+ try { fs.symlinkSync(outside, item.pointer, 'file') } catch (error) {
342
+ if (['EPERM', 'EACCES'].includes(error.code)) { t.skip('file symlinks require Windows developer mode or symlink privilege'); return }
343
+ throw error
344
+ }
345
+ ageTree(item.root)
346
+ const before = fs.readFileSync(outside)
347
+ for (const dryRun of [true, false]) {
348
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
349
+ assert.deepEqual(rowsFor(result.candidates, item), [])
350
+ assert.deepEqual(fs.readFileSync(outside), before)
351
+ assert.ok(fs.lstatSync(item.pointer).isSymbolicLink())
352
+ }
353
+ })
354
+
355
+ test('publication lock symlinks are left alone instead of being broken as stale locks', () => {
356
+ const item = fixture()
357
+ deleteLibrary(item)
358
+ ageTree(item.root)
359
+ const outside = fs.mkdtempSync(path.join(home, 'lock-target-'))
360
+ const lock = `${item.pointer}.lock`
361
+ fs.symlinkSync(outside, lock, 'junction')
362
+ for (const dryRun of [true, false]) {
363
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
364
+ assert.deepEqual(rowsFor(result.candidates, item), [])
365
+ assert.ok(result.kept.some(row => row.identity === item.identity && row.reason === 'unsafe-publication-lock'))
366
+ assert.ok(fs.lstatSync(lock).isSymbolicLink())
367
+ assert.ok(fs.existsSync(item.pointer))
368
+ }
369
+ })
370
+
371
+ test('a missing referenced segment retains the entire orphan instead of leaving a broken pointer', () => {
372
+ const item = fixture()
373
+ deleteLibrary(item)
374
+ const segment = item.controller.listArtifacts().artifacts.find(row => row.kind === 'segment')
375
+ fs.rmSync(segment.path, { recursive: true, force: true })
376
+ ageTree(item.root)
377
+ for (const dryRun of [true, false]) {
378
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
379
+ assert.deepEqual(rowsFor(result.candidates, item), [])
380
+ assert.ok(rowsFor(result.kept, item).length)
381
+ assert.ok(fs.existsSync(item.pointer))
382
+ }
383
+ })
384
+
385
+ test('a symlinked truth directory cannot prove that source truth is missing', () => {
386
+ const item = fixture()
387
+ deleteLibrary(item)
388
+ ageTree(item.root)
389
+ const truthDirectory = path.join(home, 'index')
390
+ const moved = path.join(home, `index-before-link-${nextFixture}`)
391
+ const outside = fs.mkdtempSync(path.join(home, 'truth-target-'))
392
+ fs.renameSync(truthDirectory, moved)
393
+ fs.symlinkSync(outside, truthDirectory, 'junction')
394
+ try {
395
+ for (const dryRun of [true, false]) {
396
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
397
+ assert.deepEqual(rowsFor(result.candidates, item), [])
398
+ assert.ok(fs.existsSync(item.pointer))
399
+ }
400
+ } finally {
401
+ fs.unlinkSync(truthDirectory)
402
+ fs.renameSync(moved, truthDirectory)
403
+ }
404
+ })
405
+
406
+ test('a dangling truth symlink is still truth presence and cannot authorize orphan deletion', () => {
407
+ const item = fixture()
408
+ deleteLibrary(item)
409
+ fs.symlinkSync(path.join(home, 'missing-truth-target'), item.truth, 'junction')
410
+ ageTree(item.root)
411
+ for (const dryRun of [true, false]) {
412
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
413
+ assert.deepEqual(rowsFor(result.candidates, item), [])
414
+ assert.ok(result.kept.some(row => row.identity === item.identity && row.reason === 'unregistered-truth-present'))
415
+ assert.ok(fs.existsSync(item.pointer))
416
+ }
417
+ })
418
+
419
+ test('unlocked directory cleanup preserves unknown files and a new concurrent lock', t => {
420
+ const item = fixture()
421
+ deleteLibrary(item)
422
+ ageTree(item.root)
423
+ const unknown = path.join(item.root, 'operator-notes.txt')
424
+ fs.writeFileSync(unknown, 'keep unknown files')
425
+ const rmdir = fs.rmdirSync
426
+ const lock = `${item.pointer}.lock`
427
+ let concurrentLock = false
428
+ t.mock.method(fs, 'rmdirSync', (file, ...args) => {
429
+ if (path.resolve(file) === item.root) {
430
+ assert.equal(fs.existsSync(lock), false)
431
+ fs.writeFileSync(lock, `${process.pid}\n`)
432
+ concurrentLock = true
433
+ }
434
+ return rmdir(file, ...args)
435
+ })
436
+ const preview = pruneRtArtifacts({ now: NOW })
437
+ const result = pruneRtArtifacts({ now: NOW, dryRun: false })
438
+ assert.deepEqual(result.removed, preview.candidates)
439
+ assert.equal(concurrentLock, true)
440
+ assert.equal(fs.readFileSync(unknown, 'utf8'), 'keep unknown files')
441
+ assert.ok(fs.existsSync(lock))
442
+ assert.equal(fs.existsSync(item.pointer), false)
443
+ t.mock.restoreAll()
444
+ })
445
+
446
+ test('lexicon namespace survives memory-library deletion and is never classified using missing memory truth', () => {
447
+ const item = fixture()
448
+ const directory = path.join(home, 'rt')
449
+ const options = { directory, libraryId: item.libraryId, namespace: 'lexicon', mode: 'on',
450
+ documentVersion: LEXICON_DOCUMENT_VERSION, documentText: lexiconDocumentText }
451
+ const source = createLexiconRtSource({ terms: { 'lex-protected': { term: 'violet', meaning: 'quartz' } } })
452
+ const controller = createRtIndex(options)
453
+ assert.equal(controller.rebuild(source).ok, true)
454
+ assert.equal(controller.rebuild(source).ok, true)
455
+ const lexical = indexLocation(options)
456
+ const pointer = path.join(lexical.root, 'current.json')
457
+ const before = fs.readFileSync(pointer)
458
+ const lexiconDirectory = path.join(home, 'lexicon')
459
+ fs.mkdirSync(lexiconDirectory, { recursive: true })
460
+ const truth = path.join(lexiconDirectory, `${item.libraryId}.json`)
461
+ fs.writeFileSync(truth, JSON.stringify({ terms: { 'lex-protected': { term: 'violet', meaning: 'quartz' } } }))
462
+ const truthBefore = fs.readFileSync(truth)
463
+ deleteLibrary(item)
464
+ ageTree(item.root)
465
+ ageTree(lexical.root)
466
+ const preview = pruneRtArtifacts({ now: NOW })
467
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
468
+ assert.equal(rowsFor(preview.candidates, item).length, 3)
469
+ assert.deepEqual(rowsFor(preview.candidates, lexical), [])
470
+ assert.deepEqual(rowsFor(applied.removed, lexical), [])
471
+ assert.deepEqual(applied.removed, preview.candidates)
472
+ assert.deepEqual(fs.readFileSync(pointer), before)
473
+ assert.deepEqual(fs.readFileSync(truth), truthBefore)
474
+ assert.equal(controller.listArtifacts().artifacts.length, 4, 'lexicon retention remains owned by its namespace policy')
475
+ assert.deepEqual(controller.search(source, 'quartz', { visibleIds: ['lex-protected'] }).hits.map(row => row.id), ['lex-protected'])
476
+ })
477
+
478
+ test('active and archived lexicons retire only old unreferenced generations with identical preview/apply', () => {
479
+ for (const archived of [false, true]) {
480
+ const item = fixture()
481
+ const lexicon = lexiconFixture(item.libraryId)
482
+ if (archived) assert.equal(state.archiveLibrary(item.libraryId), true)
483
+ ageTree(lexicon.root)
484
+ const pointer = fs.readFileSync(lexicon.pointer)
485
+ const truth = fs.readFileSync(lexicon.truth)
486
+ const preview = pruneRtArtifacts({ now: NOW })
487
+ assert.equal(rowsFor(preview.candidates, lexicon).length, 2)
488
+ assert.deepEqual(rowsFor(preview.removed, lexicon), [])
489
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
490
+ assert.deepEqual(rowsFor(applied.removed, lexicon), rowsFor(preview.candidates, lexicon))
491
+ assert.deepEqual(fs.readFileSync(lexicon.pointer), pointer)
492
+ assert.deepEqual(fs.readFileSync(lexicon.truth), truth)
493
+ assert.deepEqual(lexicon.controller.search(lexicon.source, 'quartz', { visibleIds: ['lex-kept'] }).hits.map(hit => hit.id), ['lex-kept'])
494
+ }
495
+ })
496
+
497
+ test('global lexicon current references survive even without a global canonical file', () => {
498
+ const lexicon = lexiconFixture('global', { truth: false })
499
+ ageTree(lexicon.root)
500
+ const before = fs.readFileSync(lexicon.pointer)
501
+ const result = pruneRtArtifacts({ now: NOW, dryRun: false })
502
+ assert.equal(rowsFor(result.removed, lexicon).length, 2)
503
+ assert.deepEqual(fs.readFileSync(lexicon.pointer), before)
504
+ assert.equal(lexicon.controller.listArtifacts().artifacts.filter(row => row.referenced).length, 2)
505
+ })
506
+
507
+ test('deleted library lexicon artifacts are orphaned only when lexicon truth is also absent', () => {
508
+ const item = fixture()
509
+ const lexicon = lexiconFixture(item.libraryId, { truth: false })
510
+ deleteLibrary(item)
511
+ ageTree(lexicon.root)
512
+ const preview = pruneRtArtifacts({ now: NOW })
513
+ assert.equal(rowsFor(preview.candidates, lexicon).length, 5)
514
+ assert.ok(fs.existsSync(lexicon.pointer))
515
+ const applied = pruneRtArtifacts({ now: NOW, dryRun: false })
516
+ assert.deepEqual(rowsFor(applied.removed, lexicon), rowsFor(preview.candidates, lexicon))
517
+ assert.equal(fs.existsSync(lexicon.root), false)
518
+ })
519
+
520
+ test('a lexicon truth junction cannot authorize orphan cleanup', () => {
521
+ const item = fixture()
522
+ const lexicon = lexiconFixture(item.libraryId, { truth: false })
523
+ deleteLibrary(item)
524
+ ageTree(lexicon.root)
525
+ fs.mkdirSync(path.dirname(lexicon.truth), { recursive: true })
526
+ fs.symlinkSync(path.join(home, 'missing-lexicon-truth'), lexicon.truth, 'junction')
527
+ for (const dryRun of [true, false]) {
528
+ const result = pruneRtArtifacts({ now: NOW, dryRun })
529
+ assert.deepEqual(rowsFor(result.candidates, lexicon), [])
530
+ assert.ok(fs.existsSync(lexicon.pointer))
531
+ assert.ok(fs.lstatSync(lexicon.truth).isSymbolicLink())
532
+ }
533
+ })
534
+
535
+ test('a corrupt registry cannot classify rt artifacts as orphaned through the empty-state fallback', () => {
536
+ const item = fixture()
537
+ ageTree(item.root)
538
+ state.flushState()
539
+ const stateFile = path.join(home, 'state.json')
540
+ const original = fs.readFileSync(stateFile)
541
+ state.clearCaches()
542
+ fs.writeFileSync(stateFile, '{corrupt registry')
543
+ try {
544
+ assert.throws(() => pruneRtArtifacts({ now: NOW, dryRun: false }), /registry could not be read reliably/)
545
+ assert.ok(fs.existsSync(item.pointer))
546
+ assert.ok(fs.existsSync(item.truth))
547
+ } finally {
548
+ fs.writeFileSync(stateFile, original)
549
+ state.clearCaches()
550
+ state.loadState()
551
+ }
552
+ })