dsh-memu-memory 1.3.1 → 1.3.3

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 (58) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +57 -0
  3. package/README.md +8 -7
  4. package/README.zh.md +8 -5
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/mobile.jpg +0 -0
  7. package/assets/screenshots/relations.jpg +0 -0
  8. package/assets/screenshots/settings.jpg +0 -0
  9. package/assets/screenshots/stats.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 +11 -0
  13. package/docs/contributing.md +6 -4
  14. package/docs/env-and-commands.md +12 -1
  15. package/docs/memory-semantics.md +8 -2
  16. package/docs/troubleshooting.md +24 -6
  17. package/lib/auto-link/apply.js +249 -0
  18. package/lib/auto-link/candidates.js +155 -0
  19. package/lib/auto-link/decide.js +304 -0
  20. package/lib/auto-link/normalize.js +99 -0
  21. package/lib/auto-link/policy.js +42 -0
  22. package/lib/auto-link/suppression.js +101 -0
  23. package/lib/auto-link/terminology.js +265 -0
  24. package/lib/binding-diagnostics.js +2 -2
  25. package/lib/client.js +1509 -72
  26. package/lib/graph.js +269 -18
  27. package/lib/memory.js +11 -0
  28. package/lib/memu.js +7 -6
  29. package/lib/private-links.js +105 -137
  30. package/lib/private.js +138 -38
  31. package/lib/rpc.js +73 -8
  32. package/lib/state.js +7 -2
  33. package/lib/tools.js +4 -2
  34. package/lib/webui/graph-LICENSE.txt +1 -62
  35. package/lib/webui/graph-view.bundle.js +1 -1
  36. package/lib/webui/graph-view.js +921 -126
  37. package/lib/webui/standalone.js +3 -3
  38. package/package.json +1 -2
  39. package/scripts/build-graph.mjs +35 -7
  40. package/scripts/check-all.mjs +2 -0
  41. package/scripts/check-graph-browser.mjs +106 -23
  42. package/scripts/make-readme-shots.mjs +59 -0
  43. package/scripts/rebuild-auto-links.mjs +252 -0
  44. package/tests/audit-regression.test.mjs +11 -8
  45. package/tests/auto-link-candidates.test.mjs +161 -0
  46. package/tests/auto-link-decide.test.mjs +512 -0
  47. package/tests/auto-link-migration.test.mjs +133 -0
  48. package/tests/browser.test.mjs +27 -0
  49. package/tests/client-render.test.mjs +178 -6
  50. package/tests/consolidation-fork.test.mjs +148 -0
  51. package/tests/cycle.test.mjs +1 -1
  52. package/tests/graph-view.test.mjs +221 -22
  53. package/tests/graph.test.mjs +5 -0
  54. package/tests/help-page.test.mjs +3 -3
  55. package/tests/memu-resident-route.test.mjs +130 -0
  56. package/tests/private-links.test.mjs +81 -45
  57. package/tests/stubs/child-process-spy.mjs +14 -0
  58. package/tests/tools.test.mjs +24 -18
@@ -314,6 +314,33 @@ test('the global curation picker hides archived and deleted conversations too',
314
314
  assert.deepEqual(out.sessions.map((s) => s.id), ['global-visible'])
315
315
  })
316
316
 
