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,121 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-date-boundaries-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+ const inject = await import('../lib/inject.js')
13
+ const wake = await import('../lib/salient-wake.js')
14
+ const { fakeScheduleService, wakeContext } = await import('./stubs/dsh-schedule.js')
15
+ const local = (y, m, d, hour = 12) => new Date(y, m - 1, d, hour)
16
+
17
+ test.after(() => {
18
+ try { state.flushState() } finally { fs.rmSync(home, { recursive: true, force: true }) }
19
+ })
20
+ test.afterEach(() => {
21
+ for (const binding of state.listSessionBindings()) state.deleteSessionBinding(binding.sessionId)
22
+ state.updateSettings({ salientWake: 'off', salientWakeHour: '09:00', salientWakeTimeZone: '' })
23
+ })
24
+
25
+ test('short month-days require real calendar dates while retaining leap-day anniversaries', () => {
26
+ for (const [text, expected] of [['2-29', '02-29'], ['02-29', '02-29'], ['4-30', '04-30'], ['12-31', '12-31']]) {
27
+ assert.equal(memory.normalizeSalientDate(text), expected)
28
+ }
29
+ for (const value of ['02-30', '2-31', '04-31', '06-31', '09-31', '11-31', '00-10', '13-01', '01-00']) {
30
+ assert.equal(memory.normalizeSalientDate(value), null, value)
31
+ assert.equal(memory.salientDateFires(value, local(2028, 3, 1)), false, value)
32
+ assert.equal(memory.salientDaysAhead(value, local(2028, 2, 28)), null, value)
33
+ }
34
+ })
35
+
36
+ test('leap-day anniversaries fire only on an actual leap day, including century boundaries', () => {
37
+ for (const year of [2027, 2028, 2099, 2100, 2400]) {
38
+ for (const [month, day] of [[2, 27], [2, 28], [3, 1]]) {
39
+ const now = local(year, month, day)
40
+ assert.equal(memory.salientDateFires('02-29', now), false, `${year}-${month}-${day}`)
41
+ assert.equal(memory.salientDaysAhead('02-29', now), null, 'anniversaries never acquire a fabricated due date')
42
+ }
43
+ }
44
+ for (const year of [2028, 2400]) assert.equal(memory.salientDateFires('02-29', local(year, 2, 29)), true)
45
+ })
46
+
47
+ test('one-off leap dates keep the existing lead window and invalid dates cannot roll over', () => {
48
+ for (const [day, ahead, fires] of [[27, 2, false], [28, 1, true], [29, 0, true]]) {
49
+ assert.equal(memory.salientDaysAhead('2028-02-29', local(2028, 2, day)), ahead)
50
+ assert.equal(memory.salientDateFires('2028-02-29', local(2028, 2, day)), fires)
51
+ }
52
+ assert.equal(memory.salientDaysAhead('2028-02-29', local(2028, 3, 1)), -1)
53
+ assert.equal(memory.salientDateFires('2028-02-29', local(2028, 3, 1)), false)
54
+ for (const bad of ['2027-02-29', '2100-02-29', '2028-02-30', '2028-04-31']) {
55
+ assert.equal(memory.normalizeSalientDate(bad), null, bad)
56
+ assert.equal(memory.salientDaysAhead(bad, local(Number(bad.slice(0, 4)), 2, 28)), null, bad)
57
+ assert.equal(memory.salientDateFires(bad, local(Number(bad.slice(0, 4)), 3, 1)), false, bad)
58
+ }
59
+ assert.equal(memory.normalizeSalientDate('2400-02-29'), '2400-02-29')
60
+ assert.equal(memory.salientDaysAhead('2027-01-01', local(2026, 12, 31)), 1)
61
+ assert.equal(memory.salientDateFires('2027-01-01', local(2026, 12, 31)), true)
62
+ assert.equal(memory.salientDaysAhead('2028-02-29', new Date(NaN)), null)
63
+ assert.equal(memory.salientDateFires('2028-02-29', new Date(NaN)), false)
64
+ })
65
+
66
+ function fixture(id, salientDate) {
67
+ const binding = state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
68
+ state.updatePrivateIndex(binding.libraryId, index => {
69
+ index.entries['boundary-memory'] = {
70
+ track: 'memory', layer: 'long_term', status: 'active', title: 'Boundary date', content: 'A date boundary fixture.',
71
+ salientDate, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
72
+ }
73
+ })
74
+ return binding
75
+ }
76
+
77
+ test('write and update reject impossible short dates without changing the saved anniversary', async () => {
78
+ const id = 'boundary-write'
79
+ const binding = fixture(id, '02-29')
80
+ const exec = { agent: { session: { header: { id } } } }
81
+ await assert.rejects(() => memory.privateRemember({ exec, title: 'Impossible', content: 'An impossible calendar date.', salientDate: '02-30' }), /salient_date/)
82
+ await assert.rejects(() => memory.privateUpdate({ exec, id: 'boundary-memory', salientDate: '04-31' }), /salient_date/)
83
+ assert.equal(state.readPrivateIndex(binding.libraryId).entries['boundary-memory'].salientDate, '02-29')
84
+ })
85
+
86
+ for (const [year, month, day, matches] of [[2027, 2, 28, false], [2027, 3, 1, false], [2028, 2, 28, false], [2028, 2, 29, true], [2028, 3, 1, false], [2100, 2, 28, false], [2100, 3, 1, false], [2400, 2, 29, true]]) {
87
+ test(`injection and scheduled delivery agree on leap anniversary ${year}-${month}-${day}`, async () => {
88
+ const id = `boundary-${year}-${month}-${day}`
89
+ const binding = fixture(id, '02-29')
90
+ const now = local(year, month, day, 8)
91
+ const block = inject.buildAnniversary(id, binding, now)
92
+ assert.deepEqual(block.ids, matches ? ['boundary-memory'] : [])
93
+ if (matches) {
94
+ assert.match(block.text, /memory-anniversary/)
95
+ assert.doesNotMatch(block.text, /memory-due/)
96
+ }
97
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00' })
98
+ const schedule = fakeScheduleService()
99
+ const result = await wake.runSalientWakePass(wakeContext(schedule), { now })
100
+ assert.equal(result.errors || 0, 0)
101
+ const dayKey = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
102
+ const today = schedule.calls.create.find(call => call.title === `memu:due:${id}:${dayKey}`)
103
+ assert.equal(Boolean(today), matches)
104
+ if (matches) assert.match(today.prompt, /每年 02-29/)
105
+ if (year === 2028 && month === 2 && day === 28) {
106
+ assert.deepEqual(schedule.calls.create.map(call => call.timing.at.date), ['2028-02-29'], 'advance scheduling does not advance anniversary delivery')
107
+ } else if (!matches) assert.equal(schedule.calls.create.length, 0)
108
+ })
109
+ }
110
+
111
+ test('persisted invalid one-offs are rejected by both injection and scheduled wake', async () => {
112
+ const id = 'boundary-invalid-oneoff'
113
+ const binding = fixture(id, '2027-02-29')
114
+ const now = local(2027, 2, 28, 8)
115
+ assert.deepEqual(inject.buildAnniversary(id, binding, now).ids, [])
116
+ state.updateSettings({ salientWake: 'schedule' })
117
+ const schedule = fakeScheduleService()
118
+ const result = await wake.runSalientWakePass(wakeContext(schedule), { now })
119
+ assert.equal(result.created, 0)
120
+ assert.equal(schedule.calls.create.length, 0)
121
+ })
@@ -387,3 +387,32 @@ test('a slot already past in the delivery zone is skipped, not sent for rejectio
387
387
  assert.equal(result.created, 0, '19:00 UTC on 10-31 already passed; passive injection still covers it')
388
388
  assert.equal(result.skipped, 1)
389
389
  })
