dsh-memu-memory 1.3.10 → 1.3.12

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.
@@ -0,0 +1,130 @@
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
+ // 全局生命周期管理面(1.3.12):归档/恢复/两步永久删除与私有同权,内容仍由
8
+ // curator 书写。守卫口径:
9
+ // 1. 归档立即被召回排除(isMemoryEligible 统一闸门),恢复即回来;
10
+ // 2. 状态机边界:pending_review 走复核队列、superseded 不能直接恢复;
11
+ // 3. 全局 updateMemory 只接受 {status:'active'},内容补丁一律拒绝;
12
+ // 4. 删除只开放已归档/抑制/过期条目,需显式确认,级联清他条 links 与指针;
13
+ // 5. 合并稿与活跃合并的来源拒删(absorbSnapshot 是撤销合并的唯一依据);
14
+ // 6. 管理视图(browseWall/listGlobal standalone)仍看得到 archived 条目。
15
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-global-lifecycle-'))
16
+ process.env.DSH_MEMU_HOME = home
17
+ process.env.DSH_MEMU_MEMORY_HOME = home
18
+ const state = await import('../lib/state.js')
19
+ const memory = await import('../lib/memory.js')
20
+ const rpc = await import('../lib/rpc.js')
21
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
22
+
23
+ state.updateSettings({ memoryBackend: 'agent', vectorSource: 'local', crossLibraryRecall: false })
24
+ const sessionId = 'global-lifecycle-session'
25
+ state.ensureSession(sessionId, { cwd: path.join(home, 'proj') })
26
+ // 域自动探测会随 cwd 落成 coding:这里钉成 general,与种子条目的 domain 对齐。
27
+ state.setSessionBinding(sessionId, { domain: 'general', domainOverride: 'general', domainSource: 'manual' })
28
+ const exec = { agent: { session: { header: { id: sessionId } } } }
29
+
30
+ const entry = (title, extra = {}) => ({
31
+ title, content: title, status: 'active', layer: 'long_term', domain: 'general',
32
+ visibility: 'shared', disclosure: 'can_tell', source: 'inferred',
33
+ createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...extra,
34
+ })
35
+ const seed = (entries) => {
36
+ state.updateGlobalIndex((index) => { index.entries = entries })
37
+ state.flushState()
38
+ }
39
+ const globalEntry = (id) => state.loadGlobalIndex().entries[id]
40
+
41
+ test('global archive drops the entry from recall; restore brings it back', async () => {
42
+ seed({ 'mem-g-visible': entry('zxquartzglobal 部署窗口'), 'mem-g-other': entry('unrelated filler') })
43
+ const before = await memory.globalRecall({ exec, query: 'zxquartzglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
44
+ assert.deepEqual(before.files.map(f => f.name), ['mem-g-visible'])
45
+ assert.equal(memory.isMemoryEligible(globalEntry('mem-g-visible'), { automatic: true }), true)
46
+
47
+ const archived = await rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-visible' })
48
+ assert.equal(archived.entry.status, 'archived')
49
+ assert.equal(memory.isMemoryEligible(globalEntry('mem-g-visible'), { automatic: true }), false)
50
+ const after = await memory.globalRecall({ exec, query: 'zxquartzglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
51
+ assert.deepEqual(after.files.map(f => f.name), [], 'archived global memory must not recall')
52
+
53
+ // 幂等归档不报错;恢复走 updateMemory 的唯一全局补丁形状。
54
+ await rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-visible' })
55
+ const restored = await rpc.dispatch({}, 'updateMemory', { scope: 'global', id: 'mem-g-visible', patch: { status: 'active' } })
56
+ assert.equal(restored.entry.status, 'active')
57
+ const back = await memory.globalRecall({ exec, query: 'zxquartzglobal', purpose: 'automatic', topK: 5, relevanceThreshold: 0 })
58
+ assert.deepEqual(back.files.map(f => f.name), ['mem-g-visible'])
59
+ })
60
+
61
+ test('global lifecycle state machine refuses review, superseded and content edits', async () => {
62
+ seed({
63
+ 'mem-g-pending': entry('待复核条目', { status: 'pending_review' }),
64
+ 'mem-g-superseded': entry('被取代条目', { status: 'superseded', supersededBy: 'mem-g-active' }),
65
+ 'mem-g-active': entry('现行条目'),
66
+ })
67
+ await assert.rejects(() => rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-pending' }), /review queue/)
68
+ await assert.rejects(() => rpc.dispatch({}, 'updateMemory', { scope: 'global', id: 'mem-g-superseded', patch: { status: 'active' } }), /only archived/)
69
+ await assert.rejects(() => rpc.dispatch({}, 'updateMemory', { scope: 'global', id: 'mem-g-active', patch: { status: 'active' } }), /only archived/)
70
+ await assert.rejects(() => rpc.dispatch({}, 'updateMemory', { scope: 'global', id: 'mem-g-active', patch: { content: '改写' } }), /curator-written/)
71
+ await assert.rejects(() => rpc.dispatch({}, 'updateMemory', { scope: 'global', id: 'mem-g-active', patch: { status: 'archived' } }), /curator-written/)
72
+ await assert.rejects(() => rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-active', libraryId: 'lib-x' }), /libraryId/)
73
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-active', libraryId: 'lib-x', confirmed: true }), /libraryId/)
74
+ await assert.rejects(() => rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-missing' }), /unknown global memory/)
75
+ // superseded 可以归档(本就不可召回),但仍不能直接恢复。
76
+ await rpc.dispatch({}, 'archiveMemory', { scope: 'global', id: 'mem-g-superseded' })
77
+ assert.equal(globalEntry('mem-g-superseded').status, 'archived')
78
+ })
79
+
80
+ test('global permanent delete is gated, confirmed, and cascades inbound pointers', async () => {
81
+ seed({
82
+ 'mem-g-target': entry('删除目标', { status: 'archived' }),
83
+ 'mem-g-live': entry('活跃条目'),
84
+ 'mem-g-referrer': entry('引用者', {
85
+ links: [{ id: 'lnk-1', to: 'mem-g-target', kind: 'related' }, { id: 'lnk-2', to: 'mem-g-live', kind: 'related' }],
86
+ duplicateOf: 'mem-g-target', relatedTo: 'mem-g-target', conflictingWith: 'mem-g-target',
87
+ supersededBy: 'mem-g-target', absorbedBy: 'mem-g-target',
88
+ }),
89
+ })
90
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-live', confirmed: true }), /archive it first/)
91
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-target' }), /explicit confirmation/)
92
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-target', preview: true }), /no preview\/restore buffer/)
93
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-target', restore: true }), /no preview\/restore buffer/)
94
+
95
+ const deleted = await rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-target', confirmed: true })
96
+ assert.equal(deleted.deleted, true)
97
+ assert.equal(deleted.libraryId, null)
98
+ assert.equal(globalEntry('mem-g-target'), undefined)
99
+ const referrer = globalEntry('mem-g-referrer')
100
+ assert.deepEqual(referrer.links.map(l => l.to), ['mem-g-live'], 'inbound links to the deleted row are swept')
101
+ for (const field of ['duplicateOf', 'relatedTo', 'conflictingWith', 'supersededBy', 'absorbedBy']) {
102
+ assert.equal(referrer[field], undefined, `${field} must not dangle`)
103
+ }
104
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-target', confirmed: true }), /unknown global memory/)
105
+ })
106
+
107
+ test('global delete refuses merged entries and sources of a live merge', async () => {
108
+ seed({
109
+ 'mem-g-merged': entry('合并稿', { status: 'archived', absorbedFrom: ['mem-g-source'], absorbSnapshot: {} }),
110
+ 'mem-g-source': entry('来源', { status: 'archived', absorbedBy: 'mem-g-merged-live' }),
111
+ 'mem-g-merged-live': entry('活跃合并稿', { absorbedFrom: ['mem-g-source'] }),
112
+ })
113
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-merged', confirmed: true }), /undo the merge first/)
114
+ await assert.rejects(() => rpc.dispatch({}, 'deleteMemory', { scope: 'global', id: 'mem-g-source', confirmed: true }), /source of merged memory mem-g-merged-live/)
115
+ })
116
+
117
+ test('management views still show archived global rows; private archive path is unchanged', async () => {
118
+ seed({ 'mem-g-archived': entry('已归档全局', { status: 'archived' }) })
119
+ const wall = await rpc.dispatch({}, 'browseWall', { libraryId: null, limit: 300 })
120
+ assert.ok(wall.items.some(item => item.libraryId === null && item.id === 'mem-g-archived' && item.status === 'archived'))
121
+ const listed = await rpc.dispatch({}, 'listGlobal', {})
122
+ assert.ok(listed.files.some(file => file.id === 'mem-g-archived' && file.status === 'archived'))
123
+
124
+ // 私有路径回归:显式 libraryId 的 archiveMemory 不受 scope 分支影响。
125
+ const lib = state.createLibrary({ name: 'global-lifecycle-private', cwd: path.join(home, 'private') })
126
+ state.updatePrivateIndex(lib.id, (index) => { index.entries['mem-p-row'] = entry('私有条目') })
127
+ const archived = await rpc.dispatch({}, 'archiveMemory', { libraryId: lib.id, id: 'mem-p-row' })
128
+ assert.equal(archived.entry.status, 'archived')
129
+ assert.equal(state.loadPrivateIndex(lib.id).entries['mem-p-row'].status, 'archived')
130
+ })
@@ -111,6 +111,17 @@ test('sample validation fails closed on a false answerable marker and on an out-
111
111
  assert.throws(() => bench.validateSampleShape({ ...base, draft: false, expectedIds: ['mem-rb-invalid'] }, 'bad'), /draft must be true/)
112
112
  })
113
113
 
114
+ test('complete expected-set metric distinguishes a partial conflict recall from full coverage', () => {
115
+ const records = [
116
+ { noAnswer: false, expectedIds: ['old', 'new'], top3: ['new'] },
117
+ { noAnswer: false, expectedIds: ['old', 'new'], top3: ['new', 'old'] },
118
+ ]
119
+ const metrics = bench.computeMetrics(records)
120
+ assert.equal(metrics.recallAt3, 1)
121
+ assert.equal(metrics.allExpectedAt3, 0.5)
122
+ assert.equal(bench.computeMetrics([{ noAnswer: true, top3: [] }]).emptySet.allExpectedAt3, true)
123
+ })
124
+
114
125
  test('metric math uses explicit denominators and scores empty top-3 as a no-answer success', () => {
115
126
  const metrics = bench.computeMetrics([
116
127
  { id: 'a', noAnswer: false, expectedIds: ['e1'], forbiddenIds: ['f'], top3: ['x', 'e1'] },
@@ -0,0 +1,51 @@
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(), 'memu-corpus-gate-'))
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 { privateRecall } = await import('../lib/memory.js')
12
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
13
+
14
+ for (const backend of ['agent', 'api', 'api-fallback']) {
15
+ for (const [kind, hidden] of Object.entries({
16
+ secret: { visibility: 'secret' },
17
+ context: { context: { characterId: 'someone-else' } },
18
+ never: { disclosure: 'never_say' },
19
+ asked: { disclosure: 'only_if_asked' },
20
+ })) {
21
+ test('single-library ' + backend + ' excludes ' + kind + ' from BM25 statistics', async () => {
22
+ const sessionId = backend + '-' + kind
23
+ const cwd = path.join(home, sessionId)
24
+ state.ensureSession(sessionId, { cwd })
25
+ const libraryId = state.getSessionBinding(sessionId).libraryId
26
+ state.updateSettings({ memoryBackend: backend === 'agent' ? 'agent' : 'api', vectorSource: 'api', crossLibraryRecall: false })
27
+ const entries = {}
28
+ const entry = (title, extra = {}) => ({ title, content: title, layer: 'long_term', status: 'active', createdAt: new Date().toISOString(), ...extra })
29
+ entries['mem-target'] = entry('zxquartz')
30
+ for (let i = 0; i < 7; i++) entries['mem-filler-' + i] = entry('unrelated' + i)
31
+ state.savePrivateIndex(libraryId, { entries })
32
+ const exec = { agent: { session: { header: { id: sessionId } } } }
33
+ // Empty semantic results exercise the production mixed recall lexical leg.
34
+ const recall = (query = 'zxquartz', purpose = 'automatic') => privateRecall({ exec, query, purpose, topK: 5, relevanceThreshold: 0, retrieveImpl: async () => { if (backend === 'api-fallback') throw new Error('simulated vector outage'); return { files: [] } } })
35
+ const before = await recall()
36
+ assert.equal(before.recallRoute, backend === 'api-fallback' ? 'local-fallback' : backend === 'api' ? 'managed-vector-rrf' : 'local')
37
+ assert.deepEqual(before.files.map(f => f.name), ['mem-target'])
38
+ for (let i = 0; i < 12; i++) entries['mem-hidden-' + i] = entry('zxquartz', hidden)
39
+ state.savePrivateIndex(libraryId, { entries })
40
+ const after = await recall()
41
+ assert.equal(after.recallRoute, backend === 'api-fallback' ? 'local-fallback' : backend === 'api' ? 'managed-vector-rrf' : 'local')
42
+ assert.deepEqual(after.files.map(f => f.name), ['mem-target'], 'ineligible documents must not prune the visible query term')
43
+ if (backend === 'agent') assert.equal(after.files[0].lexical, before.files[0].lexical, 'visible corpus statistics stay unchanged')
44
+ // Explicit exact-id reads retain their existing permission contract.
45
+ if (kind !== 'context') {
46
+ const exact = await recall('mem-hidden-0', 'explicit')
47
+ assert.deepEqual(exact.files.map(f => f.name), ['mem-hidden-0'])
48
+ }
49
+ })
50
+ }
51
+ }
@@ -783,6 +783,78 @@ test('global review queue: embedded sessions may read, writes need a live bindin
783
783
  }
784
784
  })
785
785
 
786
+ // 全局生命周期(1.3.12):scope:'global' 的 archiveMemory/updateMemory/deleteMemory
787
+ // 与全局复核队列同一管理面凭据模型——embedded 要活绑定、standalone 走 libraryId=null
788
+ // 的 review.manage;scope 与 libraryId 同时出现是作用域冲突,先于 dispatch 拒绝。
789
+ test('global lifecycle: scope global follows the global management credential model', async () => {
790
+ const seedGlobalActive = () => {
791
+ state.updateGlobalIndex((index) => {
792
+ index.entries['mem-global-lifecycle'] = {
793
+ title: 'global lifecycle', content: 'global lifecycle body', status: 'active', layer: 'long_term',
794
+ domain: 'general', visibility: 'shared', disclosure: 'can_tell', source: 'inferred',
795
+ createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
796
+ }
797
+ })
798
+ state.flushState()
799
+ }
800
+ const post = (prefix, endpoint, payload) => send(prefix.route, prefix.base + '/' + endpoint, { method: 'POST', body: envelope(endpoint, payload) })
801
+ for (const prefix of prefixes) {
802
+ seedGlobalActive()
803
+ auth.callbackMode = 'present'
804
+ auth.libraryDecision = true
805
+ auth.libraryCalls = 0
806
+ const embedded = await post(prefix, 'archiveMemory', { scope: 'global', sessionId, id: 'mem-global-lifecycle' })
807
+ assert.equal(embedded.res.status, 200, `${prefix.name}: a live binding may archive global memory without the host callback`)
808
+ assert.equal(JSON.parse(embedded.res.text).result.ok, true)
809
+ assert.equal(state.loadGlobalIndex().entries['mem-global-lifecycle'].status, 'archived')
810
+ assert.equal(auth.libraryCalls, 0)
811
+
812
+ seedGlobalActive()
813
+ const ghost = await post(prefix, 'archiveMemory', { scope: 'global', sessionId: 'ghost-session', id: 'mem-global-lifecycle' })
814
+ assert.equal(ghost.res.status, 403, `${prefix.name}: a dangling session is never a credential`)
815
+ assert.equal(state.loadGlobalIndex().entries['mem-global-lifecycle'].status, 'active', 'a denied write must not touch the store')
816
+
817
+ const conflict = await post(prefix, 'archiveMemory', { scope: 'global', libraryId: 'lib-whatever', id: 'mem-global-lifecycle' })
818
+ assert.equal(conflict.res.status, 403, `${prefix.name}: scope global alongside a libraryId is a scope conflict`)
819
+
820
+ const rows = [
821
+ ['archiveMemory', { scope: 'global', id: 'mem-global-lifecycle' }],
822
+ ['updateMemory', { scope: 'global', id: 'mem-global-lifecycle', patch: { status: 'active' } }],
823
+ ['deleteMemory', { scope: 'global', id: 'mem-global-lifecycle', confirmed: true }],
824
+ ]
825
+ for (const [endpoint, payload] of rows) {
826
+ seedGlobalActive()
827
+ if (endpoint !== 'archiveMemory') {
828
+ state.updateGlobalIndex((index) => { index.entries['mem-global-lifecycle'].status = 'archived' })
829
+ }
830
+ auth.callbackMode = 'present'
831
+ auth.libraryDecision = true
832
+ auth.libraryCalls = 0
833
+ auth.libraryRequests.length = 0
834
+ const granted = await post(prefix, endpoint, payload)
835
+ assert.equal(granted.res.status, 200, `${prefix.name} ${endpoint}: review.manage true must grant`)
836
+ assert.equal(JSON.parse(granted.res.text).result.ok, true)
837
+ assert.equal(auth.libraryCalls, 1)
838
+ assert.equal(auth.libraryRequests.at(-1).libraryId, null, 'global lifecycle authorizes with libraryId null')
839
+ assert.equal(auth.libraryRequests.at(-1).operation, 'review.manage')
840
+
841
+ seedGlobalActive()
842
+ auth.libraryDecision = false
843
+ auth.libraryCalls = 0
844
+ assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: review.manage false must deny`)
845
+ assert.equal(auth.libraryCalls, 1)
846
+
847
+ auth.callbackMode = 'throw'
848
+ auth.libraryDecision = true
849
+ assert.equal((await post(prefix, endpoint, payload)).res.status, 403, `${prefix.name} ${endpoint}: a thrown callback must deny`)
850
+
851
+ auth.callbackMode = 'absent'
852
+ assert.equal((await post(prefix, endpoint, payload)).res.status, 200, `${prefix.name} ${endpoint}: absent callback falls back to the HTTP boundary`)
853
+ auth.callbackMode = 'present'
854
+ }
855
+ }
856
+ })
857
+
786
858
 
787
859
  // ---- 2026-11-01 现场(Unexpected token "forbidden" / Invalid RPC response: 403)----
788
860
  // 无 libraryId 的 browseWall("全部记忆库"视图)曾被硬拒 403:capability 缺席的宿主
@@ -135,7 +135,8 @@ test('the wall drawer reads exactly one memory', async () => {
135
135
  assert.match(source, /function WallCover/, 'cards use the first usable attachment as a cover')
136
136
  assert.match(source, /className: 'dshm-wall-cover'/)
137
137
  assert.match(source, /detail\.file\?\.status === 'archived'/, 'delete is offered only for archived memories')
138
- assert.match(source, /call\('deleteMemory', \{ libraryId: current\.item\.libraryId/)
138
+ assert.match(source, /call\('deleteMemory', \{\s*\.\.\.\(current\.item\.libraryId \? \{ libraryId: current\.item\.libraryId \} : \{ scope: 'global' \}\)/, 'the drawer delete names its target: private libraryId or explicit global scope')
139
+ assert.match(source, /id: current\.item\.id, confirmed: true/, 'the drawer delete always carries explicit confirmation')
139
140
  assert.match(source, /t\('confirmDelete'\)/, 'deleting takes a second click')
140
141
  assert.match(source, /current\.file\.status !== 'archived'/, 'the delete handler refuses live memories')
141
142
  })