317
+ // 手动整理按钮按库找会话:listSessions 只多带一个只读 libraryId,
318
+ // 整理本身仍走会话维度的 generatePrivate(与侧边栏同一通道)。
319
+ test('listSessions reports the bound libraryId so a library can be consolidated', async () => {
320
+ const cwd = path.join(home, 'browser-lib-sessions')
321
+ const lib = createLibrary({ name: 'browser-lib-sessions', cwd })
322
+ setSessionBinding('sess-in-lib', { libraryId: lib.id })
323
+ setSessionBinding('sess-elsewhere', { libraryId: 'lib-other' })
324
+ const ctx = {
325
+ get(name) {
326
+ if (name !== 'sessionQuery') return null
327
+ return {
328
+ listSessions: async () => [
329
+ { header: { id: 'sess-in-lib', cwd }, live: false, persisted: true },
330
+ { header: { id: 'sess-elsewhere', cwd }, live: false, persisted: true },
331
+ { header: { id: 'sess-unbound', cwd }, live: false, persisted: true },
332
+ ],
333
+ readTitleSnapshots: async (ids) => ids.map((sessionId) => ({ sessionId, status: 'fulfilled', value: {} })),
334
+ }
335
+ },
336
+ }
337
+ const byId = Object.fromEntries((await dispatch(ctx, 'listSessions', { limit: 80 })).sessions
338
+ .map(row => [row.id, row.libraryId]))
339
+ assert.equal(byId['sess-in-lib'], lib.id, 'a bound conversation reports its library')
340
+ assert.equal(byId['sess-elsewhere'], 'lib-other', 'another library stays itself')
341
+ assert.equal(byId['sess-unbound'], null, 'an unbound conversation reports null, not undefined')
342
+ })
343
+
317
344
  // ---- provenance in the browser, and the private review queue ----
318
345
 