390
+
391
+ test('schedule pagination reads every page beyond the 500-task limit', async () => {
392
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00', salientWakeTimeZone: 'UTC' })
393
+ const { sessionId, binding } = newSession('wake-over-500')
394
+ putEntry(binding.libraryId, 'mem-over-500', { salientDate: '2026-11-02' })
395
+ const schedule = fakeScheduleService()
396
+ for (let index = 0; index < 1001; index += 1) schedule.seed({ title: `unrelated-${index}` })
397
+ const result = await run(schedule, new Date(Date.UTC(2026, 10, 2, 8, 0, 0, 0)))
398
+ assert.equal(result.created, 1)
399
+ assert.ok(schedule.taskByTitle(`memu:due:${sessionId}:2026-11-02`))
400
+ assert.deepEqual(schedule.calls.list.map(request => request.offset), [0, 500, 1000])
401
+ assert.deepEqual(schedule.calls.list.map(request => request.limit), [500, 500, 500])
402
+ })
403
+
404
+ test('an old host that ignores offset stops before schedule side effects', async () => {
405
+ state.updateSettings({ salientWake: 'schedule', salientWakeHour: '09:00', salientWakeTimeZone: 'UTC' })
406
+ const { binding } = newSession('wake-offset-ignored')
407
+ putEntry(binding.libraryId, 'mem-offset-ignored', { salientDate: '2026-11-02' })
408
+ const full = fakeScheduleService()
409
+ for (let index = 0; index < 501; index += 1) full.seed({ title: `unrelated-${index}` })
410
+ const schedule = { ...full, list: request => full.list({ limit: request.limit, offset: 0 }) }
411
+ const logs = []
412
+ const result = await run(schedule, new Date(Date.UTC(2026, 10, 2, 8, 0, 0, 0)), message => logs.push(message))
413
+ assert.equal(result.created, 0)
414
+ assert.equal(result.paginationIncomplete, true)
415
+ assert.equal(full.calls.create.length, 0)
416
+ assert.equal(full.calls.edit.length, 0)
417
+ assert.ok(logs.some(message => /did not honor offset 500/.test(message)))
418
+ })
@@ -0,0 +1,53 @@
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 { spawnSync } from 'node:child_process'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const script = fileURLToPath(new URL('../scripts/scale-bench.mjs', import.meta.url))
10
+
11
+ test('scale bench isolates caller home and reports excluded or missing operations explicitly', () => {
12
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-scale-test-'))
13
+ try {
14
+ const callerHome = path.join(root, 'caller-home')
15
+ fs.mkdirSync(callerHome)
16
+ fs.writeFileSync(path.join(callerHome, 'sentinel.txt'), 'untouched')
17
+ const output = path.join(root, 'result')
18
+ const run = spawnSync(process.execPath, [script, '--sizes', '10', '--samples', '3', '--operations', 'hotRead', '--out', output], {
19
+ env: { ...process.env, DSH_MEMU_HOME: callerHome }, encoding: 'utf8', timeout: 60000,
20
+ })
21
+ assert.equal(run.status, 0, run.stderr)
22
+ const report = JSON.parse(fs.readFileSync(output + '.json', 'utf8'))
23
+ assert.equal(report.gold, false)
24
+ assert.equal(report.sourceStable, true)
25
+ assert.equal(report.sourceFingerprintAfter, report.sourceFingerprint)
26
+ assert.ok(report.sourceFiles.includes('lib/graph-adjacency-index.js'))
27
+ assert.ok(report.sourceFiles.includes('lib/lexicon-rt.js'))
28
+ assert.ok(report.sourceFiles.includes('lib/webui/graph-view.bundle.js'))
29
+ assert.equal(report.seed, 1444)
30
+ assert.deepEqual(report.operations, ['hotRead'])
31
+ assert.equal(report.results.length, 1)
32
+ const row = report.results[0]
33
+ assert.equal(row.count, 10)
34
+ assert.equal(row.metrics.hotRead.samples, 3)
35
+ assert.ok(row.metrics.hotRead.p95Ms >= row.metrics.hotRead.p50Ms)
36
+ for (const name of ['coldLoad', 'hotMutableLoad', 'lexicalRecall', 'privateList', 'browseWall', 'getGraph', 'remember']) {
37
+ assert.equal(row.metrics[name].unavailable, true)
38
+ assert.match(row.metrics[name].reason, /not measured/)
39
+ }
40
+ assert.equal(row.metrics.getGraphOverview.unavailable, true)
41
+ assert.match(row.metrics.getGraphOverview.reason, /not implemented|not measured/)
42
+ assert.ok(row.cache.index.bytes <= row.cache.index.maxBytes)
43
+ assert.match(fs.readFileSync(output + '.md', 'utf8'), /not measured/)
44
+ assert.deepEqual(fs.readdirSync(callerHome), ['sentinel.txt'])
45
+ assert.equal(fs.readFileSync(path.join(callerHome, 'sentinel.txt'), 'utf8'), 'untouched')
46
+ } finally { fs.rmSync(root, { recursive: true, force: true }) }
47
+ })
48
+
49
+ test('scale bench rejects an unknown operation before constructing fixtures', () => {
50
+ const run = spawnSync(process.execPath, [script, '--operations', 'unrecognised'], { encoding: 'utf8', timeout: 10000 })
51
+ assert.equal(run.status, 1)
52
+ assert.match(run.stderr, /invalid --operations/)
53
+ })
@@ -24,11 +24,33 @@ const SAMPLE = {
24
24
  freshnessHint: false,
25
25
  freshnessDays: 90,
26
26
  crossLibraryRecall: true,
27
+ relevanceThreshold: 0.65,
28
+ midTurnRecall: false,
29
+ midTurnMinSteps: 9,
30
+ midTurnMinUnits: 4,
31
+ midTurnMinChars: 9000,
32
+ midTurnMaxPerTurn: 3,
33
+ midTurnCooldownMs: 90000,
34
+ midTurnTokens: 650,
35
+ midTurnFullUnits: 8,
36
+ midTurnFullChars: 21000,
27
37
  salientWake: 'schedule',
28
38
  salientWakeHour: '20:30',
29
39
  salientWakeTimeZone: 'Asia/Shanghai',
30
40
  // 升级自愈的 kill switch:默认 true,这里必须能写成 false 才算「可关」不是空话。
31
41
  autoRepairEntityFragments: false,
42
+ retentionDryRun: false,
43
+ retentionBoundTurnLogsEnabled: false,
44
+ retentionBoundTurnLogDays: 45,
45
+ retentionOrphanTurnLogsEnabled: true,
46
+ retentionOrphanTurnLogDays: 120,
47
+ retentionMaintenanceLedgerEnabled: false,
48
+ retentionMaintenanceLedgerDays: 240,
49
+ retentionSessionBindingsEnabled: true,
50
+ retentionSessionBindingDays: 365,
51
+ retentionVectorPruneEnabled: false,
52
+ retentionVectorKeepGenerations: 3,
53
+ retentionVectorDays: 14,
32
54
  }
