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
@@ -11,6 +11,7 @@ import { profileFromCatalog, setRequestedProfile, vectorStatus, assertProfileVer
11
11
  import { embeddingWorkerManager } from './local-embedding-manager.js'
12
12
  import { modelIdForRole } from './local-embedding-protocol.js'
13
13
  import { managedEmbeddingRuntime } from './embedding-runtime.js'
14
+ import { acknowledgeDiagnostics } from './diagnostics.js'
14
15
 
15
16
  const root = path.join(downloadsDir(), 'embeddings')
16
17
  // 受管 runtime 与模型制品分开放:模型在 downloads/embeddings/<id>,运行时在
@@ -468,6 +469,7 @@ export async function healthCheckLocalVector(profile, { timeoutMs = 30_000 } = {
468
469
  * 没有云端回退:任一环失败都是 typed error + fallback=lexical。
469
470
  */
470
471
  export async function bootstrapLocalVector(options = {}) {
472
+ const startedAt = new Date().toISOString()
471
473
  const state = vectorStatus()
472
474
  const catalogId = options.id || state.active?.profile?.catalogId || state.requested?.catalogId || null
473
475
  if (!catalogId) throw Object.assign(new Error('select a local embedding model before bootstrapping the local runtime'), { code: 'LOCAL_VECTOR_NOT_SELECTED' })
@@ -491,6 +493,7 @@ export async function bootstrapLocalVector(options = {}) {
491
493
  }
492
494
  }
493
495
  const health = await healthCheckLocalVector(profileFor(catalogId), { timeoutMs: options.timeoutMs })
496
+ acknowledgeDiagnostics({ codes: ['LOCAL_VECTOR_RUNTIME_ABSENT'], before: startedAt })
494
497
  return { ok: true, runtime: { status: runtime.status, ready: true, path: runtime.path || null, key: runtime.key || null, source: runtime.source || 'managed', reused: runtime.reused === true }, model: health.model, dimension: health.dimension, health, state: getLocalVectorState() }
495
498
  }
496
499
 
@@ -1,34 +1,491 @@
1
1
  import path from 'node:path'
2
2
  import crypto from 'node:crypto'
3
- import { dataDir, readJson, writeJson, withFileLock, assertJsonShape } from './paths.js'
3
+ import fs from 'node:fs'
4
+ import { dataDir, ensureDir, readJson, readFailure, writeJson, assertJsonShape, assertWritable, warn } from './paths.js'
4
5
  import { memoryEntryRevision } from './memory.js'
6
+ import { listLibrariesAll } from './state.js'
5
7
 
6
8
  export const MAINTENANCE_LEDGER_VERSION = 1
7
9
  export const MAINTENANCE_LEASE_MS = 300_000
8
10
  export const MAINTENANCE_REVIEW_MS = 24 * 60 * 60_000
11
+ export const MAINTENANCE_CHECKPOINT_RECORDS = 128
12
+ export const MAINTENANCE_CHECKPOINT_BYTES = 1_048_576
9
13
  export const maintenanceLedgerPath = () => path.join(dataDir(), 'maintenance.json')
14
+ export const maintenanceJournalPath = () => path.join(dataDir(), 'maintenance.journal.jsonl')
10
15
  export const maintenanceKey = (libraryId, memoryId, reason) => JSON.stringify([libraryId, memoryId, reason])
11
16
  const iso = now => new Date(now).toISOString()
12
17
  export const maintenanceEntryRevision = memoryEntryRevision
13
18
  export const maintenanceEffectRevision = entry => memoryEntryRevision({ ...entry, updatedAt: null })
14
19
  export const evidenceRevision = evidence => crypto.createHash('sha256').update(JSON.stringify(evidence)).digest('hex')
15
20
 
16
- export function loadMaintenanceLedger() {
21
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
22
+ const validLedger = value => isObject(value) && value.version === 1 && isObject(value.items)
23
+ && (value.libraries === undefined || isObject(value.libraries))
24
+ const hashPattern = /^[a-f0-9]{64}$/
25
+ const generationPattern = /^[a-f0-9-]{36}$/
26
+ const reservedRoots = new Set(['version', 'items', 'libraries', '_journal'])
27
+ const activeMutations = new Set()
28
+ const maintenanceLocks = new Map()
29
+
30
+ function maintenanceBusy() {
31
+ const error = new Error('memory store is busy: maintenance; retry the operation')
32
+ error.code = 'DSH_MEMU_STORE_BUSY'
33
+ return error
34
+ }
35
+
36
+ function assertMaintenanceLock() {
37
+ const lock = path.resolve(maintenanceLedgerPath()) + '.lock'
38
+ const owner = maintenanceLocks.get(lock)
39
+ try {
40
+ if (owner && fs.readFileSync(lock, 'utf8') === owner.payload) return
41
+ } catch {}
42
+ warn('maintenance persistence: lock ownership changed; refusing a stale store write')
43
+ throw maintenanceBusy()
44
+ }
45
+
46
+ /** Same-path synchronous lock; elapsed time alone never evicts a live owner. */
47
+ export function withMaintenanceLock(action) {
48
+ const lock = path.resolve(maintenanceLedgerPath()) + '.lock'
49
+ if (maintenanceLocks.has(lock)) { assertMaintenanceLock(); return action() }
50
+ ensureDir(path.dirname(lock))
51
+ const until = Date.now() + 500
52
+ const payload = `${process.pid}\n${new Date().toISOString()}\n${crypto.randomUUID()}\n`
53
+ let fd
54
+ while (fd === undefined) {
55
+ try {
56
+ fd = fs.openSync(lock, 'wx', 0o600)
57
+ try { fs.writeFileSync(fd, payload) } catch (error) {
58
+ fs.closeSync(fd); fd = undefined
59
+ try { fs.unlinkSync(lock) } catch {}
60
+ throw error
61
+ }
62
+ } catch (error) {
63
+ if (error?.code !== 'EEXIST') throw error
64
+ try {
65
+ const stat = fs.lstatSync(lock)
66
+ if (!stat.isFile() || stat.isSymbolicLink()) throw maintenanceBusy()
67
+ const owner = Number(fs.readFileSync(lock, 'utf8').split(/\r?\n/)[0])
68
+ let abandoned = false
69
+ if (Number.isSafeInteger(owner) && owner > 0) {
70
+ try { process.kill(owner, 0) } catch (probe) { abandoned = probe.code === 'ESRCH' }
71
+ } else abandoned = Date.now() - stat.mtimeMs >= 10_000
72
+ if (abandoned) { fs.unlinkSync(lock); continue }
73
+ } catch (probe) {
74
+ if (probe.code === 'ENOENT') continue
75
+ if (probe.code === 'DSH_MEMU_STORE_BUSY') throw probe
76
+ }
77
+ if (Date.now() >= until) throw maintenanceBusy()
78
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
79
+ }
80
+ }
81
+ maintenanceLocks.set(lock, { payload })
82
+ try {
83
+ const result = action()
84
+ if (result && typeof result.then === 'function') throw new Error('maintenance lock callbacks must be synchronous')
85
+ return result
86
+ } finally {
87
+ maintenanceLocks.delete(lock)
88
+ fs.closeSync(fd)
89
+ // A resumed stale owner must not unlink the replacement owner's lock.
90
+ for (let attempt = 0; ; attempt++) {
91
+ try {
92
+ if (fs.readFileSync(lock, 'utf8') === payload) fs.unlinkSync(lock)
93
+ break
94
+ } catch (error) {
95
+ if (error.code === 'ENOENT') break
96
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error.code) && attempt < 5) {
97
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5 * (attempt + 1)); continue
98
+ }
99
+ warn(`maintenance persistence: could not release lock (${error.code || 'IO_ERROR'})`)
100
+ break
101
+ }
102
+ }
103
+ }
104
+ }
105
+
106
+ function assertNoMutation() {
107
+ if (activeMutations.has(path.resolve(maintenanceLedgerPath()))) throw new Error('maintenance mutations cannot nest writes or checkpoints')
108
+ }
109
+
110
+ function digest(value) {
111
+ const json = JSON.stringify(value, (_, item) => isObject(item)
112
+ ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item)
113
+ return crypto.createHash('sha256').update(json).digest('hex')
114
+ }
115
+
116
+ function journalError(reason, code = 'DSH_MEMU_MAINTENANCE_JOURNAL_INVALID') {
117
+ warn(`maintenance persistence ${code}: ${reason}; writes are blocked until the store is repaired or restored`)
118
+ const error = new Error(`maintenance persistence: ${reason}`)
119
+ error.code = code
120
+ return error
121
+ }
122
+
123
+ function validToken(value) {
124
+ return isObject(value) && generationPattern.test(value.generation) && hashPattern.test(value.baseHash)
125
+ && Number.isSafeInteger(value.sequence) && value.sequence > 0 && hashPattern.test(value.headHash)
126
+ }
127
+
128
+ function baselineIdentity() {
129
+ const stat = fs.statSync(maintenanceLedgerPath(), { bigint: true })
130
+ return digest([stat.dev, stat.ino, stat.birthtimeNs, stat.mtimeNs, stat.size].map(String))
131
+ }
132
+
133
+ function snapshotData(raw) {
134
+ if (!validLedger(raw)) throw journalError('invalid maintenance snapshot shape')
135
+ const { _journal: meta, ...data } = raw
136
+ data.libraries ||= {}
137
+ if (meta !== undefined) {
138
+ if (!isObject(meta)) throw journalError('invalid maintenance snapshot anchor')
139
+ const { checksum, ...payload } = meta
140
+ if (payload.version !== 1 || !generationPattern.test(payload.generation) || !hashPattern.test(payload.baseHash)
141
+ || (payload.previous !== null && !validToken(payload.previous)) || checksum !== digest(payload)
142
+ || payload.baseHash !== digest(data)) throw journalError('maintenance snapshot anchor checksum mismatch')
143
+ }
144
+ return { data, meta: meta || null }
145
+ }
146
+
147
+ function validatePatch(patch) {
148
+ if (!Array.isArray(patch) || patch.length === 0) throw journalError('invalid journal patch')
149
+ const seen = new Set()
150
+ for (const op of patch) {
151
+ if (!isObject(op) || !['items', 'libraries', 'root'].includes(op.scope) || typeof op.key !== 'string'
152
+ || !['set', 'delete'].includes(op.op) || (op.scope === 'root' && reservedRoots.has(op.key))
153
+ || (op.op === 'set' && !Object.hasOwn(op, 'value'))
154
+ || Object.keys(op).some(key => !['scope', 'key', 'op', ...(op.op === 'set' ? ['value'] : [])].includes(key))) throw journalError('invalid journal patch operation')
155
+ const key = JSON.stringify([op.scope, op.key])
156
+ if (seen.has(key)) throw journalError('duplicate journal patch operation')
157
+ seen.add(key)
158
+ }
159
+ }
160
+
161
+ function readJournal() {
162
+ const file = maintenanceJournalPath()
163
+ assertWritable(file)
164
+ let bytes
165
+ try { bytes = fs.readFileSync(file) } catch (error) {
166
+ if (error?.code === 'ENOENT') return { exists: false, count: 0, validBytes: 0, bytes: 0, tailBytes: 0, records: [] }
167
+ throw journalError('journal read failed', 'DSH_MEMU_MAINTENANCE_JOURNAL_IO')
168
+ }
169
+ const validBytes = bytes.lastIndexOf(10) + 1
170
+ const tailBytes = bytes.length - validBytes
171
+ let text
172
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, validBytes)) } catch {
173
+ throw journalError('journal contains invalid UTF-8')
174
+ }
175
+ const records = []
176
+ let generation, baseHash, baseIdentity, headHash, legacyIdentity = false
177
+ for (const line of text ? text.slice(0, -1).split('\n') : []) {
178
+ let record
179
+ try { record = JSON.parse(line) } catch { throw journalError(`invalid committed journal line ${records.length + 1}`) }
180
+ if (!isObject(record)) throw journalError('invalid journal record shape')
181
+ const { checksum, ...payload } = record
182
+ // Records written before the baseIdentity field existed carry six keys. A new
183
+ // build must keep reading them, otherwise every upgrade bricks a live store
184
+ // on "journal sequence or checksum mismatch" — the exact failure users hit on
185
+ // a version bump. The identity guard is simply skipped for such records.
186
+ const keys = Object.keys(payload)
187
+ const legacyRecord = !Object.hasOwn(payload, 'baseIdentity') && keys.length === 6
188
+ if (legacyRecord) legacyIdentity = true
189
+ if (!(keys.length === 7 || legacyRecord) || payload.version !== 1
190
+ || !generationPattern.test(payload.generation) || !hashPattern.test(payload.baseHash)
191
+ || (!legacyRecord && !hashPattern.test(payload.baseIdentity))
192
+ || payload.sequence !== records.length + 1 || !hashPattern.test(payload.parentHash)
193
+ || checksum !== digest(payload)) throw journalError(`journal sequence or checksum mismatch at line ${records.length + 1}`)
194
+ if (!records.length) { generation = payload.generation; baseHash = payload.baseHash; baseIdentity = payload.baseIdentity; headHash = baseHash }
195
+ if (generation !== payload.generation || baseHash !== payload.baseHash
196
+ || (!legacyRecord && baseIdentity !== payload.baseIdentity)
197
+ || payload.parentHash !== headHash) throw journalError(`journal parent mismatch at line ${records.length + 1}`)
198
+ validatePatch(payload.patch)
199
+ records.push(record)
200
+ headHash = checksum
201
+ }
202
+ if (tailBytes) warn(`maintenance persistence: ignoring ${tailBytes} uncommitted journal tail byte(s)`)
203
+ return { exists: true, count: records.length, validBytes, bytes: bytes.length, tailBytes, records, generation, baseHash, baseIdentity, headHash, legacyIdentity }
204
+ }
205
+
206
+ function applyPatch(data, patch) {
207
+ for (const op of patch) {
208
+ const target = op.scope === 'root' ? data : data[op.scope]
209
+ if (op.op === 'delete') delete target[op.key]
210
+ else Object.defineProperty(target, op.key, { value: op.value, writable: true, configurable: true, enumerable: true })
211
+ }
212
+ }
213
+
214
+ function tokenOf(journal) {
215
+ return journal.count ? { generation: journal.generation, baseHash: journal.baseHash, sequence: journal.count, headHash: journal.headHash } : null
216
+ }
217
+
218
+ /**
219
+ * Explicit repair for a store whose snapshot anchor and journal can no longer be
220
+ * reconciled — typically left that way by an older, journal-less writer that kept
221
+ * rewriting the snapshot while carrying a stale `_journal`.
222
+ *
223
+ * Deliberately NOT automatic: an anchor that no longer matches its data is
224
+ * indistinguishable from tampering, and the store's contract is to fail closed
225
+ * before replaying patches. Both originals are copied aside first; nothing is
226
+ * deleted, so a wrong call is recoverable.
227
+ */
228
+ export function repairMaintenanceStore() {
229
+ return withMaintenanceLock(() => {
230
+ assertNoMutation()
231
+ return repairMaintenanceStoreLocked()
232
+ })
233
+ }
234
+
235
+ function repairMaintenanceStoreLocked(reason = 'explicit repair') {
236
+ const lock = path.resolve(maintenanceLedgerPath()) + '.lock'
237
+ if (!maintenanceLocks.has(lock)) return false
238
+ try { assertMaintenanceLock() } catch { return false }
239
+ const file = maintenanceLedgerPath()
240
+ if (!fs.existsSync(file)) return false
241
+ let raw
242
+ try { raw = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return false }
243
+ if (!isObject(raw)) return false
244
+ const { _journal, ...rest } = raw
245
+ const data = { ...rest }
246
+ data.libraries ||= {}
247
+ if (!validLedger(data)) return false
248
+ const stamp = crypto.randomUUID()
249
+ let copied = false
250
+ try {
251
+ fs.copyFileSync(file, `${file}.repaired-${stamp}`, fs.constants.COPYFILE_EXCL)
252
+ copied = true
253
+ } catch {}
254
+ if (!copied) return false
255
+ const journal = maintenanceJournalPath()
256
+ try {
257
+ if (fs.existsSync(journal)) {
258
+ fs.copyFileSync(journal, `${journal}.superseded-${stamp}`, fs.constants.COPYFILE_EXCL)
259
+ fs.rmSync(journal, { force: true })
260
+ }
261
+ } catch { return false }
262
+ try {
263
+ writeCheckpoint({ data, journal: { exists: false, count: 0 }, legacyReplacement: false, meta: null }, data)
264
+ } catch { return false }
265
+ warn(`maintenance persistence: healed an unusable journal (${reason}); snapshot kept as maintenance.json.repaired-${stamp}`
266
+ + (fs.existsSync(`${journal}.superseded-${stamp}`) ? `, journal kept as maintenance.journal.jsonl.superseded-${stamp}` : ''))
267
+ return true
268
+ }
269
+
270
+ function readStoreLocked() {
17
271
  const file = maintenanceLedgerPath()
18
272
  const raw = readJson(file, null)
19
- if (raw !== null && !assertJsonShape(file, raw, value => value?.version === 1 && value.items && typeof value.items === 'object' && !Array.isArray(value.items))) throw new Error('invalid maintenance ledger')
20
- return raw || { version: MAINTENANCE_LEDGER_VERSION, items: {}, libraries: {} }
273
+ if (readFailure(file)) throw new Error('maintenance ledger could not be read reliably')
274
+ const exists = fs.existsSync(file)
275
+ if (exists && !assertJsonShape(file, raw, validLedger)) throw new Error('invalid maintenance ledger')
276
+ let snapshot
277
+ try {
278
+ snapshot = snapshotData(raw || { version: MAINTENANCE_LEDGER_VERSION, items: {}, libraries: {} })
279
+ } catch (error) {
280
+ if (error?.code !== 'DSH_MEMU_MAINTENANCE_JOURNAL_INVALID') throw error
281
+ // With an empty journal there is nothing to replay, so an anchor that no
282
+ // longer matches its data cannot cost anything: accept what is on disk and
283
+ // re-anchor. A writer that ignores the protocol (an older build) rewrites the
284
+ // snapshot on every cycle; without this the store flipped into a permanent
285
+ // 5-minute error loop after any downgrade. A non-empty journal still refuses,
286
+ // because there the anchor decides which base the patches belong to.
287
+ const pending = readJournal()
288
+ if (pending.count > 0) throw error
289
+ if (!repairMaintenanceStoreLocked('anchor no longer matched its data while the journal was empty')) throw error
290
+ return readStoreLocked()
291
+ }
292
+ const { data, meta } = snapshot
293
+ const journal = readJournal()
294
+ if (!exists && journal.exists) throw journalError('journal baseline is missing')
295
+ if (meta && !journal.exists) throw journalError('anchored snapshot journal is missing')
296
+ let covered = false
297
+ let legacyReplacement = false
298
+ if (journal.count) {
299
+ if (!exists) throw journalError('journal baseline is missing')
300
+ if (!meta) {
301
+ // A complete old-format JSON image is an explicit legacy import. Never
302
+ // replay a newer journal over it; keep the old bytes for manual recovery.
303
+ legacyReplacement = true
304
+ warn('maintenance persistence: legacy JSON image replaced the journal baseline; preserving the superseded journal on next write')
305
+ } else if (meta.generation === journal.generation && meta.baseHash === journal.baseHash) {
306
+ if (journal.legacyIdentity) {
307
+ warn('maintenance persistence: journal predates the baseIdentity field; applying it without the file-identity guard')
308
+ } else if (journal.baseIdentity !== baselineIdentity()) {
309
+ // The snapshot is not the file these patches were appended to, so an
310
+ // outside restore wins over the write-ahead log: never replay onto it.
311
+ // Park the journal as a recovery artifact and re-anchor instead of
312
+ // blocking the store forever (that turned every copy/reinstall/legacy
313
+ // write into a permanent 5-minute error loop).
314
+ if (!repairMaintenanceStoreLocked('checkpoint file was replaced outside the store')) {
315
+ throw journalError('snapshot file was replaced; restore a complete image through the restore API')
316
+ }
317
+ return readStoreLocked()
318
+ }
319
+ for (const record of journal.records) applyPatch(data, record.patch)
320
+ } else if (meta.previous && digest(meta.previous) === digest(tokenOf(journal))) {
321
+ // Snapshot rename committed, but rotation did not. Its fresh generation
322
+ // supersedes exactly this verified journal, never a merely similar one.
323
+ covered = true
324
+ } else throw journalError('journal does not match the snapshot generation or base hash')
325
+ }
326
+ return { data, meta, journal, covered, legacyReplacement, exists }
21
327
  }