319
346
  test('the browser shows where a memory came from, and lets it be corrected', async () => {
@@ -212,14 +212,15 @@ test('the settings page renders every page instead of a blank panel', async () =
212
212
  await new Promise((resolve) => setTimeout(resolve, 0))
213
213
  await new Promise((resolve) => setTimeout(resolve, 0))
214
214
 
215
- for (let page = 0; page < 12; page++) {
215
+ // 13 页(含新增的关系图谱 graph:10);help 仍是最后一页,未纳入这轮巡检。
216
+ for (let page = 0; page < 13; page++) {
216
217
  const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
217
218
  const text = treeText(tree)
218
219
  assert.match(String(tree.props?.className), /dshm-root/, `page ${page} did not render the shell`)
219
220
  // The rail is the nav: every page label has to be there. Counting the shared
220
221
  // dshm-nav-item class instead would also pick up the in-page tab strips (memory
221
222
  // backend, prompt scope, browser view), which use the same widget on purpose.
222
- const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageLogs', 'pageLexicon']
223
+ const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageGraph', 'pageLogs', 'pageLexicon']
223
224
  assert.ok(NAV.every((key) => text.includes(key)), `page ${page} lost a nav entry`)
224
225
  assert.equal((text.match(/dshm-nav-ind/g) || []).length, 1, `page ${page} lost or duplicated its rail indicator`)
225
226
  assert.match(text, /dshm-page/, `page ${page} lost the content pane`)
@@ -229,6 +230,99 @@ test('the settings page renders every page instead of a blank panel', async () =
229
230
  }
230
231
  })
231
232
 
233
+ test('the immersive graph shell stays with the standalone WebUI', async () => {
234
+ // 点「关系图谱」把宿主页面的导航条掰成 158px 竖排,是 is-graph-wide 没分外壳造成的:
235
+ // 那套样式是为独立 WebUI 的全屏画布写的,宿主设置页只需要普通横排导航 + 一个入口按钮。
236
+ const ctx = fakeCtx()
237
+ globalThis.__dshMemuExports.apply(ctx)
238
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
239
+ assert.ok(settings?.component, 'settings.section was not registered')
240
+ const GRAPH_PAGE = 10
241
+
242
+ // The standalone shell resolves its page from the hash, so there is no
243
+ // numeric-zero page state to force on; the host shell has one.
244
+ const shell = async (props, { fromHash = false } = {}) => {
245
+ const first = await renderPage(settings.component, props, undefined, { remount: true })
246
+ if (!fromHash) collectPageHook()
247
+ for (const effect of first.effects) effect.fn()
248
+ await new Promise((resolve) => setTimeout(resolve, 0))
249
+ return (await renderPage(settings.component, props, fromHash ? undefined : GRAPH_PAGE)).tree
250
+ }
251
+
252
+ const inHost = await shell({ ctx, t: (key) => key })
253
+ assert.match(String(inHost.props?.className), /dshm-root/, 'the host graph page lost its shell')
254
+ assert.ok(!/is-graph-wide/.test(String(inHost.props?.className)),
255
+ `the host settings page must keep its horizontal rail, saw "${inHost.props?.className}"`)
256
+ const buttons = []
257
+ walkNodes(inHost, (node) => { if (node.type === 'button' && node.props?.children === 'openGraphStudio') buttons.push(node) })
258
+ assert.equal(buttons.length, 1, 'the host graph page should offer exactly one entry into the studio')
259
+ assert.equal(typeof buttons[0].props.onClick, 'function', 'the entry button has no handler')
260
+
261
+ const inWebUi = await withHash('#/settings/graph', () => shell({ ctx, t: (key) => key, standalone: true }, { fromHash: true }))
262
+ assert.match(String(inWebUi.props?.className), /is-graph-wide/, 'the standalone graph page lost its immersive shell')
263
+ })
264
+
265
+ test('the manual consolidation button rides the sidebar channel, not a new RPC', async () => {
266
+ // 「立即整理」刻意不新增方法:它查 listSessions 的库绑定,再对每个绑定会话调用
267
+ // 侧边栏同一个 generatePrivate。多一个只给 UI 用的整理方法,就等于多一条模型也能
268
+ // 调用的写路径。
269
+ const rpcCalls = []
270
+ const ctx = fakeCtx({
271
+ rpcCalls,
272
+ answers: {
273
+ getState: { ...RPC_ANSWERS.getState, libraries: [{ id: 'lib-1', name: 'L1', privateCount: 3, pinnedCount: 0, boundSessions: 2 }] },
274
+ getSettingsState: { ...RPC_ANSWERS.getSettingsState, libraries: [{ id: 'lib-1', name: 'L1', privateCount: 3, pinnedCount: 0, boundSessions: 2 }] },
275
+ listSessions: { sessions: [
276
+ { id: 's1', libraryId: 'lib-1' }, { id: 's2', libraryId: 'lib-1' }, { id: 's3', libraryId: 'lib-2' },
277
+ ] },
278
+ generatePrivate: { ok: true },
279
+ },
280
+ })
281
+ globalThis.__dshMemuExports.apply(ctx)
282
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
283
+ const props = { ctx, t: (key) => key }
284
+ const LIBRARIES_PAGE = 4
285
+ const render = async (page, remount = false) => renderPage(settings.component, props, page, { remount })
286
+ const first = await render(undefined, true)
287
+ collectPageHook()
288
+ for (const effect of first.effects) effect.fn()
289
+ await new Promise((resolve) => setTimeout(resolve, 0))
290
+ const second = await render(LIBRARIES_PAGE)
291
+ for (const effect of second.effects) effect.fn()
292
+ await new Promise((resolve) => setTimeout(resolve, 0))
293
+ const tree = (await render(LIBRARIES_PAGE)).tree
294
+
295
+ const buttons = []
296
+ walkNodes(tree, (node) => { if (node.type === 'button' && node.props?.children === 'consolidateNow') buttons.push(node) })
297
+ assert.equal(buttons.length, 1, 'the library row lost its 立即整理 button')
298
+ rpcCalls.length = 0
299
+ await buttons[0].props.onClick()
300
+ assert.deepEqual(rpcCalls, [], 'the first click must only arm the confirmation')
301
+ const armed = []
302
+ walkNodes((await render(LIBRARIES_PAGE)).tree, (node) => { if (node.type === 'button' && node.props?.children === 'confirmAction') armed.push(node) })
303
+ assert.equal(armed.length, 1, 'the arming state did not reach the button label')
304
+ await armed[0].props.onClick()
305
+ for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0))
306
+ assert.deepEqual(rpcCalls.map((c) => [c.endpoint, c.payload]), [
307
+ ['listSessions', { limit: 200 }],
308
+ ['generatePrivate', { sessionId: 's1' }],
309
+ ['generatePrivate', { sessionId: 's2' }],
310
+ ], 'consolidation must hit only the sessions bound to that library')
311
+ })
312
+
313
+ // The standalone shell reads `window.location.hash` to pick its page and rewrites
314
+ // it as the user navigates, which the host-side fixture never provides.
315
+ async function withHash(hash, run) {
316
+ const original = globalThis.window.location
317
+ const originalHistory = globalThis.window.history
318
+ globalThis.window.location = { ...original, hash }
319
+ globalThis.window.history = { ...originalHistory, replaceState: () => {} }
320
+ try { return await run() } finally {
321
+ globalThis.window.location = original
322
+ globalThis.window.history = originalHistory
323
+ }
324
+ }
325
+
232
326
  test('the sidebar tab renders with the two-layer header', async () => {
233
327
  const ctx = fakeCtx()
234
328
  const tab = registrations.find((r) => r.slot === 'sidebar.right.pane.tab')
@@ -396,6 +490,84 @@ test('the memory browser badges what a memory is allowed to say', async () => {
396
490
  }
397
491
  })
398
492
 
493
+ test('the browse search box filters the loaded library in place', async () => {
494
+ // 搜索是纯前端的:它只过滤已经拉回来的那一页,不新发 RPC。库一切换就清空,
495
+ // 否则上一个库的关键词会把当前库筛成「空库」。
496
+ const originalGetState = RPC_ANSWERS.getState
497
+ const originalSettingsState = RPC_ANSWERS.getSettingsState
498
+ const loaded = { ...EMPTY_STATE, libraries: [{ id: 'lib-1', name: 'demo', scopeKey: '/proj/demo', privateCount: 2 }] }
499
+ RPC_ANSWERS.getState = loaded
500
+ RPC_ANSWERS.getSettingsState = loaded
501
+ RPC_ANSWERS.browseLibrary = {
502
+ source: 'engine',
503
+ files: [
504
+ { id: 'mem-attic', title: 'the attic', content: 'he never told his brother', layer: 'long_term', status: 'active', decay: .5 },
505
+ { id: 'mem-loud', title: 'shared fact', content: 'anything', layer: 'long_term', status: 'active', decay: .9 },
506
+ ],
507
+ }
508
+ try {
509
+ const rpcCalls = []
510
+ const ctx = fakeCtx({ rpcCalls })
511
+ globalThis.__dshMemuExports.apply(ctx)
512
+ const settings = registrations.filter((r) => r.slot === 'settings.section').pop()
513
+ const props = { ctx, t: (key) => key }
514
+ const render = (page, remount = false) => renderPage(settings.component, props, page, { remount })
515
+ const first = await render(undefined, true)
516
+ collectPageHook()
517
+ for (const effect of first.effects) effect.fn()
518
+ await new Promise((resolve) => setTimeout(resolve, 0))
519
+ let tree = (await render(5)).tree
520
+ const picker = []
521
+ walkNodes(tree, (node) => {
522
+ const options = Array.isArray(node.props?.children) ? node.props.children : []
523
+ if (node.type === 'select' && options.some((option) => option?.props?.value === 'lib-1')) picker.push(node)
524
+ })
525
+ picker[0].props.onChange({ target: { value: 'lib-1' } })
526
+ tree = (await render(5)).tree
527
+ const reload = []
528
+ walkNodes(tree, (node) => { if (node.type === 'button' && node.props?.children === 'reload') reload.push(node) })
529
+ reload[0].props.onClick()
530
+ for (let i = 0; i < 3; i++) await new Promise((resolve) => setTimeout(resolve, 0))
531
+ tree = (await render(5)).tree
532
+
533
+ // Rows carry their title in an editor input, so counting rendered values beats
534
+ // grepping the flattened tree.
535
+ const snapshot = (node) => {
536
+ const titles = []
537
+ let rows = 0
538
+ walkNodes(node, (n) => {
539
+ if (n.type === 'button' && n.props?.children === 'archive') rows++
540
+ if (n.type === 'input' && (n.props?.value === 'the attic' || n.props?.value === 'shared fact')) titles.push(n.props.value)
541
+ })
542
+ return { rows, titles }
543
+ }
544
+
545
+ const before = snapshot(tree)
546
+ assert.deepEqual(before, { rows: 2, titles: ['the attic', 'shared fact'] }, 'both rows render before filtering')
547
+ rpcCalls.length = 0
548
+ const box = []
549
+ walkNodes(tree, (node) => { if (node.type === 'input' && node.props?.placeholder === 'browseSearchPlaceholder') box.push(node) })
550
+ assert.equal(box.length, 1, 'no search box under 当前记忆库')
551
+ box[0].props.onChange({ target: { value: 'attic' } })
552
+ const filteredTree = (await render(5)).tree
553
+ assert.deepEqual(snapshot(filteredTree), { rows: 1, titles: ['the attic'] }, 'the filter keeps only the matching row')
554
+ assert.match(treeText(filteredTree), /1 \/ 2/, 'the counter says how much of the library the filter kept')
555
+ assert.match(treeText(filteredTree), /browseActiveTab \(1\)/, 'the tab counts follow the filter, not the whole library')
556
+ assert.deepEqual(rpcCalls, [], 'filtering an already loaded library must not re-fetch it')
557
+ box[0].props.onChange({ target: { value: 'no-such-memory' } })
558
+ assert.match(treeText((await render(5)).tree), /browseActiveTab \(0\)/, 'a query that matches nothing empties the tab counts')
559
+ const clear = []
560
+ walkNodes((await render(5)).tree, (node) => { if (node.type === 'button' && node.props?.children === 'browseSearchClear') clear.push(node) })
561
+ assert.equal(clear.length, 1, 'no way to clear the query')
562
+ clear[0].props.onClick()
563
+ assert.deepEqual(snapshot((await render(5)).tree), before, 'clearing the query brings the library back')
564
+ } finally {
565
+ RPC_ANSWERS.getState = originalGetState
566
+ RPC_ANSWERS.getSettingsState = originalSettingsState
567
+ delete RPC_ANSWERS.browseLibrary
568
+ }
569
+ })
570
+
399
571
  test('the WebUI buttons open a new tab and never navigate this one', async () => {
400
572
  const opened = []
401
573
  const navigated = []
@@ -938,10 +1110,10 @@ test('failed and degraded activity rows are visually distinguished from normal r
938
1110
  collectPageHook()
939
1111
  for (const effect of first.effects) effect.fn()
940
1112
  await new Promise((resolve) => setTimeout(resolve, 0))
941
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1113
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
942
1114
  for (const effect of mid.effects) effect.fn()
943
1115
  await new Promise((resolve) => setTimeout(resolve, 0))
944
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1116
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
945
1117
  const rows = new Map()
946
1118
  const labels = []
947
1119
  walkNodes(tree, (node) => {
@@ -998,11 +1170,11 @@ test('the log page renders rows with copy, download and locate actions', async (
998
1170
  await new Promise((resolve) => setTimeout(resolve, 0))
999
1171
  // The log page's own effect only exists once that page renders, so it needs one
1000
1172
  // more render + effect pass before the data is in the hook.
1001
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1173
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1002
1174
  for (const effect of mid.effects) effect.fn()
1003
1175
  await new Promise((resolve) => setTimeout(resolve, 0))
1004
1176
  await new Promise((resolve) => setTimeout(resolve, 0))
1005
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1177
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1006
1178
  const text = treeText(tree)
1007
1179
  assert.match(text, /整理超时/)
1008
1180
  assert.match(text, /logCopyAll/)
@@ -771,3 +771,151 @@ test('compactSeedEvents accepts the catalog and local recall as two read-only pr
771
771
  assert.equal(seed[2].type, 'user/message')
772
772
  assert.match(seed[2].data.content[0].text, /事件时间/)
773
773
  })
774
+
775
+ // ------------------------------------------------------- surface replacements
776
+ // Mirrors @deepseek-ai/dsh-session 0.2.2-rc.1 Session.create for the fields a
777
+ // consolidation seed touches: seq contiguity plus the surface fold. The host
778
+ // rejects "seed event at index N has seq M" and every dangling replace citation,
779
+ // so the assertion has to replay the fold, not just look at one event.
780
+ const HOST_SURFACE_EVENT_TYPES = new Set(['system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result'])
781
+ function assertSeedAcceptedByHost(seed, label = 'seed') {
782
+ const nodes = []
783
+ seed.forEach((event, index) => {
784
+ assert.equal(event.seq, index, `${label}: event at index ${index} has seq ${event.seq}`)
785
+ if (!HOST_SURFACE_EVENT_TYPES.has(event.type)) {
786
+ assert.equal(event.surfaceOp, undefined, `${label}: ${event.type} cannot carry surfaceOp`)
787
+ assert.equal(event.sourceEventSeqs, undefined, `${label}: ${event.type} cannot carry sourceEventSeqs`)
788
+ return
789
+ }
790
+ const op = event.surfaceOp
791
+ assert.ok(op !== undefined, `${label}: ${event.type} at ${index} requires a surfaceOp marker`)
792
+ const sources = event.sourceEventSeqs
793
+ if (sources !== undefined) {
794
+ assert.ok(Array.isArray(sources) && sources.length > 0, `${label}: sourceEventSeqs must be a non-empty array`)
795
+ assert.equal(new Set(sources).size, sources.length, `${label}: sourceEventSeqs must not repeat`)
796
+ assert.ok(sources.every(seq => Number.isSafeInteger(seq) && seq < event.seq), `${label}: sourceEventSeqs must reference earlier events`)
797
+ }
798
+ if (op === 'append') {
799
+ nodes.push(event.seq)
800
+ return
801
+ }
802
+ assert.deepEqual(Object.keys(op).sort(), ['endSeq', 'op', 'startSeq'], `${label}: replace markers carry exactly op/startSeq/endSeq`)
803
+ assert.ok(op.startSeq < event.seq && op.endSeq < event.seq, `${label}: surface replace at ${index} must reference earlier events`)
804
+ const startIdx = nodes.indexOf(op.startSeq)
805
+ const endIdx = nodes.indexOf(op.endSeq)
806
+ assert.ok(startIdx >= 0, `${label}: replace start seq ${op.startSeq} is not on the surface`)
807
+ assert.ok(endIdx >= startIdx, `${label}: replace range must be ordered`)
808
+ const shadowed = nodes.slice(startIdx, endIdx + 1)
809
+ if (event.type === 'tool/result') assert.equal(shadowed.length, 1, `${label}: tool/result replacement rewrites exactly one node`)
810
+ assert.ok(Array.isArray(sources), `${label}: replace at ${index} needs sourceEventSeqs`)
811
+ assert.deepEqual(shadowed.filter(seq => !sources.includes(seq)), [], `${label}: replace at ${index} must cite every shadowed node`)
812
+ nodes.splice(startIdx, endIdx - startIdx + 1)
813
+ nodes.push(event.seq)
814
+ })
815
+ }
816
+
817
+ const userEvent = (seq, text, extra = {}) => ({
818
+ seq, type: 'user/message', surfaceOp: 'append',
819
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text }] }, ...extra,
820
+ })
821
+ const assistantEvent = (seq, text) => ({
822
+ seq, type: 'assistant/message', surfaceOp: 'append',
823
+ data: { message: { content: [{ type: 'text', text }] } },
824
+ })
825
+ const toolResultEvent = (seq, text, extra = {}) => ({
826
+ seq, type: 'tool/result', surfaceOp: 'append',
827
+ data: { message: { content: [{ type: 'text', text }] } }, ...extra,
828
+ })
829
+
830
+ test('a surface replace is renumbered into the seed instead of citing original seqs', () => {
831
+ const seed = compactSeedEvents([
832
+ userEvent(0, '记住:周五交房租'),
833
+ assistantEvent(1, '好'),
834
+ toolResultEvent(2, '原始工具输出'),
835
+ toolResultEvent(3, '[已裁剪]', {
836
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
837
+ sourceEventSeqs: [2],
838
+ }),
839
+ userEvent(4, '继续'),
840
+ ])
841
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
842
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 }, 'the citation follows the surviving node, not its original seq')
843
+ assert.deepEqual(seed[3].sourceEventSeqs, [2])
844
+ assertSeedAcceptedByHost(seed)
845
+ })
846
+
847
+ test('a replace pointing outside the window is dropped and the seed stays contiguous', () => {
848
+ // 窗口从父会话中间切出:seq 4 不在这一窗里;后面的 replace 又引用前面被丢的
849
+ // replace。旧实现先编号后丢弃,留下 seq 空洞,宿主报 index 1 has seq 5。
850
+ const seed = compactSeedEvents([
851
+ userEvent(10, '这一窗的第一句'),
852
+ toolResultEvent(11, '输出'),
853
+ toolResultEvent(12, '[已裁剪]', {
854
+ surfaceOp: { op: 'replace', startSeq: 4, endSeq: 4 },
855
+ sourceEventSeqs: [4],
856
+ }),
857
+ assistantEvent(13, '回答'),
858
+ toolResultEvent(14, '[已裁剪]', {
859
+ surfaceOp: { op: 'replace', startSeq: 12, endSeq: 12 },
860
+ sourceEventSeqs: [12],
861
+ }),
862
+ ])
863
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2], 'dropping a patch must renumber the survivors')
864
+ assert.equal(seed.some(event => event.surfaceOp && typeof event.surfaceOp === 'object'), false)
865
+ assertSeedAcceptedByHost(seed)
866
+ })
867
+
868
+ test('a replacement that cites another replacement keeps both when their targets survive', () => {
869
+ const seed = compactSeedEvents([
870
+ userEvent(0, '开头'),
871
+ toolResultEvent(1, '原始输出'),
872
+ toolResultEvent(2, '[第一次裁剪]', {
873
+ surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 },
874
+ sourceEventSeqs: [1],
875
+ }),
876
+ assistantEvent(3, '中间'),
877
+ toolResultEvent(4, '[第二次裁剪]', {
878
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
879
+ sourceEventSeqs: [2],
880
+ }),
881
+ ])
882
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
883
+ assert.deepEqual(seed[2].surfaceOp, { op: 'replace', startSeq: 1, endSeq: 1 })
884
+ assert.deepEqual(seed[4].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 })
885
+ assertSeedAcceptedByHost(seed)
886
+ })
887
+
888
+ test('a multi-node replace is remapped when every shadowed node survives', () => {
889
+ const seed = compactSeedEvents([
890
+ userEvent(0, 'A'),
891
+ userEvent(1, 'X'),
892
+ userEvent(2, 'B'),
893
+ userEvent(3, '外层摘要', {
894
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
895
+ sourceEventSeqs: [0, 1, 2],
896
+ }),
897
+ ])
898
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3])
899
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 0, endSeq: 2 })
900
+ assert.deepEqual(seed[3].sourceEventSeqs, [0, 1, 2])
901
+ assertSeedAcceptedByHost(seed)
902
+ })
903
+
904
+ test('a replace is dropped when filtering an inner checkpoint reveals a shadowed node', () => {
905
+ // 内层压缩检查点(source.kind 不是 user)会被种子过滤器丢掉;它遮住的 X 因此
906
+ // 重新出现在种子的 surface 上。外层替换写于 X 被遮住期间,引用里没有 X。
907
+ // 宿主会要求外层补上 X 的引用——补不出来就只能丢外层,种子回到纯 append。
908
+ const seed = compactSeedEvents([
909
+ userEvent(0, 'A'),
910
+ userEvent(1, 'X'),
911
+ userEvent(2, 'B'),
912
+ userEvent(3, '内层摘要', { data: { source: { kind: 'compact-checkpoint' }, content: [{ type: 'text', text: '内层摘要' }] }, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 }, sourceEventSeqs: [1] }),
913
+ userEvent(4, '外层摘要', {
914
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
915
+ sourceEventSeqs: [0, 2],
916
+ }),
917
+ ])
918
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2])
919
+ assert.deepEqual(seed.map(event => event.data.content[0].text), ['A', 'X', 'B'])
920
+ assertSeedAcceptedByHost(seed)
921
+ })
@@ -177,7 +177,7 @@ test('a fork that cannot be created is logged, not dropped silently', async () =
177
177
  },
178
178
  }
179
179
  await cycle.runSleepPass(ctx, { log: (m) => logs.push(m) })
180
- assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
180
+ assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: .*no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
181
181
  assert.equal(state.getLastSleepAt('cycle-hist'), null)
182
182
  assert.match(state.getSessionBinding('cycle-hist').lastSleepError, /no fork/)
183
183
  })