33
55
 
34
56
  test('each new setting is writable through setSettings', async () => {
@@ -76,4 +98,7 @@ test('the client settings page exposes a control for every new setting', () => {
76
98
  for (const key of Object.keys(SAMPLE)) {
77
99
  assert.match(source, new RegExp("setSetting\\('" + key + "'"), key + ' has no settings control')
78
100
  }
101
+ assert.match(source, /settingsGroupRetention/)
102
+ assert.match(source, /retentionDryRun: '保留清理仅预览/)
103
+ assert.match(source, /retentionDryRun: 'Retention cleanup is preview-only/)
79
104
  })
@@ -63,8 +63,22 @@ test('a zero cue chance is the reproducible default and --cue can restore the sh
63
63
  assert.equal(summary.deltaTotals.cue, 0)
64
64
  })
65
65
 
66
+ test('long tool rounds keep title cards intact and share the turn token budget', () => {
67
+ const summary = JSON.parse(run(['--turns', '5', '--tool-steps', '9', '--json', '--out', path.join(home, 'run-long'), '--home', path.join(home, 'home-long')]))
68
+ assert.equal(summary.toolSteps, 9)
69
+ assert.ok(summary.midTurnInjections > 0)
70
+ assert.equal(summary.tokenBudget.violations, 0)
71
+ assert.ok(summary.tokenBudget.maximumTurnEstimated <= summary.tokenBudget.limit)
72
+ assert.equal(summary.tokenBudget.actual, 'unverified')
73
+ assert.equal(summary.titleCardBodyLineMax, 0)
74
+ assert.equal(summary.warnCount, 0)
75
+ const rows = JSON.parse(fs.readFileSync(summary.tokenBudget.path, 'utf8')).turnBudgets
76
+ assert.equal(rows.length, 5)
77
+ assert.ok(rows.every(row => row.estimated <= row.limit && row.memoryActual === null))
78
+ })
79
+
66
80
  test('usage errors exit 2 and never write a library', () => {
67
- for (const args of [['--turns', '0'], ['--turns', '501'], ['--cue', '2'], ['--nope']]) {
81
+ for (const args of [['--turns', '0'], ['--turns', '501'], ['--cue', '2'], ['--tool-steps', '-1'], ['--tool-steps', '41'], ['--nope']]) {
68
82
  let code = 0
69
83
  try {
70
84
  execFileSync(process.execPath, [SCRIPT, ...args], { cwd: REPO, stdio: 'pipe' })
@@ -0,0 +1,44 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import vm from 'node:vm'
5
+
6
+ const source = fs.readFileSync(new URL('../lib/webui/standalone.js', import.meta.url), 'utf8')
7
+
8
+ function shell(language, hash) {
9
+ const events = new Map()
10
+ const labels = { pageLabel: {}, hashLabel: {} }
11
+ const document = {
12
+ documentElement: { dataset: { theme: 'light' }, style: { setProperty() {} } },
13
+ body: { dataset: {} },
14
+ querySelectorAll: () => [], querySelector: () => null,
15
+ getElementById: id => labels[id] || null,
16
+ }
17
+ const window = {
18
+ location: { hash, search: '' }, history: { length: 1 }, scrollY: 0,
19
+ matchMedia: () => ({ matches: false, addEventListener() {} }),
20
+ addEventListener: (name, fn) => events.set(name, fn),
21
+ }
22
+ window.self = window
23
+ window.top = window
24
+ vm.runInNewContext(source, { window, document, navigator: { language }, URLSearchParams, console })
25
+ return { window, document, labels, navigate(hash) { window.location.hash = hash; events.get('hashchange')() } }
26
+ }
27
+
28
+ test('standalone diagnostic navigation keeps the actual page label and document title in both languages', () => {
29
+ for (const [language, diagnostic, help, brand] of [
30
+ ['zh-CN', '诊断', '帮助', 'MemU 记忆'],
31
+ ['en-US', 'Diagnostics', 'Help', 'MemU Memory'],
32
+ ]) {
33
+ const page = shell(language, '#/settings/diagnostics')
34
+ assert.equal(page.labels.pageLabel.textContent, diagnostic)
35
+ assert.equal(page.labels.hashLabel.textContent, '#/settings/diagnostics')
36
+ assert.equal(page.document.title, diagnostic + ' · ' + brand)
37
+ page.navigate('#/settings/help')
38
+ assert.equal(page.labels.pageLabel.textContent, help)
39
+ page.navigate('#/settings/diagnostics')
40
+ assert.equal(page.document.title, diagnostic + ' · ' + brand)
41
+ page.navigate('#/settings/not-a-page')
42
+ assert.equal(page.labels.hashLabel.textContent, '#/settings/memories')
43
+ }
44
+ })
@@ -13,6 +13,21 @@ test.after(() => {
13
13
  try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
14
14
  })
15
15
 
16
+ test('rollback cannot revive a timestamp already evicted from the injection window', () => {
17
+ const sessionId = 'state-cap-rollback'
18
+ const binding = state.ensureSession(sessionId, { cwd: path.join(home, sessionId) })
19
+ state.markInjected(sessionId, ['mem-old'], 1)
20
+ state.markInjectedRefs(sessionId, [{ scope: 'private', libraryId: binding.libraryId, id: 'mem-old' }], 2, {
21
+ messageId: 'cap-rollback-message', hostTurn: 2,
22
+ })
23
+ state.markInjected(sessionId, Array.from({ length: 400 }, (_, i) => `mem-new-${i}`), 3)
24
+ state.rollbackInjectionForTurn(sessionId, 2, { messageIds: ['cap-rollback-message'] })
25
+ const after = state.getSessionBinding(sessionId)
26
+ assert.equal(after.injectedAt['mem-old'], undefined)
27
+ assert.equal(Object.keys(after.injectedAt).length, 400)
28
+ assert.deepEqual(new Set(Object.keys(after.injectedAt)), new Set(after.injectedIds))
29
+ })
30
+
16
31
  test('same cwd auto-binds to the same library', () => {
17
32
  const cwd = path.join(home, 'project-a')
18
33
  const a = state.ensureSession('state-a', { cwd, agentPreset: 'coding' })
@@ -150,6 +165,42 @@ test('a fresh install starts with the four conveniences enabled', () => {
150
165
  assert.equal(settings.sleepConsolidation, true)
151
166
  })
152
167
 
168
+ test('folder backfill binds only opted-in sessions when the library already exists', () => {
169
+ const cwd = path.join(home, 'backfill-existing')
170
+ const scopeKey = state.normalizeCwd(cwd)
171
+ const library = state.createLibrary({ cwd })
172
+ state.setSessionBinding('backfill-yes', { scopeKey, useLibrary: true, libraryId: null })
173
+ state.setSessionBinding('backfill-no', { scopeKey, useLibrary: false, libraryId: null })
174
+ state.setWorkspacePolicy(cwd, { useLibrary: true })
175
+ assert.equal(state.getSessionBinding('backfill-yes').libraryId, library.id, 'the loop must reach the normalized scope')
176
+ assert.equal(state.getSessionBinding('backfill-no').libraryId, null, 'the same loop must respect an explicit opt-out')
177
+ assert.equal(state.getSessionBinding('backfill-no').useLibrary, false)
178
+ })
179
+
180
+ test('both injection paths bound timestamps to the 400 retained memory ids', () => {
181
+ for (const typed of [false, true]) {
182
+ const sessionId = typed ? 'bounded-typed' : 'bounded-legacy'
183
+ state.ensureSession(sessionId, { cwd: path.join(home, sessionId) })
184
+ const ids = Array.from({ length: 405 }, (_, i) => `bounded-${i}`)
185
+ state.setSessionBinding(sessionId, { injectedAt: { obsolete: 0, __anchor__: 0 } })
186
+ if (typed) {
187
+ const refs = ids.map(id => ({ scope: 'global', id, revision: 'r1' }))
188
+ state.markInjectedRefs(sessionId, refs, 10, { messageId: `${sessionId}-first`, actions: { anchor: true } })
189
+ } else state.markInjected(sessionId, ['__anchor__', ...ids], 10)
190
+ let binding = state.getSessionBinding(sessionId)
191
+ assert.deepEqual(binding.injectedIds, ids.slice(-400))
192
+ assert.deepEqual(Object.keys(binding.injectedAt), ids.slice(-400))
193
+ assert.equal(binding.anchorPushed, true, 'anchor admission survives timestamp pruning')
194
+ if (typed) state.markInjectedRefs(sessionId, [{ scope: 'global', id: 'bounded-next', revision: 'r2' }], 11, { messageId: `${sessionId}-next` })
195
+ else state.markInjected(sessionId, ['bounded-next'], 11)
196
+ binding = state.getSessionBinding(sessionId)
197
+ assert.equal(Object.keys(binding.injectedAt).length, 400)
198
+ assert.equal(binding.injectedAt['bounded-5'], undefined, 'evicted ids lose timestamps too')
199
+ assert.equal(binding.injectedAt['bounded-next'], 11)
200
+ assert.equal(binding.injectedAt['bounded-404'], 10, 'retained timestamps keep their clocks')
201
+ }
202
+ })
203
+
153
204
  test('vision descriptions are enabled by default and stay inert until an endpoint is configured', () => {
154
205
  assert.equal(state.getSettings().visionCaptionEnabled, true)
155
206
  })
@@ -0,0 +1,102 @@
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 { parseTemporalExpression, hasTemporalHint, resolveQueryDates } from '../lib/temporal.js'
7
+
8
+ const NOW = new Date('2026-11-06T04:00:00Z')
9
+ for (const [text, precision, prefix] of [
10
+ ['明年', 'year', '2027'], ['去年', 'year', '2025'], ['前年', 'year', '2024'], ['后年', 'year', '2028'],
11
+ ['月初', 'month', '2026-11'], ['月底', 'month', '2026-11'], ['下个月', 'month', '2026-12'], ['上个月', 'month', '2026-10'],
12
+ ['年初', 'year', '2026'], ['明年底', 'year', '2027'], ['2027年', 'year', '2027'], ['2027年2月', 'month', '2027-02'],
13
+ ['明年5月', 'month', '2027-05'],
14
+ ]) {
15
+ test(`partial date keeps its true precision: ${text}`, () => {
16
+ assert.equal(hasTemporalHint(text), true)
17
+ const parsed = parseTemporalExpression(text, { now: NOW })
18
+ assert.ok(parsed)
19
+ assert.equal(parsed.absoluteDate, null)
20
+ assert.equal(parsed.precision, precision)
21
+ assert.equal(parsed.datePrefix, prefix)
22
+ assert.deepEqual(resolveQueryDates(text, { now: NOW }), [prefix])
23
+ })
24
+ }
25
+
26
+ test('relative year/month expressions with explicit days still resolve valid days', () => {
27
+ assert.equal(parseTemporalExpression('明年5月3日', { now: NOW }).absoluteDate, '2027-05-03')
28
+ assert.equal(parseTemporalExpression('上个月15号', { now: NOW }).absoluteDate, '2026-10-15')
29
+ assert.equal(parseTemporalExpression('明年2月30号', { now: NOW }), null)
30
+ assert.equal(parseTemporalExpression('下个月', { now: new Date('2026-12-31T04:00:00Z') }).datePrefix, '2027-01')
31
+ })
32
+
33
+ test('relative periods cross year and leap boundaries without inventing a day', () => {
34
+ for (const [text, now, prefix, precision] of [
35
+ ['下个月复诊', '2027-12-31T04:00:00Z', '2028-01', 'month'],
36
+ ['上个月对账', '2028-01-01T04:00:00Z', '2027-12', 'month'],
37
+ ['下个月底', '2028-01-31T04:00:00Z', '2028-02', 'month'],
38
+ ['明年体检', '2028-02-29T04:00:00Z', '2029', 'year'],
39
+ ['前年旧事', '2028-01-01T04:00:00Z', '2026', 'year'],
40
+ ['明年年底', '2026-12-31T04:00:00Z', '2027', 'year'],
41
+ ]) {
42
+ const options = { now: new Date(now) }
43
+ const result = parseTemporalExpression(text, options)
44
+ assert.equal(hasTemporalHint(text), true, text)
45
+ assert.equal(result.absoluteDate, null, text)
46
+ assert.equal(result.precision, precision, text)
47
+ assert.deepEqual(resolveQueryDates(text, options), [prefix], text)
48
+ }
49
+ })
50
+
51
+ test('invalid leap days stay unresolved instead of becoming a month, year or rolled day', () => {
52
+ for (const [text, now] of [
53
+ ['2027年2月29日', '2026-11-06T04:00:00Z'],
54
+ ['2100-02-29', '2099-11-06T04:00:00Z'],
55
+ ['明年2月29日', '2028-11-06T04:00:00Z'],
56
+ ['下个月29号', '2027-01-31T04:00:00Z'],
57
+ ['上个月31号', '2028-03-31T04:00:00Z'],
58
+ ]) {
59
+ const options = { now: new Date(now) }
60
+ assert.equal(hasTemporalHint(text), true, text)
61
+ assert.equal(parseTemporalExpression(text, options), null, text)
62
+ assert.deepEqual(resolveQueryDates(text, options), [], text)
63
+ }
64
+ assert.equal(parseTemporalExpression('明年2月29日', { now: new Date('2027-11-06T04:00:00Z') }).absoluteDate, '2028-02-29')
65
+ assert.equal(parseTemporalExpression('2400年2月29日', { now: NOW }).absoluteDate, '2400-02-29')
66
+ })
67
+
68
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-temporal-precision-'))
69
+ process.env.DSH_MEMU_HOME = home
70
+ const state = await import('../lib/state.js')
71
+ const memory = await import('../lib/memory.js')
72
+ const activity = await import('../lib/activity-log.js')
73
+ state.ensureSession('precision', { cwd: path.join(home, 'precision'), agentPreset: 'coding' })
74
+ state.setSessionBinding('precision', { sceneTime: NOW.toISOString() })
75
+ const exec = { agent: { session: { header: { id: 'precision' } } } }
76
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
77
+
78
+ test('write paths never turn year/month prose into an absolute day', async () => {
79
+ for (const text of ['明年体检', '前年旧事', '月初对账', '下个月复诊']) {
80
+ const result = await memory.privateRemember({ exec, title: text, content: text + ',这里只知道期间,没有具体日。' })
81
+ assert.equal(result.entry.absolute_date, undefined)
82
+ assert.ok(['year', 'month'].includes(result.entry.date_precision))
83
+ assert.equal(result.entry.salientDate ?? null, null)
84
+ }
85
+ const saved = await memory.privateRemember({ exec, title: '原日程', content: '原先确定在明天交付。' })
86
+ assert.equal(saved.entry.absolute_date, '2026-11-07')
87
+ const changed = await memory.privateUpdate({ exec, id: saved.id, title: '改期未定', content: '现在改到明年处理,仅知道年份。' })
88
+ assert.equal(changed.entry.absolute_date, undefined, 'a partial rewrite clears an unsupported old exact day')
89
+ assert.equal(changed.entry.date_precision, 'year')
90
+ })
91
+
92
+ test('unresolved date hints emit a privacy-safe warning instead of silently inventing a day', async () => {
93
+ const secretText = '下周再谈私密合成计划XYZ。'
94
+ const result = await memory.privateRemember({ exec, title: '待定安排', content: secretText })
95
+ assert.equal(result.entry.absolute_date, undefined)
96
+ assert.equal(result.entry.date_precision, 'unknown')
97
+ const event = activity.listEvents({}).find(row => row.detail?.code === 'TEMPORAL_PARSE_UNRESOLVED')
98
+ assert.ok(event)
99
+ assert.equal(event.level, 'warn')
100
+ assert.equal(event.ok, false)
101
+ assert.equal(JSON.stringify(event).includes(secretText), false)
102
+ })
@@ -52,17 +52,21 @@ test('week phrases use Monday-based weeks and never guess a bare weekday', () =>
52
52
  assert.equal(dateOf('周三见'), null)
53
53
  })
54
54
 
55
- test('month, month-end and year boundaries resolve to a concrete day', () => {
55
+ test('only day precision produces a concrete day; month and year keep their prefix', () => {
56
56
  assert.equal(dateOf('下个月15号'), '2026-12-15')
57
57
  assert.equal(dateOf('本月6号'), '2026-11-06')
58
58
  const monthEnd = parse('月底')
59
- assert.equal(monthEnd.absoluteDate, '2026-11-30')
59
+ assert.equal(monthEnd.absoluteDate, null)
60
+ assert.equal(monthEnd.datePrefix, '2026-11')
60
61
  assert.equal(monthEnd.precision, 'month')
61
- assert.equal(dateOf('下月底'), '2026-12-31')
62
+ assert.equal(dateOf('下月底'), null)
63
+ assert.equal(parse('下月底').datePrefix, '2026-12')
62
64
  const yearStart = parse('年初')
63
- assert.equal(yearStart.absoluteDate, '2026-01-01')
65
+ assert.equal(yearStart.absoluteDate, null)
66
+ assert.equal(yearStart.datePrefix, '2026')
64
67
  assert.equal(yearStart.precision, 'year')
65
- assert.equal(dateOf('年底'), '2026-12-31')
68
+ assert.equal(dateOf('年底'), null)
69
+ assert.equal(parse('年底').datePrefix, '2026')
66
70
  })
67
71
 
68
72
  test('impossible dates are refused instead of guessed', () => {
@@ -104,7 +108,7 @@ test('the time zone changes what "today" means', () => {
104
108
  test('all expressions can be extracted for query expansion', () => {
105
109
  const all = extractTemporalExpressions('昨天她说下周三见面,月底再确认', { now: NOW })
106
110
  assert.deepEqual(all.map((item) => item.sourceText), ['昨天', '下周三', '月底'])
107
- assert.deepEqual(resolveQueryDates('昨天她说下周三见面,月底再确认', { now: NOW }), ['2026-11-05', '2026-11-11', '2026-11-30'])
111
+ assert.deepEqual(resolveQueryDates('昨天她说下周三见面,月底再确认', { now: NOW }), ['2026-11-05', '2026-11-11', '2026-11'])
108
112
  assert.deepEqual(resolveQueryDates('没有日期的句子', { now: NOW }), [])
109
113
  })
110
114
 
@@ -0,0 +1,98 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { createTurnTokenLedger, createDomainOutputFactors, tokenRatioBucket, requestTokenUsage } from '../lib/token-measurement.js'
4
+ import { estTokens } from '../lib/budget.js'
5
+
6
+ test('one turn reserves first-step, guide and mid-turn against one allowance', () => {
7
+ const ledger = createTurnTokenLedger()
8
+ assert.equal(ledger.reserve('s', 1, 'first', '中'.repeat(80), 100), true)
9
+ assert.equal(ledger.reserve('s', 1, 'guide', '中'.repeat(15), 100), true)
10
+ assert.equal(ledger.reserve('s', 1, 'mid', '提示卡', 100), true)
11
+ assert.equal(ledger.reserve('s', 1, 'over', '完整提示卡', 100), false)
12
+ assert.equal(ledger.snapshot('s', 1, 100).estimated, 98)
13
+ assert.equal(ledger.reserve('s', 1, 'first', '中'.repeat(80), 100), true, 'same proposal is idempotent')
14
+ assert.equal(ledger.room('s', 1, 100), 2)
15
+ assert.equal(ledger.room('s', 2, 100), 100, 'new human turn has a fresh allowance')
16
+ })
17
+
18
+ test('rollback releases only unadmitted proposals; same-turn retry retains accepted cost', () => {
19
+ const ledger = createTurnTokenLedger()
20
+ ledger.reserve('s', 1, 'accepted', '中'.repeat(70), 100)
21
+ ledger.admit('s', 1, 'accepted')
22
+ ledger.reserve('s', 1, 'unsent', '中'.repeat(20), 100)
23
+ ledger.finish('s', 1)
24
+ assert.equal(ledger.room('s', 1, 100), 30)
25
+ ledger.release('s', 1, 'accepted')
26
+ assert.equal(ledger.room('s', 1, 100), 30)
27
+ assert.equal(ledger.reserve('s', 1, 'retry', '中'.repeat(31), 100), false)
28
+ assert.equal(ledger.reserve('s', 1, 'retry', '中'.repeat(30), 100), true)
29
+ ledger.clear('s')
30
+ assert.equal(ledger.room('s', 1, 100), 100)
31
+ })
32
+
33
+ test('bounded ledger fails conservatively at message cap and evicts old turn/session metadata', () => {
34
+ const ledger = createTurnTokenLedger({ maxSessions: 2, maxTurns: 2, maxMessages: 2 })
35
+ for (const id of ['one', 'two']) assert.equal(ledger.reserve('s', 1, id, 'abc', 100), true)
36
+ assert.equal(ledger.reserve('s', 1, 'three', 'abc', 100), false)
37
+ ledger.reserve('s', 2, 'x', 'abc', 100)
38
+ ledger.reserve('s', 3, 'x', 'abc', 100)
39
+ assert.equal(ledger.snapshot('s', 1, 100).messages, 0)
40
+ ledger.reserve('t', 1, 'x', 'abc', 100)
41
+ ledger.reserve('u', 1, 'x', 'abc', 100)
42
+ assert.equal(ledger.snapshot('s', 3, 100).messages, 0)
43
+ })
44
+
45
+ test('CJK ratio buckets retain existing estimates and never invent actual calibration', () => {
46
+ const ledger = createTurnTokenLedger()
47
+ const samples = ['plain latin words', '中国 words 中国 words', '全都是中文']
48
+ assert.deepEqual(samples.map(tokenRatioBucket), ['latin', 'mixed', 'cjk'])
49
+ samples.forEach((text, i) => ledger.reserve('s', 1, String(i), text, 1000))
50
+ const metrics = ledger.snapshot('s', 1, 1000)
51
+ assert.equal(metrics.estimated, samples.reduce((sum, text) => sum + estTokens(text), 0))
52
+ assert.equal(metrics.memoryActual, null)
53
+ assert.equal(metrics.calibrationFactor, null)
54
+ assert.equal(metrics.calibration, 'unverified')
55
+ assert.ok(Object.values(metrics.ratioBuckets).every(row => row.actual === null && row.status === 'unverified'))
56
+ assert.ok(!JSON.stringify(metrics).includes(samples[0]), 'no original text retained')
57
+ })
58
+
59
+ test('public request usage stays whole-request, preserves unknowns, deduplicates and rejects guessed fields', () => {
60
+ const ledger = createTurnTokenLedger()
61
+ const event = { type: 'assistant/message', seq: 2, data: { turn: 1, requestId: 'r', usage: { inputTokens: 90, outputTokens: 20 } } }
62
+ assert.equal(ledger.observeUsage('s', 1, event), true)
63
+ assert.equal(ledger.observeUsage('s', 1, { ...event, seq: 3 }), false)
64
+ let metrics = ledger.snapshot('s', 1, 1000)
65
+ assert.equal(metrics.requestUsage.last.promptTokens, null, 'missing cache counters are not made zero')
66
+ assert.equal(metrics.requestUsage.last.inputTokens, 90)
67
+ assert.equal(metrics.requestUsage.last.cacheReadTokens, null)
68
+ assert.equal(metrics.memoryActual, null)
69
+ assert.equal(ledger.observeUsage('s', 1, { type: 'assistant/message', data: { usage: { prompt_tokens: 999 } } }), false)
70
+ assert.equal(ledger.observeUsage('s', 1, { type: 'usage', data: { usage: { inputTokens: 999 } } }), false)
71
+ assert.equal(requestTokenUsage({ type: 'assistant/message', data: { usage: { inputTokens: -1, outputTokens: NaN } } }), null)
72
+ const known = { type: 'assistant/message', data: { usage: { inputTokens: 90, cacheReadTokens: 10, cacheWriteTokens: 5, outputTokens: 20, reasoningTokens: 8 } } }
73
+ assert.equal(requestTokenUsage(known).promptTokens, 105)
74
+ const exact = { type: 'assistant/message', data: { usage: { totalTokens: 140, outputTokens: 20 } } }
75
+ assert.equal(requestTokenUsage(exact).promptTokens, 120)
76
+ metrics = ledger.snapshot('s', 1, 1000)
77
+ assert.equal(metrics.calibration, 'unverified')
78
+ })
79
+
80
+ test('worker factors cold-start at 3, isolate domains, clamp 2..4 and slide after 16 windows', () => {
81
+ const factors = createDomainOutputFactors()
82
+ assert.equal(factors.snapshot('rp').factor, 3)
83
+ assert.equal(factors.observe('rp', 100, 0), true)
84
+ assert.equal(factors.snapshot('rp').factor, 2)
85
+ assert.equal(factors.snapshot('coding').factor, 3)
86
+ factors.observe('coding', 100, 10000)
87
+ assert.equal(factors.snapshot('coding').factor, 4)
88
+ factors.observe('general', 100, 200)
89
+ assert.equal(factors.snapshot('general').factor, 3)
90
+ for (let i = 0; i < 16; i++) factors.observe('rp', 100, 400)
91
+ assert.equal(factors.snapshot('rp').factor, 4)
92
+ assert.equal(factors.snapshot('rp').samples, 16)
93
+ assert.equal(factors.snapshot('rp').reasoning, 'unverified')
94
+ assert.equal(factors.observe('rp', 0, 100), false)
95
+ assert.equal(factors.observe('rp', 100, NaN), false)
96
+ assert.equal(factors.observe('rp', 100, -1), false)
97
+ assert.equal(factors.snapshot('rp').samples, 16)
98
+ })