22
328
 
23
- export function mutateMaintenanceLedger(action) {
24
- return withFileLock(maintenanceLedgerPath(), () => {
25
- const ledger = loadMaintenanceLedger()
26
- const result = action(ledger)
27
- writeJson(maintenanceLedgerPath(), ledger)
28
- return result
329
+ function syncDirectory() {
330
+ let fd
331
+ try { fd = fs.openSync(dataDir(), 'r'); fs.fsyncSync(fd) } catch (error) {
332
+ if (!['EPERM', 'EACCES', 'EINVAL', 'ENOTSUP', 'EISDIR', 'EBADF'].includes(error?.code)) throw error
333
+ } finally { if (fd !== undefined) fs.closeSync(fd) }
334
+ }
335
+
336
+ function rotateJournal() {
337
+ assertMaintenanceLock()
338
+ const file = maintenanceJournalPath()
339
+ assertWritable(file)
340
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`
341
+ try {
342
+ const fd = fs.openSync(tmp, 'wx', 0o600)
343
+ try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
344
+ fs.renameSync(tmp, file)
345
+ syncDirectory()
346
+ } catch (error) {
347
+ try { fs.unlinkSync(tmp) } catch {}
348
+ throw error
349
+ }
350
+ }
351
+
352
+ function writeCheckpoint(store, data = store.data) {
353
+ assertMaintenanceLock()
354
+ if (store.legacyReplacement) {
355
+ const aside = `${maintenanceJournalPath()}.superseded-${crypto.randomUUID()}`
356
+ fs.copyFileSync(maintenanceJournalPath(), aside, fs.constants.COPYFILE_EXCL)
357
+ const fd = fs.openSync(aside, 'r+')
358
+ try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
359
+ syncDirectory()
360
+ }
361
+ const anchor = { version: 1, generation: crypto.randomUUID(), baseHash: digest(data), previous: tokenOf(store.journal) }
362
+ const snapshot = { ...data, _journal: { ...anchor, checksum: digest(anchor) } }
363
+ // Create and sync the initial journal before publishing an anchored snapshot.
364
+ // Thereafter a missing journal is data loss, never an empty pending queue.
365
+ if (!store.journal.exists) rotateJournal()
366
+ writeJson(maintenanceLedgerPath(), snapshot)
367
+ syncDirectory()
368
+ rotateJournal()
369
+ return { generation: anchor.generation, checkpointedRecords: store.journal.count, pendingRecords: 0 }
370
+ }
371
+
372
+ /** Legacy readers/exporters must checkpoint before consuming maintenance.json. */
373
+ export function checkpointMaintenanceLedger({ ifExists = false } = {}) {
374
+ return withMaintenanceLock(() => {
375
+ assertNoMutation()
376
+ const store = readStoreLocked()
377
+ if (ifExists && !store.exists) return null
378
+ return writeCheckpoint(store)
379
+ })
380
+ }
381
+
382
+ /** Validate backup input without modifying either the backup or the live store. */
383
+ export function validateMaintenanceSnapshot(raw) {
384
+ return snapshotData(raw).data
385
+ }
386
+
387
+ /** An explicit restore starts a fresh generation, even for identical JSON data. */
388
+ export function restoreMaintenanceSnapshot(raw) {
389
+ const data = validateMaintenanceSnapshot(raw)
390
+ return withMaintenanceLock(() => {
391
+ assertNoMutation()
392
+ return writeCheckpoint(readStoreLocked(), data)
29
393
  })
30
394
  }
31
395
 
396
+ export function loadMaintenanceLedger() {
397
+ return withMaintenanceLock(() => readStoreLocked().data)
398
+ }
399
+
400
+ function serializeParts(data) {
401
+ return Object.fromEntries(['items', 'libraries', 'root'].map(scope => {
402
+ const object = scope === 'root' ? data : data[scope] || {}
403
+ return [scope, new Map(Object.keys(object).filter(key => scope !== 'root' || !reservedRoots.has(key))
404
+ .map(key => [key, JSON.stringify(object[key])]).filter(([, value]) => value !== undefined))]
405
+ }))
406
+ }
407
+
408
+ function diffParts(before, data) {
409
+ const after = serializeParts(data)
410
+ const patch = []
411
+ for (const scope of ['items', 'libraries', 'root']) {
412
+ for (const key of before[scope].keys()) if (!after[scope].has(key)) patch.push({ scope, key, op: 'delete' })
413
+ for (const [key, value] of after[scope]) {
414
+ if (before[scope].get(key) !== value) patch.push({ scope, key, op: 'set', value: JSON.parse(value) })
415
+ }
416
+ }
417
+ return patch
418
+ }
419
+
420
+ function appendPatch(store, patch) {
421
+ assertMaintenanceLock()
422
+ const payload = { version: 1, generation: store.meta.generation, baseHash: store.meta.baseHash,
423
+ baseIdentity: baselineIdentity(),
424
+ sequence: store.journal.count + 1, parentHash: store.journal.headHash || store.meta.baseHash, patch }
425
+ const record = { ...payload, checksum: digest(payload) }
426
+ const bytes = Buffer.from(JSON.stringify(record) + '\n', 'utf8')
427
+ const file = maintenanceJournalPath()
428
+ assertWritable(file)
429
+ // Windows append-only handles cannot truncate a torn suffix. The same-path
430
+ // lock makes an explicit verified append offset safe on a read/write handle.
431
+ const fd = fs.openSync(file, 'r+')
432
+ try {
433
+ // Only a suffix lacking the newline commit marker may be discarded. Every
434
+ // complete line has already passed checksum/sequence/parent verification.
435
+ if (store.journal.tailBytes) { fs.ftruncateSync(fd, store.journal.validBytes); fs.fsyncSync(fd) }
436
+ let written = 0
437
+ while (written < bytes.length) {
438
+ assertMaintenanceLock()
439
+ const count = fs.writeSync(fd, bytes, written, bytes.length - written, store.journal.validBytes + written)
440
+ if (count <= 0) throw new Error('maintenance journal append made no progress')
441
+ written += count
442
+ }
443
+ fs.fsyncSync(fd)
444
+ } catch (error) {
445
+ try { assertMaintenanceLock(); fs.ftruncateSync(fd, store.journal.validBytes); fs.fsyncSync(fd) } catch {
446
+ warn('maintenance persistence: append outcome is uncertain; recovery must verify the journal before any write')
447
+ }
448
+ throw error
449
+ } finally { fs.closeSync(fd) }
450
+ syncDirectory()
451
+ return { ...store.journal, count: payload.sequence, generation: payload.generation, baseHash: payload.baseHash,
452
+ headHash: record.checksum, validBytes: store.journal.validBytes + bytes.length, bytes: store.journal.validBytes + bytes.length, tailBytes: 0 }
453
+ }
454
+
455
+ const checkpointDue = journal => journal.count >= MAINTENANCE_CHECKPOINT_RECORDS || journal.bytes >= MAINTENANCE_CHECKPOINT_BYTES
456
+
457
+ function mutateLocked(store, action) {
458
+ assertNoMutation()
459
+ const target = path.resolve(maintenanceLedgerPath())
460
+ activeMutations.add(target)
461
+ try {
462
+ if (!store.meta || store.covered || store.legacyReplacement || checkpointDue(store.journal)) {
463
+ writeCheckpoint(store)
464
+ store = readStoreLocked()
465
+ }
466
+ const before = serializeParts(store.data)
467
+ const result = action(store.data)
468
+ if (result && typeof result.then === 'function') throw new Error('maintenance mutations must be synchronous')
469
+ if (!validLedger(store.data) || Object.hasOwn(store.data, '_journal')) throw new Error('invalid maintenance mutation shape')
470
+ const patch = diffParts(before, store.data)
471
+ if (patch.length) {
472
+ store.journal = appendPatch(store, patch)
473
+ if (checkpointDue(store.journal)) {
474
+ // The patch is already durable. Report compaction failure without lying
475
+ // about that commit; the next mutation must checkpoint before appending.
476
+ try { writeCheckpoint(store) } catch (error) {
477
+ warn(`maintenance persistence: checkpoint deferred after durable append (${error?.code || 'IO_ERROR'})`)
478
+ }
479
+ }
480
+ }
481
+ return result
482
+ } finally { activeMutations.delete(target) }
483
+ }
484
+
485
+ export function mutateMaintenanceLedger(action) {
486
+ return withMaintenanceLock(() => mutateLocked(readStoreLocked(), action))
487
+ }
488
+
32
489
  // No entry text or source quotes live in this sidecar. Content changes invalidate an
33
490
  // old review; injection counters do not. A persisted apply intent survives rescans.
34
491
  export function syncMaintenanceCandidates(candidates, { now, scannedLibraries = [] } = {}) {
@@ -53,10 +510,14 @@ export function syncMaintenanceCandidates(candidates, { now, scannedLibraries =
53
510
  } else if (item.state === 'settled') {
54
511
  Object.assign(item, { blockedReason: null, state: 'pending', nextReviewAt: iso(now) })
55
512
  }
513
+ if (item.state !== 'settled') delete item.settledAt
56
514
  }
57
515
  const scanned = new Set(scannedLibraries)
58
516
  for (const item of Object.values(ledger.items)) {
59
- if (scanned.has(item.libraryId) && !seen.has(item.key) && !item.applyIntent) {
517
+ if (scanned.has(item.libraryId) && !seen.has(item.key) && !item.applyIntent && !(Date.parse(item.lease?.until || '') > now)) {
518
+ // A rescan must neither backdate a new settlement nor invent a date for
519
+ // legacy rows already settled without evidence of when that happened.
520
+ if (item.state !== 'settled') item.settledAt = iso(now)
60
521
  Object.assign(item, { state: 'settled', result: 'no-longer-pending', lease: null, retryAt: null, blockedReason: null })
61
522
  }
62
523
  }
@@ -72,17 +533,21 @@ export function claimMaintenanceItem(key, { now, entryRevision, leaseMs = MAINTE
72
533
  const recovered = Boolean(item.lease)
73
534
  const jobId = crypto.randomUUID()
74
535
  Object.assign(item, { state: 'inflight', blockedReason: null, lastCheckedAt: iso(now), lease: { jobId, until: iso(now + leaseMs) }, recoveredLeases: (item.recoveredLeases || 0) + Number(recovered) })
536
+ delete item.settledAt
75
537
  ledger.libraries ||= {}
76
538
  ledger.libraries[item.libraryId] = { lastCheckedAt: iso(now) }
77
539
  return structuredClone(item)
78
540
  })
79
541
  }
80
542
 
81
- export function patchMaintenanceItem(key, jobId, patch) {
543
+ export function patchMaintenanceItem(key, jobId, patch, { now = Date.now() } = {}) {
82
544
  return mutateMaintenanceLedger(ledger => {
83
545
  const item = ledger.items[key]
84
546
  if (!item || (jobId && item.lease?.jobId !== jobId)) return null
547
+ const settling = patch.state === 'settled' && item.state !== 'settled'
85
548
  Object.assign(item, patch)
549
+ if (settling) item.settledAt = patch.settledAt || patch.lastReviewedAt || iso(now)
550
+ else if (item.state !== 'settled') delete item.settledAt
86
551
  return structuredClone(item)
87
552
  })
88
553
  }
@@ -136,3 +601,68 @@ export function maintenanceStatus({ libraryId = null, now = Date.now() } = {}) {
136
601
  }
137
602
  return out
138
603
  }
604
+
605
+ function maintenanceItemTimestamp(item) {
606
+ // Old creation/review clocks are not evidence of a settlement date. Unknown
607
+ // legacy dates fail safe: a newly settled old item gets a full retention term.
608
+ const value = item?.settledAt
609
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)) return null
610
+ const at = Date.parse(value)
611
+ return Number.isFinite(at) && new Date(at).toISOString().slice(0, 19) === value.slice(0, 19) ? at : null
612
+ }
613
+
614
+ function settledRetentionCandidate(item, { cutoff, now }) {
615
+ if (!item || item.state !== 'settled' || item.applyIntent) return false
616
+ if (Date.parse(item.lease?.until || '') > now) return false
617
+ const at = maintenanceItemTimestamp(item)
618
+ return at !== null && at < cutoff
619
+ }
620
+
621
+ function registeredLibraryIds(listLibraries) {
622
+ const libraries = listLibraries()
623
+ // The registry's read-failure fallback is useful for UI reads, but is not
624
+ // evidence that every library has been deleted. Archived libraries still exist.
625
+ if (readFailure(path.join(dataDir(), 'state.json'))) throw new Error('library registry could not be read reliably')
626
+ if (!Array.isArray(libraries) || libraries.some(item => !item || typeof item.id !== 'string' || !item.id)) throw new Error('invalid library registry')
627
+ return new Set(libraries.map(item => item.id))
628
+ }
629
+
630
+ /** Remove only aged, settled maintenance metadata; never memory entries or apply intents. */
631
+ export function pruneSettledMaintenanceItems({ olderThanDays = 180, dryRun = true, now = Date.now(), listLibraries = listLibrariesAll } = {}) {
632
+ const days = Number(olderThanDays)
633
+ const current = Number(now)
634
+ if (!Number.isFinite(days) || days <= 0) throw new Error('olderThanDays must be a positive number of days')
635
+ if (!Number.isFinite(current)) throw new Error('now must be a finite timestamp')
636
+ const cutoff = current - days * 86_400_000
637
+ const registered = registeredLibraryIds(listLibraries)
638
+ const initial = loadMaintenanceLedger()
639
+ const candidates = Object.entries(initial.items)
640
+ .filter(([, item]) => settledRetentionCandidate(item, { cutoff, now: current }))
641
+ .map(([key, item]) => ({ key, revision: evidenceRevision(item), orphaned: !registered.has(item.libraryId) }))
642
+ const orphanedCandidates = candidates.filter(item => item.orphaned).map(item => item.key)
643
+ const base = { dryRun: dryRun !== false, olderThanDays: days, candidates: candidates.map(item => item.key), orphanedCandidates, orphanedCandidateCount: orphanedCandidates.length }
644
+ if (dryRun !== false || candidates.length === 0) return { ...base, removed: [], revalidated: [], orphanedRemoved: [], orphanedRemovedCount: 0 }
645
+ const removed = []
646
+ const revalidated = []
647
+ const orphanedRemoved = []
648
+ withMaintenanceLock(() => {
649
+ const store = readStoreLocked()
650
+ const ledger = store.data
651
+ const currentRegistered = registeredLibraryIds(listLibraries)
652
+ for (const candidate of candidates) {
653
+ const item = ledger.items[candidate.key]
654
+ if (!settledRetentionCandidate(item, { cutoff, now: current })
655
+ || evidenceRevision(item) !== candidate.revision
656
+ || (!currentRegistered.has(item.libraryId)) !== candidate.orphaned) {
657
+ revalidated.push(candidate.key)
658
+ continue
659
+ }
660
+ removed.push(candidate.key)
661
+ if (candidate.orphaned) orphanedRemoved.push(candidate.key)
662
+ }
663
+ if (removed.length > 0) mutateLocked(store, data => {
664
+ for (const key of removed) delete data.items[key]
665
+ })
666
+ })
667
+ return { ...base, removed, revalidated, orphanedRemoved, orphanedRemovedCount: orphanedRemoved.length }
668
+ }