dsh-memu-memory 1.4.3 → 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 (183) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +34 -15
  4. package/README.zh.md +35 -13
  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/preset-mount.js +13 -7
  63. package/lib/private.js +47 -21
  64. package/lib/recall-cache.js +20 -34
  65. package/lib/retention.js +173 -0
  66. package/lib/rpc.js +135 -52
  67. package/lib/rt-index/builder.js +209 -0
  68. package/lib/rt-index/format.js +231 -0
  69. package/lib/rt-index/manifest.js +105 -0
  70. package/lib/rt-index/reader.js +673 -0
  71. package/lib/rt-index-retention.js +151 -0
  72. package/lib/rt-index-service.js +283 -0
  73. package/lib/rt-index-worker.js +21 -0
  74. package/lib/salient-wake.js +55 -4
  75. package/lib/state.js +195 -24
  76. package/lib/temporal.js +39 -13
  77. package/lib/token-measurement.js +126 -0
  78. package/lib/tools.js +101 -6
  79. package/lib/turn-log.js +108 -3
  80. package/lib/webui/graph-layout-worker.js +68 -0
  81. package/lib/webui/graph-local-physics.js +390 -0
  82. package/lib/webui/graph-spatial-grid.js +64 -0
  83. package/lib/webui/graph-view.bundle.js +6 -1
  84. package/lib/webui/graph-view.js +478 -135
  85. package/lib/webui/graph-webgl-renderer.js +74 -0
  86. package/lib/webui/standalone.js +1 -1
  87. package/lib/worker-pool.js +38 -7
  88. package/package.json +3 -2
  89. package/scripts/acceptance-local.mjs +4 -10
  90. package/scripts/bench-all-libraries.mjs +47 -0
  91. package/scripts/check-classic-graph-browser.mjs +189 -0
  92. package/scripts/check-client-browser.mjs +929 -0
  93. package/scripts/check-graph-browser.mjs +6 -0
  94. package/scripts/check-graph-elastic-browser.mjs +139 -0
  95. package/scripts/check-memory-review-browser.mjs +124 -0
  96. package/scripts/entity-dedupe.mjs +19 -3
  97. package/scripts/graph-artifact-provenance.mjs +30 -0
  98. package/scripts/graph-freeze-manifest.mjs +129 -0
  99. package/scripts/graph-geometry-fixture.mjs +40 -0
  100. package/scripts/graph-physics-bench.mjs +218 -0
  101. package/scripts/graph-scale-bench.mjs +213 -0
  102. package/scripts/graph-scale-memory.mjs +48 -0
  103. package/scripts/graph-service-bench.mjs +72 -0
  104. package/scripts/make-readme-shots.mjs +17 -5
  105. package/scripts/preview.mjs +1 -0
  106. package/scripts/rebuild-rt.mjs +18 -0
  107. package/scripts/scale-bench.mjs +183 -0
  108. package/scripts/simulate-injection.mjs +47 -8
  109. package/scripts/verify-host-fixtures.mjs +108 -0
  110. package/scripts/verify-host-recovery.mjs +565 -0
  111. package/scripts/verify-vector-recovery.mjs +740 -0
  112. package/tests/auto-link-candidates.test.mjs +20 -0
  113. package/tests/browser.test.mjs +16 -2
  114. package/tests/client-export.test.mjs +16 -1
  115. package/tests/client-pagination.test.mjs +1495 -0
  116. package/tests/client-render.test.mjs +223 -28
  117. package/tests/consolidation-fork.test.mjs +97 -13
  118. package/tests/consolidation-ledger.test.mjs +17 -1
  119. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  120. package/tests/diagnostic-report.test.mjs +429 -0
  121. package/tests/diagnostic-wiring.test.mjs +88 -0
  122. package/tests/diagnostics.test.mjs +27 -0
  123. package/tests/embedding-download.test.mjs +44 -0
  124. package/tests/engine-source-settings.test.mjs +69 -0
  125. package/tests/engine-sources.test.mjs +145 -0
  126. package/tests/entity-dedupe.test.mjs +143 -0
  127. package/tests/entity-merge-review.test.mjs +363 -0
  128. package/tests/entity-merge.test.mjs +12 -4
  129. package/tests/entity-review.test.mjs +87 -0
  130. package/tests/environment-check.test.mjs +51 -1
  131. package/tests/feedback.test.mjs +95 -0
  132. package/tests/graph-adjacency-index.test.mjs +536 -0
  133. package/tests/graph-cascade.test.mjs +229 -0
  134. package/tests/graph-import-diagnostic.test.mjs +25 -0
  135. package/tests/graph-overview.test.mjs +709 -0
  136. package/tests/graph-session-authorization.test.mjs +419 -0
  137. package/tests/graph-view-geometry.test.mjs +426 -0
  138. package/tests/graph-view-scale.test.mjs +88 -0
  139. package/tests/graph-view.test.mjs +444 -5
  140. package/tests/graph.test.mjs +43 -0
  141. package/tests/help-page.test.mjs +128 -54
  142. package/tests/inbound.test.mjs +19 -0
  143. package/tests/index-pagination.test.mjs +113 -0
  144. package/tests/index-read-view.test.mjs +212 -0
  145. package/tests/inject-guide.test.mjs +9 -0
  146. package/tests/injection-dedupe.test.mjs +213 -0
  147. package/tests/lexicon-recall.test.mjs +641 -0
  148. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  149. package/tests/lexicon-rt.test.mjs +468 -0
  150. package/tests/local-embedding-worker.test.mjs +38 -0
  151. package/tests/local-vector-service.test.mjs +32 -3
  152. package/tests/maintenance-compat.test.mjs +128 -0
  153. package/tests/maintenance-settlement.test.mjs +1003 -0
  154. package/tests/managed-memory.test.mjs +39 -11
  155. package/tests/managed-runtime.test.mjs +109 -0
  156. package/tests/memory-fields.test.mjs +24 -12
  157. package/tests/observed-evidence.test.mjs +52 -0
  158. package/tests/port-surface.test.mjs +93 -1
  159. package/tests/preset-mount.test.mjs +12 -4
  160. package/tests/recall-cache.test.mjs +56 -3
  161. package/tests/recall-dedup.test.mjs +63 -2
  162. package/tests/retention.test.mjs +260 -0
  163. package/tests/rt-index-cross-library.test.mjs +230 -0
  164. package/tests/rt-index-integration.test.mjs +194 -0
  165. package/tests/rt-index-retention.test.mjs +552 -0
  166. package/tests/rt-index-scale.test.mjs +204 -0
  167. package/tests/rt-index.test.mjs +705 -0
  168. package/tests/salient-date-boundaries.test.mjs +121 -0
  169. package/tests/salient-wake.test.mjs +29 -0
  170. package/tests/scale-bench.test.mjs +53 -0
  171. package/tests/settings-plumbing.test.mjs +25 -0
  172. package/tests/simulate-injection.test.mjs +15 -1
  173. package/tests/standalone-navigation.test.mjs +44 -0
  174. package/tests/state.test.mjs +51 -0
  175. package/tests/temporal-precision.test.mjs +102 -0
  176. package/tests/temporal.test.mjs +10 -6
  177. package/tests/token-measurement.test.mjs +98 -0
  178. package/tests/tool-schema.test.mjs +41 -5
  179. package/tests/tools.test.mjs +6 -3
  180. package/tests/turn-token-budget.test.mjs +149 -0
  181. package/tests/webui-auth.test.mjs +57 -1
  182. package/tests/webui.test.mjs +40 -15
  183. package/tests/worker-lifecycle.test.mjs +2 -1
@@ -0,0 +1,1003 @@
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
+ import crypto from 'node:crypto'
7
+ import { spawn, spawnSync } from 'node:child_process'
8
+
9
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-settlement-'))
10
+ process.env.DSH_MEMU_HOME = home
11
+ process.env.DSH_MEMU_MEMORY_HOME = home
12
+ const state = await import('../lib/state.js')
13
+ const ledger = await import('../lib/maintenance-ledger.js')
14
+ const backup = await import('../lib/backup.js')
15
+ const paths = await import('../lib/paths.js')
16
+ const DAY = 86_400_000
17
+ const NOW = Date.parse('2026-11-30T00:00:00Z')
18
+ const OLD = NOW - 200 * DAY
19
+ const row = (extra = {}) => ({ libraryId: 'lib-fixture', memoryId: 'mem-fixture', reason: 'validity-ended', entryRevision: 'r1', ...extra })
20
+ const key = ledger.maintenanceKey('lib-fixture', 'mem-fixture', 'validity-ended')
21
+ const item = () => ledger.loadMaintenanceLedger().items[key]
22
+ const prune = (extra = {}) => ledger.pruneSettledMaintenanceItems({ now: NOW, olderThanDays: 180, dryRun: true, ...extra })
23
+
24
+ test.after(() => { try { state.flushState() } catch {}; fs.rmSync(home, { recursive: true, force: true }) })
25
+ test.beforeEach(() => ledger.mutateMaintenanceLedger(data => { data.items = {}; data.libraries = {} }))
26
+
27
+ test('a newly settled old candidate starts retention at settlement, not creation', () => {
28
+ ledger.syncMaintenanceCandidates([row()], { now: OLD, scannedLibraries: ['lib-fixture'] })
29
+ ledger.syncMaintenanceCandidates([], { now: NOW, scannedLibraries: ['lib-fixture'] })
30
+ assert.equal(item().createdAt, new Date(OLD).toISOString())
31
+ assert.equal(item().settledAt, new Date(NOW).toISOString())
32
+ assert.deepEqual(prune().candidates, [])
33
+ ledger.syncMaintenanceCandidates([], { now: NOW + DAY, scannedLibraries: ['lib-fixture'] })
34
+ assert.equal(item().settledAt, new Date(NOW).toISOString(), 'rescans do not extend an established settlement clock')
35
+ })
36
+
37
+ test('a settled candidate clears its date when reopened and gets a fresh settlement date', () => {
38
+ ledger.syncMaintenanceCandidates([row()], { now: OLD, scannedLibraries: ['lib-fixture'] })
39
+ ledger.patchMaintenanceItem(key, null, { state: 'settled', lastReviewedAt: new Date(OLD).toISOString() })
40
+ assert.equal(prune().candidates.length, 1)
41
+ ledger.syncMaintenanceCandidates([row({ entryRevision: 'r2' })], { now: NOW - DAY, scannedLibraries: ['lib-fixture'] })
42
+ assert.equal(item().state, 'pending')
43
+ assert.equal(item().settledAt, undefined)
44
+ const claimed = ledger.claimMaintenanceItem(key, { now: NOW, entryRevision: 'r2' })
45
+ ledger.patchMaintenanceItem(key, claimed.lease.jobId, { state: 'settled', lease: null }, { now: NOW })
46
+ assert.equal(item().settledAt, new Date(NOW).toISOString())
47
+ assert.deepEqual(prune().candidates, [])
48
+ })
49
+
50
+ test('legacy settled rows without a valid settlement timestamp fail safe, even after rescans', () => {
51
+ ledger.syncMaintenanceCandidates([row()], { now: OLD, scannedLibraries: ['lib-fixture'] })
52
+ ledger.mutateMaintenanceLedger(data => { data.items[key].state = 'settled'; delete data.items[key].settledAt })
53
+ ledger.syncMaintenanceCandidates([], { now: NOW, scannedLibraries: ['lib-fixture'] })
54
+ assert.equal(item().settledAt, undefined)
55
+ assert.deepEqual(prune().candidates, [])
56
+ for (const bad of ['2026', '2026-02-30T00:00:00.000Z', 'not-a-date']) {
57
+ ledger.mutateMaintenanceLedger(data => { data.items[key].settledAt = bad })
58
+ assert.deepEqual(prune().candidates, [])
59
+ }
60
+ })
61
+
62
+ test('active leases and apply intents veto settlement or retention', () => {
63
+ ledger.syncMaintenanceCandidates([row()], { now: OLD, scannedLibraries: ['lib-fixture'] })
64
+ const claimed = ledger.claimMaintenanceItem(key, { now: NOW, entryRevision: 'r1', leaseMs: DAY })
65
+ ledger.syncMaintenanceCandidates([], { now: NOW, scannedLibraries: ['lib-fixture'] })
66
+ assert.equal(item().state, 'inflight')
67
+ assert.equal(item().lease.jobId, claimed.lease.jobId)
68
+ ledger.patchMaintenanceItem(key, claimed.lease.jobId, { state: 'settled', settledAt: new Date(OLD).toISOString() })
69
+ assert.deepEqual(prune().candidates, [])
70
+ ledger.patchMaintenanceItem(key, claimed.lease.jobId, { lease: null, applyIntent: { action: 'update' } })
71
+ assert.deepEqual(prune({ dryRun: false }).removed, [])
72
+ assert.ok(item().applyIntent)
73
+ })
74
+
75
+ test('retention classifies live, archived and deleted libraries using the current registry', () => {
76
+ const active = state.createLibrary({ name: 'retention-active', scopeKey: path.join(home, 'active') })
77
+ const archived = state.createLibrary({ name: 'retention-archived', scopeKey: path.join(home, 'archived') })
78
+ const deleted = state.createLibrary({ name: 'retention-deleted', scopeKey: path.join(home, 'deleted') })
79
+ state.archiveLibrary(archived.id)
80
+ state.archiveLibrary(deleted.id)
81
+ assert.equal(state.deleteLibrary(deleted.id).ok, true)
82
+ const keys = [active, archived, deleted].map(lib => ledger.maintenanceKey(lib.id, 'mem-fixture', 'validity-ended'))
83
+ ledger.mutateMaintenanceLedger(data => {
84
+ for (const [index, lib] of [active, archived, deleted].entries()) {
85
+ data.items[keys[index]] = row({ key: keys[index], libraryId: lib.id, state: 'settled', settledAt: new Date(OLD).toISOString() })
86
+ }
87
+ // This is a historical fairness clock, not a library registry. Both kinds
88
+ // of stale evidence are deliberate: live ids absent, deleted id present.
89
+ data.libraries = { [deleted.id]: { lastCheckedAt: new Date(NOW).toISOString() } }
90
+ })
91
+ const preview = prune()
92
+ assert.deepEqual(preview.candidates, keys)
93
+ assert.deepEqual(preview.orphanedCandidates, [keys[2]])
94
+ assert.equal(preview.orphanedCandidateCount, 1)
95
+ assert.equal(preview.orphanedRemovedCount, 0)
96
+ const applied = prune({ dryRun: false })
97
+ assert.deepEqual(applied.removed, keys, 'aged metadata is eligible for every library lifecycle state')
98
+ assert.deepEqual(applied.orphanedRemoved, [keys[2]])
99
+ assert.equal(applied.orphanedRemovedCount, 1)
100
+ assert.ok(state.getLibrary(active.id))
101
+ assert.equal(state.getLibrary(archived.id).archived, true)
102
+ })
103
+
104
+ test('retention rechecks registry membership under the ledger lock and skips changed classifications', () => {
105
+ ledger.mutateMaintenanceLedger(data => {
106
+ data.items[key] = row({ key, state: 'settled', settledAt: new Date(OLD).toISOString() })
107
+ })
108
+ let reads = 0
109
+ const result = prune({
110
+ dryRun: false,
111
+ listLibraries: () => {
112
+ reads += 1
113
+ assert.equal(fs.existsSync(ledger.maintenanceLedgerPath() + '.lock'), reads === 2)
114
+ return reads === 1 ? [] : [{ id: 'lib-fixture', archived: true }]
115
+ },
116
+ })
117
+ assert.equal(reads, 2)
118
+ assert.deepEqual(result.orphanedCandidates, [key])
119
+ assert.deepEqual(result.revalidated, [key])
120
+ assert.deepEqual(result.removed, [])
121
+ assert.equal(result.orphanedRemovedCount, 0)
122
+ assert.ok(item())
123
+ })
124
+
125
+ test('retention revalidates the whole candidate after a concurrent rewrite with the same settledAt', t => {
126
+ ledger.mutateMaintenanceLedger(data => {
127
+ data.items[key] = row({ key, state: 'settled', settledAt: new Date(OLD).toISOString() })
128
+ })
129
+ const open = fs.openSync
130
+ const file = ledger.maintenanceLedgerPath()
131
+ let rewritten = false
132
+ let locks = 0
133
+ t.mock.method(fs, 'openSync', (target, ...args) => {
134
+ if (target === path.resolve(file) + '.lock' && ++locks === 2 && !rewritten) {
135
+ rewritten = true
136
+ ledger.mutateMaintenanceLedger(current => { current.items[key].entryRevision = 'rewritten-after-preview' })
137
+ }
138
+ return open(target, ...args)
139
+ })
140
+ const result = prune({ dryRun: false })
141
+ assert.equal(rewritten, true)
142
+ assert.deepEqual(result.revalidated, [key])
143
+ assert.deepEqual(result.removed, [])
144
+ assert.equal(item().entryRevision, 'rewritten-after-preview')
145
+ })
146
+
147
+ test('retention protects apply intents, live leases and unknown dates even after library deletion', () => {
148
+ const kept = {
149
+ intent: { applyIntent: { action: 'update' } },
150
+ lease: { lease: { jobId: 'active', until: new Date(NOW + DAY).toISOString() } },
151
+ legacy: { settledAt: undefined },
152
+ invalid: { settledAt: '2026-02-30T00:00:00.000Z' },
153
+ pending: { state: 'pending' },
154
+ cutoff: { settledAt: new Date(NOW - 180 * DAY).toISOString() },
155
+ future: { settledAt: new Date(NOW + DAY).toISOString() },
156
+ }
157
+ ledger.mutateMaintenanceLedger(data => {
158
+ for (const [id, extra] of Object.entries(kept)) data.items[id] = row({ key: id, state: 'settled', settledAt: new Date(OLD).toISOString(), ...extra })
159
+ data.items.expired = row({ key: 'expired', state: 'settled', settledAt: new Date(OLD).toISOString(), lease: { until: new Date(OLD).toISOString() } })
160
+ })
161
+ const result = prune({ dryRun: false })
162
+ assert.deepEqual(result.removed, ['expired'])
163
+ assert.deepEqual(result.orphanedRemoved, ['expired'])
164
+ assert.deepEqual(Object.keys(ledger.loadMaintenanceLedger().items).sort(), Object.keys(kept).sort())
165
+ })
166
+
167
+ test('a registry read failure aborts retention without changing the ledger', () => {
168
+ ledger.mutateMaintenanceLedger(data => {
169
+ data.items[key] = row({ key, state: 'settled', settledAt: new Date(OLD).toISOString() })
170
+ })
171
+ const before = fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8')
172
+ assert.throws(() => prune({ dryRun: false, listLibraries: () => { throw new Error('registry unavailable') } }), /registry unavailable/)
173
+ assert.equal(fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8'), before)
174
+ })
175
+
176
+ test('registry read-failure fallback is not accepted as an empty live-library catalog', () => {
177
+ const file = path.join(home, 'state.json')
178
+ state.flushState()
179
+ const original = fs.readFileSync(file, 'utf8')
180
+ const before = fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8')
181
+ try {
182
+ fs.writeFileSync(file, '{"libraries":')
183
+ state.clearCaches()
184
+ assert.throws(() => prune({ dryRun: false }), /registry could not be read reliably/)
185
+ assert.equal(fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8'), before)
186
+ } finally {
187
+ fs.writeFileSync(file, original)
188
+ state.clearCaches()
189
+ state.listLibrariesAll()
190
+ }
191
+ })
192
+
193
+ test('registry failure during lock revalidation also leaves candidate metadata intact', () => {
194
+ ledger.mutateMaintenanceLedger(data => {
195
+ data.items[key] = row({ key, state: 'settled', settledAt: new Date(OLD).toISOString() })
196
+ })
197
+ const before = fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8')
198
+ let reads = 0
199
+ assert.throws(() => prune({ dryRun: false, listLibraries: () => {
200
+ if (++reads === 2) throw new Error('registry unavailable under lock')
201
+ return []
202
+ } }), /registry unavailable under lock/)
203
+ assert.equal(reads, 2)
204
+ assert.equal(fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8'), before)
205
+ })
206
+
207
+ test('corrupt maintenance reads never appear as an empty queue or permit a later overwrite', () => {
208
+ ledger.checkpointMaintenanceLedger()
209
+ const file = ledger.maintenanceLedgerPath()
210
+ const original = fs.readFileSync(file, 'utf8')
211
+ const broken = '{"version":1,"items":'
212
+ try {
213
+ fs.writeFileSync(file, broken)
214
+ assert.throws(() => ledger.loadMaintenanceLedger(), /could not be read reliably/)
215
+ assert.throws(() => ledger.mutateMaintenanceLedger(data => { data.items = {} }), /could not be read reliably/)
216
+ assert.equal(fs.existsSync(file), false)
217
+ const quarantined = fs.readdirSync(home).find(name => name.startsWith('maintenance.json.corrupt-'))
218
+ assert.ok(quarantined)
219
+ assert.equal(fs.readFileSync(path.join(home, quarantined), 'utf8'), broken)
220
+ } finally {
221
+ fs.writeFileSync(file, original)
222
+ assert.deepEqual(ledger.loadMaintenanceLedger().items, {})
223
+ }
224
+ })
225
+
226
+ // Persistence tests retain independent temporary data and never start a host.
227
+ const baseline = () => JSON.parse(fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8'))
228
+ const journalBytes = () => fs.readFileSync(ledger.maintenanceJournalPath(), 'utf8')
229
+ const journalRecords = () => journalBytes().trim().split('\n').filter(Boolean).map(line => JSON.parse(line))
230
+ const canonicalHash = value => crypto.createHash('sha256').update(JSON.stringify(value, (_, item) => item && typeof item === 'object' && !Array.isArray(item)
231
+ ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item)).digest('hex')
232
+
233
+ function journalFixture(extra = {}) {
234
+ ledger.mutateMaintenanceLedger(data => { data.items[key] = row({ key, state: 'pending', ...extra }) })
235
+ ledger.checkpointMaintenanceLedger()
236
+ }
237
+
238
+ test('incremental patches preserve the baseline and unrelated metadata while durably saving intents and leases', () => {
239
+ journalFixture()
240
+ ledger.mutateMaintenanceLedger(data => {
241
+ data.items.untouched = row({ memoryId: 'untouched', diagnostic: 'x'.repeat(32_000) })
242
+ data.libraries.untouched = { lastCheckedAt: new Date(OLD).toISOString() }
243
+ data.futureMetadata = { enabled: true }
244
+ })
245
+ ledger.checkpointMaintenanceLedger()
246
+ const before = fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8')
247
+ const intent = { action: 'update', nested: { status: 'done' } }
248
+ const lease = { jobId: 'journal-lease', until: new Date(NOW + DAY).toISOString() }
249
+ ledger.patchMaintenanceItem(key, null, { state: 'inflight', applyIntent: intent, lease })
250
+ assert.equal(fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8'), before, 'a patch does not rewrite the full snapshot')
251
+ assert.ok(Buffer.byteLength(journalBytes()) < 4000, 'the unrelated large row is absent from the patch')
252
+ const records = journalRecords()
253
+ assert.equal(records.length, 1)
254
+ assert.equal(records[0].sequence, 1)
255
+ assert.equal(records[0].parentHash, baseline()._journal.baseHash)
256
+ const { checksum, ...payload } = records[0]
257
+ assert.equal(checksum, canonicalHash(payload))
258
+ assert.deepEqual(item().applyIntent, intent)
259
+ assert.deepEqual(item().lease, lease)
260
+ assert.equal(ledger.loadMaintenanceLedger().items.untouched.diagnostic.length, 32_000)
261
+ assert.equal(ledger.loadMaintenanceLedger().futureMetadata.enabled, true)
262
+ assert.equal(Object.hasOwn(ledger.loadMaintenanceLedger(), '_journal'), false, 'the public v1 logical image remains directly importable')
263
+ ledger.mutateMaintenanceLedger(data => { delete data.items.untouched; delete data.libraries.untouched; delete data.futureMetadata })
264
+ assert.equal(ledger.loadMaintenanceLedger().items.untouched, undefined)
265
+ assert.equal(ledger.loadMaintenanceLedger().libraries.untouched, undefined)
266
+ assert.equal(ledger.loadMaintenanceLedger().futureMetadata, undefined)
267
+ ledger.checkpointMaintenanceLedger()
268
+ assert.deepEqual(baseline().items[key].applyIntent, intent)
269
+ assert.deepEqual(baseline().items[key].lease, lease)
270
+ assert.equal(journalBytes(), '')
271
+ })
272
+
273
+ test('journal recovery survives process restart and preserves exact apply-intent and lease metadata', () => {
274
+ journalFixture()
275
+ const intent = { action: 'update', revision: 'before-effect' }
276
+ ledger.patchMaintenanceItem(key, null, { applyIntent: intent, lease: { jobId: 'persisted-job', until: new Date(NOW + DAY).toISOString() } })
277
+ const child = spawnSync(process.execPath, ['--import', './tests/loader-register.mjs', '--input-type=module', '-e',
278
+ 'const ledger = await import("./lib/maintenance-ledger.js"); process.stdout.write(JSON.stringify(ledger.loadMaintenanceLedger()));'],
279
+ { cwd: process.cwd(), env: { ...process.env, DSH_MEMU_HOME: home, DSH_MEMU_MEMORY_HOME: home }, encoding: 'utf8', timeout: 30_000 })
280
+ assert.equal(child.status, 0, child.stderr)
281
+ const loaded = JSON.parse(child.stdout)
282
+ assert.deepEqual(loaded.items[key].applyIntent, intent)
283
+ assert.equal(loaded.items[key].lease.jobId, 'persisted-job')
284
+ })
285
+
286
+ test('same-path locking and file fsync cover append before mutation returns', t => {
287
+ journalFixture()
288
+ const open = fs.openSync
289
+ const sync = fs.fsyncSync
290
+ let journalFd, flushed = false
291
+ t.mock.method(fs, 'openSync', (file, flags, ...args) => {
292
+ if (file === ledger.maintenanceJournalPath() && flags === 'r+') {
293
+ assert.equal(fs.existsSync(ledger.maintenanceLedgerPath() + '.lock'), true)
294
+ journalFd = open(file, flags, ...args)
295
+ return journalFd
296
+ }
297
+ return open(file, flags, ...args)
298
+ })
299
+ t.mock.method(fs, 'fsyncSync', fd => { if (fd === journalFd) flushed = true; return sync(fd) })
300
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'prepared' } })
301
+ assert.equal(flushed, true)
302
+ assert.ok(item().applyIntent)
303
+ if (process.platform !== 'win32') assert.equal(fs.statSync(ledger.maintenanceJournalPath()).mode & 0o777, 0o600)
304
+ })
305
+
306
+ test('short append writes are completed before the mutation is acknowledged', t => {
307
+ journalFixture()
308
+ const open = fs.openSync
309
+ const write = fs.writeSync
310
+ let journalFd, writes = 0
311
+ t.mock.method(fs, 'openSync', (file, flags, ...args) => {
312
+ const fd = open(file, flags, ...args)
313
+ if (file === ledger.maintenanceJournalPath() && flags === 'r+') journalFd = fd
314
+ return fd
315
+ })
316
+ t.mock.method(fs, 'writeSync', (fd, bytes, offset, length, position) => {
317
+ if (fd === journalFd && Buffer.isBuffer(bytes)) {
318
+ writes += 1
319
+ return write(fd, bytes, offset, Math.min(length, 29), position)
320
+ }
321
+ return write(fd, bytes, offset, length, position)
322
+ })
323
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'short-write-safe' } })
324
+ assert.ok(writes > 1)
325
+ assert.equal(item().applyIntent.action, 'short-write-safe')
326
+ assert.equal(journalRecords().length, 1)
327
+ })
328
+
329
+ test('an interrupted partial append rolls back to its original verified prefix', t => {
330
+ journalFixture()
331
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'committed-before-failure' } })
332
+ const original = journalBytes()
333
+ const open = fs.openSync
334
+ const write = fs.writeSync
335
+ let journalFd, writes = 0
336
+ t.mock.method(fs, 'openSync', (file, flags, ...args) => {
337
+ const fd = open(file, flags, ...args)
338
+ if (file === ledger.maintenanceJournalPath() && flags === 'r+') journalFd = fd
339
+ return fd
340
+ })
341
+ const writeMock = t.mock.method(fs, 'writeSync', (fd, bytes, offset, length, position) => {
342
+ if (fd === journalFd && Buffer.isBuffer(bytes)) {
343
+ if (++writes === 3) throw Object.assign(new Error('injected partial append failure'), { code: 'ENOSPC' })
344
+ return write(fd, bytes, offset, Math.min(length, 19), position)
345
+ }
346
+ return write(fd, bytes, offset, length, position)
347
+ })
348
+ try { assert.throws(() => ledger.patchMaintenanceItem(key, null, { applyIntent: null }), /injected partial append failure/) }
349
+ finally { writeMock.mock.restore() }
350
+ assert.equal(journalBytes(), original)
351
+ assert.equal(item().applyIntent.action, 'committed-before-failure')
352
+ })
353
+
354
+ test('no-op mutations append nothing and a thrown mutator cannot leak partial in-memory edits', () => {
355
+ journalFixture()
356
+ const snapshot = fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8')
357
+ ledger.mutateMaintenanceLedger(() => 'unchanged')
358
+ assert.equal(journalBytes(), '')
359
+ assert.equal(fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8'), snapshot)
360
+ assert.throws(() => ledger.mutateMaintenanceLedger(data => { data.items[key].state = 'settled'; throw new Error('aborted mutation') }), /aborted mutation/)
361
+ assert.equal(item().state, 'pending')
362
+ assert.equal(journalBytes(), '')
363
+ })
364
+
365
+ test('a mutation callback cannot nest a write, restore or checkpoint that invalidates the outer journal', () => {
366
+ journalFixture({ applyIntent: { action: 'outer-protected' } })
367
+ const snapshot = baseline()
368
+ for (const operation of [() => ledger.patchMaintenanceItem(key, null, { applyIntent: null }),
369
+ ledger.checkpointMaintenanceLedger, () => ledger.restoreMaintenanceSnapshot(snapshot)]) {
370
+ assert.throws(() => ledger.mutateMaintenanceLedger(data => { data.items[key].attempts = 50; operation() }), /cannot nest writes or checkpoints/)
371
+ assert.equal(item().applyIntent.action, 'outer-protected')
372
+ assert.equal(item().attempts, undefined)
373
+ assert.equal(journalBytes(), '')
374
+ }
375
+ ledger.patchMaintenanceItem(key, null, { attempts: 1 })
376
+ assert.equal(item().attempts, 1)
377
+ })
378
+
379
+ test('only a final line without its newline commit marker may be trimmed before another append', () => {
380
+ journalFixture()
381
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'must-survive' } })
382
+ const committed = journalBytes()
383
+ const warnings = []
384
+ paths.setWarnSink(message => warnings.push(message))
385
+ try {
386
+ fs.appendFileSync(ledger.maintenanceJournalPath(), '{"version":1,"uncommitted":')
387
+ assert.equal(item().applyIntent.action, 'must-survive')
388
+ assert.equal(journalBytes(), committed + '{"version":1,"uncommitted":', 'a reader does not alter the log')
389
+ ledger.patchMaintenanceItem(key, null, { lastError: null })
390
+ assert.equal(journalRecords().length, 2)
391
+ assert.equal(journalRecords()[1].sequence, 2)
392
+ assert.ok(warnings.some(message => /uncommitted journal tail/.test(message)))
393
+ } finally { paths.setWarnSink(null) }
394
+ })
395
+
396
+ test('valid JSON without a final newline is also uncommitted and cannot clear a prepared intent', () => {
397
+ journalFixture()
398
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'committed' } })
399
+ const committed = journalBytes()
400
+ ledger.patchMaintenanceItem(key, null, { applyIntent: null })
401
+ const uncommitted = journalBytes().slice(committed.length).trimEnd()
402
+ fs.writeFileSync(ledger.maintenanceJournalPath(), committed + uncommitted)
403
+ assert.equal(item().applyIntent.action, 'committed')
404
+ ledger.patchMaintenanceItem(key, null, { attempts: 1 })
405
+ assert.equal(journalRecords().length, 2)
406
+ assert.equal(item().applyIntent.action, 'committed')
407
+ assert.equal(item().attempts, 1)
408
+ })
409
+
410
+ test('a missing anchored journal is refused instead of exposing an older queue', () => {
411
+ journalFixture()
412
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'pending-on-disk' } })
413
+ const file = ledger.maintenanceJournalPath()
414
+ const aside = file + '.missing-test'
415
+ fs.renameSync(file, aside)
416
+ try {
417
+ for (const operation of [ledger.loadMaintenanceLedger, ledger.checkpointMaintenanceLedger,
418
+ () => ledger.patchMaintenanceItem(key, null, { applyIntent: null })]) {
419
+ assert.throws(operation, /anchored snapshot journal is missing/)
420
+ }
421
+ assert.equal(fs.existsSync(file), false)
422
+ } finally { fs.renameSync(aside, file) }
423
+ assert.equal(item().applyIntent.action, 'pending-on-disk')
424
+ })
425
+
426
+ test('a missing baseline never converts a journal containing tasks into a fresh empty store', () => {
427
+ journalFixture()
428
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'baseline-required' } })
429
+ const file = ledger.maintenanceLedgerPath()
430
+ const aside = file + '.missing-test'
431
+ const originalJournal = journalBytes()
432
+ fs.renameSync(file, aside)
433
+ try {
434
+ const protectedRead = error => /journal baseline is missing/.test(error.message)
435
+ || (error.message === 'maintenance ledger could not be read reliably' && Boolean(paths.readFailure(file)))
436
+ assert.throws(ledger.loadMaintenanceLedger, protectedRead)
437
+ assert.throws(() => ledger.mutateMaintenanceLedger(data => { data.items = {} }), protectedRead)
438
+ assert.equal(fs.existsSync(file), false)
439
+ assert.equal(journalBytes(), originalJournal)
440
+ } finally { fs.renameSync(aside, file) }
441
+ assert.equal(item().applyIntent.action, 'baseline-required')
442
+ })
443
+
444
+ test('a changed snapshot is refused while patches are pending, before any record is replayed', () => {
445
+ journalFixture({ applyIntent: { action: 'anchor-protected' } })
446
+ // 契约(2026-12-01 起):只有「journal 为空」时锚点失配才自动重锚(没有待重放的补丁);
447
+ // 一旦有未应用补丁,锚点决定它们属于哪个 base,必须 fail-closed。这里先制造一条待应用补丁。
448
+ ledger.patchMaintenanceItem(key, null, { attempts: 1 })
449
+ const original = fs.readFileSync(ledger.maintenanceLedgerPath())
450
+ for (const kind of ['data', 'generation']) {
451
+ const raw = JSON.parse(original)
452
+ if (kind === 'data') raw.items[key].applyIntent = null
453
+ else raw._journal.generation = crypto.randomUUID()
454
+ try {
455
+ fs.writeFileSync(ledger.maintenanceLedgerPath(), JSON.stringify(raw))
456
+ assert.throws(ledger.loadMaintenanceLedger, /snapshot anchor checksum mismatch/)
457
+ assert.throws(() => ledger.patchMaintenanceItem(key, null, { applyIntent: null }), /snapshot anchor checksum mismatch/)
458
+ } finally { fs.writeFileSync(ledger.maintenanceLedgerPath(), original) }
459
+ }
460
+ assert.equal(item().applyIntent.action, 'anchor-protected')
461
+ })
462
+
463
+ test('a JSON null snapshot is quarantined and remains write-protected until a valid image is restored', () => {
464
+ journalFixture({ applyIntent: { action: 'null-is-not-empty' } })
465
+ const file = ledger.maintenanceLedgerPath()
466
+ const original = fs.readFileSync(file)
467
+ try {
468
+ fs.writeFileSync(file, 'null')
469
+ assert.throws(ledger.loadMaintenanceLedger, /invalid maintenance ledger/)
470
+ assert.throws(() => ledger.mutateMaintenanceLedger(data => { data.items = {} }), /could not be read reliably/)
471
+ assert.equal(fs.existsSync(file), false)
472
+ assert.ok(paths.readFailure(file))
473
+ } finally { fs.writeFileSync(file, original) }
474
+ assert.equal(item().applyIntent.action, 'null-is-not-empty')
475
+ })
476
+
477
+ test('journal IO read failures block mutations without overwriting the unread file', t => {
478
+ journalFixture()
479
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'io-protected' } })
480
+ const original = journalBytes()
481
+ const read = fs.readFileSync
482
+ const mock = t.mock.method(fs, 'readFileSync', (file, ...args) => {
483
+ if (file === ledger.maintenanceJournalPath()) throw Object.assign(new Error('injected read failure'), { code: 'EACCES' })
484
+ return read(file, ...args)
485
+ })
486
+ try {
487
+ for (const operation of [ledger.loadMaintenanceLedger, ledger.checkpointMaintenanceLedger,
488
+ () => ledger.patchMaintenanceItem(key, null, { applyIntent: null })]) {
489
+ assert.throws(operation, error => error.code === 'DSH_MEMU_MAINTENANCE_JOURNAL_IO')
490
+ }
491
+ } finally { mock.mock.restore() }
492
+ assert.equal(journalBytes(), original)
493
+ assert.equal(item().applyIntent.action, 'io-protected')
494
+ })
495
+
496
+ for (const kind of ['checksum', 'sequence', 'parent', 'base', 'operation', 'blank-line', 'invalid-json', 'invalid-utf8']) {
497
+ test(`committed ${kind} damage blocks reads, writes and checkpoints without deleting an intent`, () => {
498
+ journalFixture()
499
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'protected' } })
500
+ ledger.patchMaintenanceItem(key, null, { attempts: 1 })
501
+ const original = fs.readFileSync(ledger.maintenanceJournalPath())
502
+ const records = journalRecords()
503
+ const last = records[1]
504
+ if (kind === 'checksum') last.patch[0].value.attempts = 200
505
+ if (kind === 'sequence') last.sequence = 4
506
+ if (kind === 'parent') last.parentHash = '0'.repeat(64)
507
+ if (kind === 'base') last.baseHash = '1'.repeat(64)
508
+ if (kind === 'operation') last.patch = [{ scope: 'root', key: 'items', op: 'delete' }]
509
+ if (kind !== 'checksum') {
510
+ const { checksum, ...payload } = last
511
+ last.checksum = canonicalHash(payload)
512
+ }
513
+ let broken = Buffer.from(records.map(row => JSON.stringify(row)).join('\n') + '\n')
514
+ if (kind === 'blank-line') broken = Buffer.from(JSON.stringify(records[0]) + '\n\n' + JSON.stringify(records[1]) + '\n')
515
+ if (kind === 'invalid-json') broken = Buffer.from(JSON.stringify(records[0]) + '\n{broken}\n' + JSON.stringify(records[1]) + '\n')
516
+ if (kind === 'invalid-utf8') broken = Buffer.concat([Buffer.from(JSON.stringify(records[0]) + '\n'), Buffer.from([255, 10])])
517
+ const snapshot = fs.readFileSync(ledger.maintenanceLedgerPath())
518
+ const warnings = []
519
+ paths.setWarnSink(message => warnings.push(message))
520
+ try {
521
+ fs.writeFileSync(ledger.maintenanceJournalPath(), broken)
522
+ for (const readOrWrite of [() => ledger.loadMaintenanceLedger(), () => ledger.patchMaintenanceItem(key, null, { applyIntent: null }), () => ledger.checkpointMaintenanceLedger()]) {
523
+ assert.throws(readOrWrite, error => error.code === 'DSH_MEMU_MAINTENANCE_JOURNAL_INVALID')
524
+ }
525
+ assert.deepEqual(fs.readFileSync(ledger.maintenanceJournalPath()), broken)
526
+ assert.deepEqual(fs.readFileSync(ledger.maintenanceLedgerPath()), snapshot)
527
+ assert.ok(warnings.some(message => /writes are blocked/.test(message)))
528
+ } finally {
529
+ paths.setWarnSink(null)
530
+ fs.writeFileSync(ledger.maintenanceJournalPath(), original)
531
+ }
532
+ assert.equal(item().applyIntent.action, 'protected')
533
+ })
534
+ }
535
+
536
+ test('the record-count checkpoint is bounded and leaves the JSON baseline fully readable', () => {
537
+ journalFixture()
538
+ const initial = baseline()._journal.generation
539
+ for (let count = 1; count <= ledger.MAINTENANCE_CHECKPOINT_RECORDS; count += 1) ledger.patchMaintenanceItem(key, null, { attempts: count })
540
+ assert.equal(journalBytes(), '')
541
+ assert.notEqual(baseline()._journal.generation, initial)
542
+ assert.equal(baseline().items[key].attempts, ledger.MAINTENANCE_CHECKPOINT_RECORDS)
543
+ assert.equal(item().attempts, ledger.MAINTENANCE_CHECKPOINT_RECORDS)
544
+ })
545
+
546
+ test('an oversized single patch checkpoints at the byte bound without truncating its metadata', () => {
547
+ journalFixture()
548
+ const intent = { action: 'large-intent', evidence: 'x'.repeat(ledger.MAINTENANCE_CHECKPOINT_BYTES) }
549
+ ledger.patchMaintenanceItem(key, null, { applyIntent: intent })
550
+ assert.equal(journalBytes(), '')
551
+ assert.deepEqual(baseline().items[key].applyIntent, intent)
552
+ assert.deepEqual(item().applyIntent, intent)
553
+ })
554
+
555
+ test('an automatic checkpoint failure preserves the durable commit and blocks growth until checkpoint succeeds', t => {
556
+ journalFixture({ applyIntent: { action: 'survives-deferred-checkpoint' } })
557
+ for (let count = 1; count < ledger.MAINTENANCE_CHECKPOINT_RECORDS; count += 1) ledger.patchMaintenanceItem(key, null, { attempts: count })
558
+ const rename = fs.renameSync
559
+ const mock = t.mock.method(fs, 'renameSync', (from, to) => {
560
+ if (to === ledger.maintenanceLedgerPath()) throw Object.assign(new Error('checkpoint unavailable'), { code: 'EIO' })
561
+ return rename(from, to)
562
+ })
563
+ const warnings = []
564
+ paths.setWarnSink(message => warnings.push(message))
565
+ try {
566
+ assert.doesNotThrow(() => ledger.patchMaintenanceItem(key, null, { attempts: ledger.MAINTENANCE_CHECKPOINT_RECORDS }))
567
+ assert.equal(journalRecords().length, ledger.MAINTENANCE_CHECKPOINT_RECORDS)
568
+ const committed = journalBytes()
569
+ assert.equal(item().attempts, ledger.MAINTENANCE_CHECKPOINT_RECORDS)
570
+ assert.ok(warnings.some(message => /checkpoint deferred after durable append/.test(message)))
571
+ assert.throws(() => ledger.patchMaintenanceItem(key, null, { applyIntent: null }), /checkpoint unavailable/)
572
+ assert.equal(journalBytes(), committed, 'the next append cannot exceed the checkpoint bound')
573
+ assert.equal(item().applyIntent.action, 'survives-deferred-checkpoint')
574
+ } finally { mock.mock.restore(); paths.setWarnSink(null) }
575
+ ledger.patchMaintenanceItem(key, null, { attempts: 1000 })
576
+ assert.equal(item().attempts, 1000)
577
+ assert.equal(item().applyIntent.action, 'survives-deferred-checkpoint')
578
+ assert.equal(journalRecords().length, 1)
579
+ })
580
+
581
+ test('snapshot-rename success followed by rotation failure recovers exactly once', t => {
582
+ journalFixture()
583
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'prepared-once' } })
584
+ const original = journalBytes()
585
+ const rename = fs.renameSync
586
+ const mock = t.mock.method(fs, 'renameSync', (from, to) => {
587
+ if (to === ledger.maintenanceJournalPath()) throw Object.assign(new Error('injected rotate failure'), { code: 'EIO' })
588
+ return rename(from, to)
589
+ })
590
+ assert.throws(() => ledger.checkpointMaintenanceLedger(), /injected rotate failure/)
591
+ mock.mock.restore()
592
+ assert.equal(journalBytes(), original)
593
+ assert.equal(baseline().items[key].applyIntent.action, 'prepared-once')
594
+ assert.equal(item().applyIntent.action, 'prepared-once', 'covered old records are not reapplied')
595
+ ledger.patchMaintenanceItem(key, null, { applyIntent: null, result: 'verified' })
596
+ assert.equal(item().applyIntent, null)
597
+ assert.equal(item().result, 'verified')
598
+ assert.equal(journalRecords().length, 1)
599
+ assert.equal(journalRecords()[0].sequence, 1)
600
+ })
601
+
602
+ test('a failed checkpoint rename leaves every committed journal record recoverable', t => {
603
+ journalFixture()
604
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'before-checkpoint' } })
605
+ const before = fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8')
606
+ const journal = journalBytes()
607
+ const rename = fs.renameSync
608
+ const mock = t.mock.method(fs, 'renameSync', (from, to) => {
609
+ if (to === ledger.maintenanceLedgerPath()) throw Object.assign(new Error('injected snapshot failure'), { code: 'EIO' })
610
+ return rename(from, to)
611
+ })
612
+ assert.throws(() => ledger.checkpointMaintenanceLedger(), /injected snapshot failure/)
613
+ mock.mock.restore()
614
+ assert.equal(fs.readFileSync(ledger.maintenanceLedgerPath(), 'utf8'), before)
615
+ assert.equal(journalBytes(), journal)
616
+ assert.equal(item().applyIntent.action, 'before-checkpoint')
617
+ })
618
+
619
+ test('failed append fsync rolls back to the verified prefix and cannot acknowledge a lost intent', t => {
620
+ journalFixture()
621
+ ledger.patchMaintenanceItem(key, null, { attempts: 1 })
622
+ const original = journalBytes()
623
+ const open = fs.openSync
624
+ const sync = fs.fsyncSync
625
+ let journalFd, failed = false
626
+ const openMock = t.mock.method(fs, 'openSync', (file, flags, ...args) => {
627
+ const fd = open(file, flags, ...args)
628
+ if (file === ledger.maintenanceJournalPath() && flags === 'r+') journalFd = fd
629
+ return fd
630
+ })
631
+ const syncMock = t.mock.method(fs, 'fsyncSync', fd => {
632
+ if (fd === journalFd && !failed) { failed = true; throw Object.assign(new Error('injected fsync failure'), { code: 'EIO' }) }
633
+ return sync(fd)
634
+ })
635
+ assert.throws(() => ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'not-committed' } }), /injected fsync failure/)
636
+ syncMock.mock.restore()
637
+ openMock.mock.restore()
638
+ assert.equal(failed, true)
639
+ assert.equal(journalBytes(), original)
640
+ assert.equal(item().applyIntent, undefined)
641
+ assert.equal(item().attempts, 1)
642
+ })
643
+
644
+ test('a replaced checkpoint file wins over the journal instead of replaying it', () => {
645
+ journalFixture()
646
+ const checkpoint = fs.readFileSync(ledger.maintenanceLedgerPath())
647
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'later-live-intent' } })
648
+ const originalJournal = journalBytes()
649
+ assert.equal(item().applyIntent.action, 'later-live-intent')
650
+ const replacement = ledger.maintenanceLedgerPath() + '.external-restore'
651
+ fs.writeFileSync(replacement, checkpoint)
652
+ fs.renameSync(replacement, ledger.maintenanceLedgerPath())
653
+ // 契约(2026-12-01 起):外部恢复的图像胜过预写日志——不回放、也不锁死。
654
+ // 旧契约是抛 "snapshot file was replaced" 并永久拒绝,结果任何一次复制/重装/旧版写入
655
+ // 都会把这个库变成每 5 分钟一条 DSH_MEMU_MAINTENANCE_JOURNAL_INVALID 的死循环。
656
+ assert.equal(ledger.loadMaintenanceLedger().items[key].applyIntent, undefined,
657
+ 'the restored snapshot wins: the stale journal is never replayed onto it')
658
+ const saved = fs.readdirSync(home).filter(name => name.startsWith('maintenance.journal.jsonl.superseded-'))
659
+ assert.ok(saved.some(name => fs.readFileSync(path.join(home, name), 'utf8') === originalJournal),
660
+ 'the skipped journal is kept as an observable recovery artifact')
661
+ // 写入立即解锁,且被跳过的意图不会被补投回来。
662
+ ledger.patchMaintenanceItem(key, null, { attempts: 2 })
663
+ assert.equal(item().applyIntent, undefined)
664
+ assert.equal(item().attempts, 2)
665
+ })
666
+
667
+ test('checkpointed logical export supports an older full-image writer and a later journal upgrade', () => {
668
+ journalFixture()
669
+ const lease = { jobId: 'legacy-export-lease', until: new Date(NOW + DAY).toISOString() }
670
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'export-protected' }, lease })
671
+ ledger.checkpointMaintenanceLedger()
672
+ const generation = baseline()._journal.generation
673
+ const legacy = ledger.loadMaintenanceLedger()
674
+ assert.equal(Object.hasOwn(legacy, '_journal'), false)
675
+ assert.equal(journalBytes(), '')
676
+ legacy.items[key].attempts = 20
677
+ fs.writeFileSync(ledger.maintenanceLedgerPath(), JSON.stringify(legacy))
678
+ assert.equal(item().attempts, 20)
679
+ assert.equal(item().applyIntent.action, 'export-protected')
680
+ ledger.patchMaintenanceItem(key, null, { attempts: 21 })
681
+ assert.equal(item().attempts, 21)
682
+ assert.equal(item().applyIntent.action, 'export-protected')
683
+ assert.deepEqual(item().lease, lease)
684
+ assert.notEqual(baseline()._journal.generation, generation)
685
+ assert.equal(journalRecords().length, 1)
686
+ })
687
+
688
+ test('managed backup checkpoints the full queue and restore cannot replay a later same-base journal', async () => {
689
+ journalFixture({ state: 'inflight', lease: { jobId: 'backup-live-lease', until: new Date(NOW + DAY).toISOString() } })
690
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'saved-intent' } })
691
+ const dest = await state.backupDatabases({ keep: 10 })
692
+ const snapshot = JSON.parse(fs.readFileSync(path.join(dest, 'maintenance.json'), 'utf8'))
693
+ const manifest = JSON.parse(fs.readFileSync(path.join(dest, 'manifest.json'), 'utf8'))
694
+ assert.ok(manifest.files['maintenance.json'].sha256)
695
+ assert.equal(manifest.files['maintenance.journal.jsonl'], undefined, 'the backup contains a self-contained checkpoint')
696
+ assert.equal(snapshot.items[key].applyIntent.action, 'saved-intent')
697
+ assert.equal(snapshot.items[key].lease.jobId, 'backup-live-lease')
698
+ const backedUpGeneration = snapshot._journal.generation
699
+ ledger.patchMaintenanceItem(key, null, { state: 'settled', applyIntent: null, lease: null }, { now: NOW })
700
+ const staleJournal = journalBytes()
701
+ assert.equal(journalRecords()[0].generation, backedUpGeneration, 'this is the dangerous same-base restore case')
702
+ const result = await state.restoreBackup(path.basename(dest), { keep: 10 })
703
+ assert.ok(result.safety)
704
+ assert.equal(item().applyIntent.action, 'saved-intent')
705
+ assert.equal(item().lease.jobId, 'backup-live-lease')
706
+ assert.equal(item().state, 'inflight')
707
+ assert.notEqual(baseline()._journal.generation, backedUpGeneration)
708
+ const empty = journalBytes()
709
+ assert.equal(empty, '')
710
+ fs.writeFileSync(ledger.maintenanceJournalPath(), staleJournal)
711
+ assert.throws(() => ledger.loadMaintenanceLedger(), /does not match the snapshot generation or base hash/)
712
+ fs.writeFileSync(ledger.maintenanceJournalPath(), empty)
713
+ assert.equal(item().applyIntent.action, 'saved-intent')
714
+ })
715
+
716
+ test('restoring a backup predating maintenance journaling preserves the current pending queue', async () => {
717
+ journalFixture()
718
+ const old = await backup.createBackup({ keep: 10 })
719
+ const manifestFile = path.join(old.dir, 'manifest.json')
720
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'))
721
+ delete manifest.files['maintenance.json']
722
+ fs.writeFileSync(manifestFile, JSON.stringify(manifest))
723
+ fs.unlinkSync(path.join(old.dir, 'maintenance.json'))
724
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'current-pending' }, lease: { jobId: 'held', until: new Date(NOW + DAY).toISOString() } })
725
+ await backup.restoreFromBackup(old.name, { keep: 10 })
726
+ assert.equal(item().applyIntent.action, 'current-pending')
727
+ assert.equal(item().lease.jobId, 'held')
728
+ assert.equal(journalBytes(), '')
729
+ })
730
+
731
+ test('invalid maintenance backup anchor is refused before any live file is replaced', async () => {
732
+ journalFixture()
733
+ const created = await backup.createBackup({ keep: 10 })
734
+ const file = path.join(created.dir, 'maintenance.json')
735
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
736
+ raw._journal.baseHash = '0'.repeat(64)
737
+ fs.writeFileSync(file, JSON.stringify(raw))
738
+ const manifestFile = path.join(created.dir, 'manifest.json')
739
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'))
740
+ manifest.files['maintenance.json'] = { bytes: fs.statSync(file).size, sha256: crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex') }
741
+ fs.writeFileSync(manifestFile, JSON.stringify(manifest))
742
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'live-protected' } })
743
+ const before = fs.readFileSync(ledger.maintenanceLedgerPath())
744
+ const beforeJournal = journalBytes()
745
+ await assert.rejects(() => backup.restoreFromBackup(created.name, { keep: 10 }), /snapshot anchor checksum mismatch/)
746
+ assert.deepEqual(fs.readFileSync(ledger.maintenanceLedgerPath()), before)
747
+ assert.equal(journalBytes(), beforeJournal)
748
+ assert.equal(item().applyIntent.action, 'live-protected')
749
+ })
750
+
751
+ test('a damaged live journal refuses backup publication and managed restore instead of dropping queued work', async () => {
752
+ journalFixture()
753
+ const created = await backup.createBackup({ keep: 10 })
754
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'damaged-but-retained' } })
755
+ const file = ledger.maintenanceJournalPath()
756
+ const original = fs.readFileSync(file)
757
+ const broken = Buffer.concat([original, Buffer.from('{bad committed record}\n')])
758
+ const snapshot = fs.readFileSync(ledger.maintenanceLedgerPath())
759
+ const backupsBefore = backup.listBackupEntries().map(entry => entry.name).sort()
760
+ try {
761
+ fs.writeFileSync(file, broken)
762
+ await assert.rejects(() => state.backupDatabases({ keep: 10 }), error => error.code === 'DSH_MEMU_MAINTENANCE_JOURNAL_INVALID')
763
+ assert.equal(state.lastBackupReportView().status, 'failed')
764
+ await assert.rejects(() => state.restoreBackup(created.name, { keep: 10 }), /no safety backup could be made/)
765
+ assert.deepEqual(backup.listBackupEntries().map(entry => entry.name).sort(), backupsBefore)
766
+ assert.deepEqual(fs.readFileSync(file), broken)
767
+ assert.deepEqual(fs.readFileSync(ledger.maintenanceLedgerPath()), snapshot)
768
+ } finally { fs.writeFileSync(file, original) }
769
+ assert.equal(item().applyIntent.action, 'damaged-but-retained')
770
+ })
771
+
772
+ test('a failed restore retains a complete safety checkpoint that restores the prior intent and live lease', async t => {
773
+ journalFixture({ applyIntent: { action: 'target-backup' } })
774
+ const target = await state.backupDatabases({ keep: 10 })
775
+ const lease = { jobId: 'before-failed-restore', until: new Date(NOW + DAY).toISOString() }
776
+ ledger.patchMaintenanceItem(key, null, { state: 'inflight', applyIntent: { action: 'latest-live-intent' }, lease })
777
+ const rename = fs.renameSync
778
+ const mock = t.mock.method(fs, 'renameSync', (from, to) => {
779
+ if (to === path.join(home, 'state.json') && from.includes('.restore-')) {
780
+ assert.equal(fs.existsSync(ledger.maintenanceLedgerPath() + '.lock'), false, 'large non-maintenance copies do not hold the maintenance file lock')
781
+ throw Object.assign(new Error('injected restore copy failure'), { code: 'EIO' })
782
+ }
783
+ return rename(from, to)
784
+ })
785
+ let caught
786
+ try { await state.restoreBackup(path.basename(target), { keep: 10 }) } catch (error) { caught = error }
787
+ finally { mock.mock.restore() }
788
+ assert.equal(caught?.code, 'DSH_MEMU_BACKUP_RESTORE_FAILED')
789
+ assert.ok(caught.safety)
790
+ const safety = JSON.parse(fs.readFileSync(path.join(home, 'backups', caught.safety, 'maintenance.json'), 'utf8'))
791
+ assert.equal(safety.items[key].applyIntent.action, 'latest-live-intent')
792
+ assert.deepEqual(safety.items[key].lease, lease)
793
+ assert.equal(item().applyIntent.action, 'target-backup', 'the partial restore has a valid fresh maintenance generation')
794
+ const failedGeneration = baseline()._journal.generation
795
+ await state.restoreBackup(caught.safety, { keep: 10 })
796
+ assert.equal(item().applyIntent.action, 'latest-live-intent')
797
+ assert.deepEqual(item().lease, lease)
798
+ assert.equal(item().state, 'inflight')
799
+ assert.notEqual(baseline()._journal.generation, failedGeneration)
800
+ assert.equal(journalBytes(), '')
801
+ })
802
+
803
+ test('backup checkpoint hooks and snapshot copying run under the same maintenance lock', async t => {
804
+ journalFixture()
805
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'hook-protected' } })
806
+ const copy = fs.copyFileSync
807
+ let copied = false, checkpointed = false
808
+ t.mock.method(fs, 'copyFileSync', (from, to, ...args) => {
809
+ if (from === ledger.maintenanceLedgerPath()) {
810
+ assert.equal(checkpointed, true)
811
+ assert.equal(fs.existsSync(ledger.maintenanceLedgerPath() + '.lock'), true)
812
+ copied = true
813
+ }
814
+ return copy(from, to, ...args)
815
+ })
816
+ const created = await backup.createBackup({ keep: 10, checkpointMaintenance: options => {
817
+ assert.equal(fs.existsSync(ledger.maintenanceLedgerPath() + '.lock'), true)
818
+ const result = ledger.checkpointMaintenanceLedger(options)
819
+ checkpointed = true
820
+ return result
821
+ } })
822
+ assert.equal(copied, true)
823
+ assert.equal(JSON.parse(fs.readFileSync(path.join(created.dir, 'maintenance.json'), 'utf8')).items[key].applyIntent.action, 'hook-protected')
824
+ })
825
+
826
+ test('independent writer processes serialize patch sequences without losing either prepared intent', async () => {
827
+ journalFixture()
828
+ const source = 'const ledger = await import("./lib/maintenance-ledger.js"); for (let i = 0; i < 8; i++) ledger.mutateMaintenanceLedger(data => { data.items[process.argv[1] + i] = { state: "inflight", applyIntent: { action: process.argv[1] }, lease: { jobId: process.argv[1] + i, until: "2027-01-01T00:00:00.000Z" } }; });'
829
+ const run = name => new Promise((resolve, reject) => {
830
+ const child = spawn(process.execPath, ['--import', './tests/loader-register.mjs', '--input-type=module', '-e', source, name],
831
+ { cwd: process.cwd(), env: { ...process.env, DSH_MEMU_HOME: home, DSH_MEMU_MEMORY_HOME: home }, stdio: ['ignore', 'ignore', 'pipe'], timeout: 30_000 })
832
+ let stderr = ''
833
+ child.stderr.on('data', chunk => { stderr += chunk })
834
+ child.on('error', reject)
835
+ child.on('close', code => code === 0 ? resolve() : reject(new Error(`writer ${name} exited ${code}: ${stderr}`)))
836
+ })
837
+ await Promise.all([run('writer-a-'), run('writer-b-')])
838
+ const recovered = ledger.loadMaintenanceLedger()
839
+ for (const name of ['writer-a-', 'writer-b-']) for (let i = 0; i < 8; i += 1) {
840
+ assert.equal(recovered.items[name + i].applyIntent.action, name)
841
+ assert.equal(recovered.items[name + i].lease.jobId, name + i)
842
+ }
843
+ const records = journalRecords()
844
+ assert.equal(records.length, 16)
845
+ assert.deepEqual(records.map(record => record.sequence), Array.from({ length: 16 }, (_, index) => index + 1))
846
+ for (let index = 1; index < records.length; index += 1) assert.equal(records[index].parentHash, records[index - 1].checksum)
847
+ })
848
+
849
+ test('a missing checkpoint with an existing empty journal refuses reads, writes, checkpoints and backups', () => {
850
+ // Prior quarantine evidence must not mask this distinct missing-baseline guard.
851
+ const isolated = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-missing-checkpoint-'))
852
+ const env = { ...process.env, DSH_MEMU_HOME: isolated, DSH_MEMU_MEMORY_HOME: isolated }
853
+ const run = source => spawnSync(process.execPath,
854
+ ['--import', './tests/loader-register.mjs', '--input-type=module', '-e', source],
855
+ { cwd: process.cwd(), env, encoding: 'utf8', timeout: 30_000 })
856
+ try {
857
+ const loss = run(`import assert from 'node:assert/strict'; import fs from 'node:fs';
858
+ const l = await import('./lib/maintenance-ledger.js');
859
+ const b = await import('./lib/backup.js');
860
+ l.mutateMaintenanceLedger(data => { data.items.protected = {
861
+ applyIntent: { action: 'checkpointed-intent' }, lease: { jobId: 'checkpointed-lease', until: '2027-01-01T00:00:00.000Z' }
862
+ } });
863
+ l.checkpointMaintenanceLedger();
864
+ const file = l.maintenanceLedgerPath();
865
+ assert.equal(fs.readFileSync(l.maintenanceJournalPath(), 'utf8'), '');
866
+ fs.copyFileSync(file, file + '.saved'); fs.unlinkSync(file);
867
+ for (const action of [l.loadMaintenanceLedger, () => l.mutateMaintenanceLedger(data => { data.items = {} }),
868
+ l.checkpointMaintenanceLedger, () => l.checkpointMaintenanceLedger({ ifExists: true })]) {
869
+ assert.throws(action, /journal baseline is missing/);
870
+ assert.equal(fs.existsSync(file), false);
871
+ }
872
+ await assert.rejects(() => b.createBackup({ keep: 10 }), /journal baseline is missing/);`)
873
+ assert.equal(loss.status, 0, loss.stderr)
874
+ const restarted = run(`import assert from 'node:assert/strict'; import fs from 'node:fs';
875
+ const l = await import('./lib/maintenance-ledger.js');
876
+ assert.throws(l.loadMaintenanceLedger, { code: 'DSH_MEMU_MAINTENANCE_JOURNAL_INVALID' });
877
+ const file = l.maintenanceLedgerPath();
878
+ fs.copyFileSync(file + '.saved', file);
879
+ const item = l.loadMaintenanceLedger().items.protected;
880
+ assert.equal(item.applyIntent.action, 'checkpointed-intent');
881
+ assert.equal(item.lease.jobId, 'checkpointed-lease');`)
882
+ assert.equal(restarted.status, 0, restarted.stderr)
883
+ } finally { fs.rmSync(isolated, { recursive: true, force: true }) }
884
+ })
885
+
886
+ test('a live aged maintenance owner is not evicted and both processes preserve their acknowledged intents', async () => {
887
+ journalFixture()
888
+ const ready = path.join(home, 'aged-writer-ready')
889
+ const resume = path.join(home, 'aged-writer-resume')
890
+ const source = `import fs from 'node:fs'; import path from 'node:path';
891
+ const l = await import('./lib/maintenance-ledger.js');
892
+ l.mutateMaintenanceLedger(data => {
893
+ fs.writeFileSync(${JSON.stringify(ready)}, String(process.pid));
894
+ const deadline = Date.now() + 15000;
895
+ while (!fs.existsSync(${JSON.stringify(resume)})) {
896
+ if (Date.now() > deadline) throw new Error('resume deadline exceeded');
897
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
898
+ }
899
+ data.items['aged-writer-a'] = { applyIntent: { action: 'intent-a' }, lease: { jobId: 'lease-a', until: '2027-01-01T00:00:00.000Z' } };
900
+ });`
901
+ const child = spawn(process.execPath, ['--import', './tests/loader-register.mjs', '--input-type=module', '-e', source],
902
+ { cwd: process.cwd(), env: { ...process.env }, stdio: ['ignore', 'ignore', 'pipe'], timeout: 30_000 })
903
+ let stderr = ''
904
+ child.stderr.on('data', bytes => { stderr += bytes })
905
+ const exited = new Promise((resolve, reject) => { child.on('error', reject); child.on('close', resolve) })
906
+ try {
907
+ const deadline = Date.now() + 10000
908
+ while (!fs.existsSync(ready)) {
909
+ if (child.exitCode !== null || Date.now() > deadline) throw new Error(`writer was not ready: ${stderr}`)
910
+ await new Promise(resolve => setTimeout(resolve, 10))
911
+ }
912
+ const lock = ledger.maintenanceLedgerPath() + '.lock'
913
+ const owner = fs.readFileSync(lock, 'utf8')
914
+ const old = new Date(Date.now() - 61_000)
915
+ fs.utimesSync(lock, old, old)
916
+ assert.throws(() => ledger.mutateMaintenanceLedger(data => { data.items['aged-writer-b'] = { applyIntent: { action: 'intent-b' } } }), { code: 'DSH_MEMU_STORE_BUSY' })
917
+ assert.equal(fs.readFileSync(lock, 'utf8'), owner)
918
+ assert.throws(() => ledger.checkpointMaintenanceLedger(), { code: 'DSH_MEMU_STORE_BUSY' })
919
+ await assert.rejects(() => backup.createBackup({ keep: 10 }), { code: 'DSH_MEMU_STORE_BUSY' })
920
+ } finally {
921
+ fs.writeFileSync(resume, 'resume')
922
+ assert.equal(await exited, 0, stderr)
923
+ fs.rmSync(ready, { force: true }); fs.rmSync(resume, { force: true })
924
+ }
925
+ ledger.mutateMaintenanceLedger(data => { data.items['aged-writer-b'] = { applyIntent: { action: 'intent-b' }, lease: { jobId: 'lease-b' } } })
926
+ const recovered = ledger.loadMaintenanceLedger()
927
+ assert.equal(recovered.items['aged-writer-a'].applyIntent.action, 'intent-a')
928
+ assert.equal(recovered.items['aged-writer-a'].lease.jobId, 'lease-a')
929
+ assert.equal(recovered.items['aged-writer-b'].applyIntent.action, 'intent-b')
930
+ assert.equal(recovered.items['aged-writer-b'].lease.jobId, 'lease-b')
931
+ })
932
+
933
+ test('a displaced maintenance owner refuses its stale append and does not unlink the replacement lock', () => {
934
+ journalFixture({ applyIntent: { action: 'retained-intent' } })
935
+ const lock = ledger.maintenanceLedgerPath() + '.lock'
936
+ const before = journalBytes()
937
+ try {
938
+ assert.throws(() => ledger.mutateMaintenanceLedger(data => {
939
+ data.items[key].applyIntent.action = 'stale-intent'
940
+ fs.unlinkSync(lock)
941
+ fs.writeFileSync(lock, 'replacement owner')
942
+ }), { code: 'DSH_MEMU_STORE_BUSY' })
943
+ assert.equal(fs.readFileSync(lock, 'utf8'), 'replacement owner')
944
+ assert.equal(journalBytes(), before)
945
+ } finally { fs.rmSync(lock, { force: true }) }
946
+ assert.equal(item().applyIntent.action, 'retained-intent')
947
+ })
948
+
949
+ test('unrelated same-process backup operations cannot prune an async restore safety backup', async () => {
950
+ journalFixture({ applyIntent: { action: 'restore-target' } })
951
+ const target = await backup.createBackup({ keep: 10 })
952
+ ledger.patchMaintenanceItem(key, null, { applyIntent: { action: 'before-restore' } })
953
+ let ready, resume, safety
954
+ const entered = new Promise(resolve => { ready = resolve })
955
+ const gate = new Promise(resolve => { resume = resolve })
956
+ const restoring = backup.restoreFromBackup(target.name, { beforeRestore: async () => {
957
+ safety = await backup.createBackup({ keep: 10, label: 'audit-safety' })
958
+ ready()
959
+ await gate
960
+ return safety
961
+ } })
962
+ await entered
963
+ let restored
964
+ try {
965
+ for (let i = 0; i < 3; i++) await assert.rejects(() => backup.createBackup(), { code: 'DSH_MEMU_STORE_BUSY' })
966
+ assert.throws(() => backup.pruneBackups(), { code: 'DSH_MEMU_STORE_BUSY' })
967
+ assert.throws(() => backup.deleteBackupEntry(safety.name), { code: 'DSH_MEMU_STORE_BUSY' })
968
+ assert.ok(fs.existsSync(safety.dir))
969
+ assert.ok(backup.activeLeases()[target.name])
970
+ } finally { resume(); restored = await restoring }
971
+ assert.equal(restored.safety, safety.dir)
972
+ assert.ok(fs.existsSync(restored.safety))
973
+ const saved = JSON.parse(fs.readFileSync(path.join(safety.dir, 'maintenance.json'), 'utf8'))
974
+ assert.equal(saved.items[key].applyIntent.action, 'before-restore')
975
+ assert.equal(item().applyIntent.action, 'restore-target')
976
+ })
977
+
978
+ test('a crash before the backup lock PID write recovers only after the empty-owner grace period', async () => {
979
+ journalFixture()
980
+ const source = `import fs from 'node:fs'; import path from 'node:path';
981
+ const backup = await import('./lib/backup.js');
982
+ const open = fs.openSync, write = fs.writeFileSync; let lockFd;
983
+ fs.openSync = (file, flags, ...args) => {
984
+ const fd = open(file, flags, ...args);
985
+ if (file === path.join(process.env.DSH_MEMU_MEMORY_HOME, 'backups', '.backup.lock')) lockFd = fd;
986
+ return fd;
987
+ };
988
+ fs.writeFileSync = (file, ...args) => { if (file === lockFd) process.exit(73); return write(file, ...args) };
989
+ await backup.createBackup();`
990
+ const child = spawnSync(process.execPath, ['--import', './tests/loader-register.mjs', '--input-type=module', '-e', source],
991
+ { cwd: process.cwd(), env: { ...process.env }, encoding: 'utf8', timeout: 30_000 })
992
+ const lock = path.join(home, 'backups', '.backup.lock')
993
+ try {
994
+ assert.equal(child.status, 73, child.stderr)
995
+ assert.equal(fs.statSync(lock).size, 0)
996
+ await assert.rejects(() => backup.createBackup({ keep: 10 }), { code: 'DSH_MEMU_STORE_BUSY' })
997
+ const old = new Date(Date.now() - 60_000)
998
+ fs.utimesSync(lock, old, old)
999
+ const recovered = await backup.createBackup({ keep: 10 })
1000
+ assert.ok(fs.existsSync(recovered.dir))
1001
+ assert.equal(fs.existsSync(lock), false)
1002
+ } finally { fs.rmSync(lock, { force: true }) }
1003
+ })