workspaceKnowledge.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // @vitest-environment node
  2. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  3. import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  4. import { join } from 'node:path'
  5. import { tmpdir } from 'node:os'
  6. import { randomUUID } from 'node:crypto'
  7. import { WorkspaceStore } from '../../src/server/workspaceStore'
  8. import { MEMORY_CONTEXT_MAX_CHARS, WorkspaceKnowledge } from '../../src/server/workspaceKnowledge'
  9. import { acknowledgeMemory, memoryResetReason, memoryDelta, emptyMemoryContext } from '../../src/server/workspaceMemoryContext'
  10. import type { WorkspaceAgent, WorkspaceMessage } from '../../src/shared/workspace'
  11. let home: string, store: WorkspaceStore, knowledge: WorkspaceKnowledge, a: WorkspaceAgent, b: WorkspaceAgent
  12. const owner = 'memory-owner'
  13. beforeEach(() => {
  14. home = mkdtempSync(join(tmpdir(), 'yaoyao-file-memory-'))
  15. store = new WorkspaceStore(home); knowledge = new WorkspaceKnowledge(home, store)
  16. a = store.createAgent(owner, { name: '甲', profile: 'same-profile', canManageTeam: true })
  17. b = store.createAgent(owner, { name: '乙', profile: 'same-profile' })
  18. })
  19. afterEach(() => { store.close(); rmSync(home, { recursive: true, force: true }) })
  20. function source(content: string) {
  21. const conversation = store.list<any>(owner, 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === a.id)
  22. const message: WorkspaceMessage = { id: randomUUID(), conversationId: conversation.id, seq: 0, role: 'user', content, reasoning: '', status: 'complete', attachments: [], tools: [], createdAt: Date.now() }
  23. store.saveMessage(owner, message)
  24. return { messageId: message.id, conversationId: message.conversationId, quote: content }
  25. }
  26. describe('Bot file memory', () => {
  27. it('retains case-insensitive keyword filtering for local files', async () => {
  28. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'agent', agentId: a.id, content: 'API uses JSON', tier: 'profile' })
  29. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'agent', agentId: a.id, content: '用户偏爱低糖饮食', tier: 'profile' })
  30. expect((await knowledge.memories(owner, { scope: 'agent', agentId: a.id, search: 'json' })).map(memory => memory.content)).toEqual(['API uses JSON'])
  31. expect(await knowledge.memories(owner, { scope: 'agent', agentId: a.id, search: '饮食习惯' })).toEqual([])
  32. })
  33. it('does not change the injected version for unselected notes or source metadata', async () => {
  34. const input = { scope: 'agent' as const, agentId: a.id, content: '稳定事实', tier: 'profile' as const }
  35. const fact = await knowledge.writeMemory(owner, { ...input, requestId: randomUUID() })
  36. const before = await knowledge.context(owner, a.id), state = acknowledgeMemory(before)
  37. await knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), id: fact.id, expectedRevision: fact.revision, topic: '仅更新主题' })
  38. await knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), content: '未注入的短暂信息', tier: 'note' })
  39. const after = await knowledge.context(owner, a.id)
  40. expect(after.version).toBe(before.version)
  41. expect(memoryDelta(after, state)).toBe('')
  42. expect(memoryResetReason(after, state)).toBeUndefined()
  43. expect(memoryResetReason(await knowledge.context(owner, b.id), state)).toBe('memory_scope_changed')
  44. expect(memoryResetReason(emptyMemoryContext('unsupported'), state)).toBe('memory_scope_changed')
  45. expect(memoryResetReason(after, undefined, 'old-version')).toBe('memory_baseline_missing')
  46. })
  47. it('keeps reuse safe when bounded context evicts old facts, including later deletion of an evicted fact', async () => {
  48. const input = { scope: 'agent' as const, agentId: a.id, tier: 'profile' as const }
  49. const old = await knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), content: '原先注入的事实'.padEnd(2000, '旧') })
  50. const state = acknowledgeMemory(await knowledge.context(owner, a.id))
  51. for (let index = 0; index < 8; index++) await knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), content: `新增事实-${index}`.padEnd(2000, '新') })
  52. const current = await knowledge.context(owner, a.id)
  53. expect(current.text).not.toContain('原先注入的事实')
  54. expect(memoryResetReason(current, state)).toBeUndefined()
  55. expect(memoryDelta(current, state)).toContain('新增事实')
  56. const next = acknowledgeMemory(current, state)
  57. await knowledge.forget(owner, { ...input, requestId: randomUUID(), id: old.id, expectedRevision: old.revision })
  58. expect(memoryResetReason(await knowledge.context(owner, a.id), next)).toBe('memory_changed_or_removed')
  59. })
  60. it('bounds all three scopes together without truncating or deleting long profile facts', async () => {
  61. const project = knowledge.saveProject(owner, { requestId: randomUUID(), name: '长记忆项目', description: '', memberIds: [a.id], groupIds: [] })
  62. const all = []
  63. for (const scope of ['agent', 'project', 'user'] as const) {
  64. for (let index = 0; index < 6; index++) {
  65. const content = `${scope}-${index}:`.padEnd(2000, '甲')
  66. all.push(await knowledge.writeMemory(owner, { requestId: randomUUID(), scope, agentId: a.id, projectId: scope === 'project' ? project.id : undefined, content, tier: 'profile' }))
  67. }
  68. }
  69. const context = await knowledge.context(owner, a.id, project.id)
  70. expect(context.text.length).toBeLessThanOrEqual(MEMORY_CONTEXT_MAX_CHARS)
  71. for (const label of ['此 Bot 的记忆', '当前项目记忆', '用户共享记忆']) expect(context.text).toContain(label)
  72. const selected = context.text.split('\n').filter(line => line.startsWith('- '))
  73. expect(selected.length).toBeGreaterThanOrEqual(3)
  74. expect(selected.every(line => all.some(memory => line === `- ${memory.content}(profile;来源 Bot ${memory.agentId};记忆 ID ${memory.id})`))).toBe(true)
  75. const omitted = all.find(memory => !context.text.includes(memory.id))!
  76. expect(omitted).toBeDefined()
  77. const found = await knowledge.memories(owner, { scope: omitted.scope, agentId: a.id, projectId: omitted.projectId, search: omitted.content })
  78. expect(found.map(memory => memory.id)).toContain(omitted.id)
  79. expect((await knowledge.context(owner, a.id, project.id)).version).toBe(context.version)
  80. })
  81. it('prioritizes shared profile facts before recent private logs', async () => {
  82. for (let index = 0; index < 12; index++) await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'agent', agentId: a.id, content: `${index}:`.padEnd(2000, '历史'), tier: 'log' })
  83. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'user', agentId: b.id, content: '用户长期使用中文', tier: 'profile' })
  84. const context = await knowledge.context(owner, a.id)
  85. expect(context.text).toContain('用户长期使用中文')
  86. expect(context.text.length).toBeLessThanOrEqual(MEMORY_CONTEXT_MAX_CHARS)
  87. })
  88. it('preserves different shared contributions instead of overwriting the same topic', async () => {
  89. for (const [agent, content] of [[a, '接口使用版本一'], [b, '接口使用版本二']] as const) await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'user', agentId: agent.id, topic: '接口版本', content, tier: 'profile' })
  90. const memories = await knowledge.memories(owner, { scope: 'user' })
  91. expect(memories).toHaveLength(2)
  92. expect(memories.every(m => m.conflict)).toBe(true)
  93. expect(new Set(memories.map(m => m.agentId)).size).toBe(2)
  94. })
  95. it('keeps profile and log in the standing prompt and leaves notes out', async () => {
  96. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'agent', agentId: a.id, content: '基础职责', tier: 'profile' })
  97. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'agent', agentId: a.id, content: '昨天做过的事', tier: 'log' })
  98. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'agent', agentId: a.id, content: '马上会过期', tier: 'note' })
  99. const text = (await knowledge.context(owner, a.id)).text
  100. expect(text).toContain('基础职责')
  101. expect(text).toContain('昨天做过的事')
  102. expect(text).not.toContain('马上会过期')
  103. })
  104. it('isolates bots sharing one Profile and merges only shared user contributions', async () => {
  105. const fact = source('以后请使用中文回答')
  106. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'agent', agentId: a.id, content: '甲自己的经验', tier: 'profile' })
  107. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'user', agentId: a.id, content: '用户偏好中文', tier: 'profile', sources: [fact] }, { agentId: a.id })
  108. expect((await knowledge.context(owner, a.id)).text).toContain('甲自己的经验')
  109. expect((await knowledge.context(owner, b.id)).text).not.toContain('甲自己的经验')
  110. expect((await knowledge.context(owner, b.id)).text).toContain('用户偏好中文')
  111. expect((await knowledge.context(owner, a.id)).text).toContain('以自己的记忆为准')
  112. await expect(knowledge.memories(owner, { scope: 'agent', agentId: a.id }, { agentId: b.id })).rejects.toThrowError(expect.objectContaining({ code: 'memory_forbidden' }))
  113. await expect(knowledge.memories('other-owner', { scope: 'agent', agentId: a.id })).resolves.toEqual([])
  114. const body = readFileSync(join(home, 'bot-workspace', owner, 'agents', a.id, 'memory', 'profile.md'), 'utf8')
  115. expect(body).toMatch(/- \(\d{4}-\d{2}-\d{2}\) 甲自己的经验/)
  116. })
  117. it('keeps files authoritative and rebuilds project membership and group projections', async () => {
  118. const group = store.createGroup(owner, { name: '群', memberIds: [a.id, b.id], collaborationMode: 'discussion' })
  119. const requestId = randomUUID(), input = { requestId, name: '项目一', description: '共同工作', memberIds: [a.id, b.id], groupIds: [group.id] }
  120. const project = knowledge.saveProject(owner, input)
  121. expect(knowledge.saveProject(owner, input)).toEqual(project)
  122. store.remove(owner, 'project', project.id)
  123. const c = store.require<any>(owner, 'conversation', group.id); delete c.projectId; store.put(owner, 'conversation', c.id, c)
  124. knowledge = new WorkspaceKnowledge(home, store)
  125. expect(store.require<any>(owner, 'project', project.id).memberIds).toEqual([a.id, b.id].sort())
  126. expect(store.require<any>(owner, 'conversation', group.id).projectId).toBe(project.id)
  127. const fact = source('本项目使用版本化接口')
  128. await knowledge.writeMemory(owner, { requestId: randomUUID(), scope: 'project', projectId: project.id, agentId: a.id, content: '接口需要版本号', tier: 'profile', sources: [fact] }, { agentId: a.id })
  129. expect((await knowledge.context(owner, b.id, project.id)).text).toContain('接口需要版本号')
  130. expect((await knowledge.context(owner, b.id)).text).not.toContain('接口需要版本号')
  131. knowledge.saveProject(owner, { ...input, requestId: randomUUID(), id: project.id, expectedRevision: project.revision, memberIds: [a.id], groupIds: [] })
  132. await expect(knowledge.context(owner, b.id, project.id)).rejects.toThrowError(expect.objectContaining({ code: 'project_forbidden' }))
  133. })
  134. it('rejects stale revisions, cross-contributor writes and overwrite of user-maintained facts', async () => {
  135. const fact = source('以后请精简回复')
  136. const input = { requestId: randomUUID(), scope: 'user' as const, agentId: a.id, content: '用户喜欢简洁', tier: 'profile' as const, sources: [fact] }
  137. const initial = await knowledge.writeMemory(owner, input, { agentId: a.id })
  138. await expect(knowledge.writeMemory(owner, { ...input, requestId: randomUUID() }, { agentId: b.id })).rejects.toThrowError(expect.objectContaining({ code: 'memory_forbidden' }))
  139. const edited = await knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), id: initial.id, expectedRevision: 1, content: '回复简洁但保留依据' })
  140. expect(edited.revision).toBe(2)
  141. await expect(knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), id: initial.id, expectedRevision: 1 })).rejects.toThrowError(expect.objectContaining({ code: 'memory_revision_conflict' }))
  142. await expect(knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), id: initial.id, expectedRevision: 2 }, { agentId: a.id })).rejects.toThrowError(expect.objectContaining({ code: 'memory_manual_protected' }))
  143. expect(await knowledge.revisions(owner, input, initial.id)).toHaveLength(2)
  144. })
  145. it('keeps tombstones across restart and prevents old synthesis from resurrecting forgotten facts', async () => {
  146. const input = { requestId: randomUUID(), scope: 'agent' as const, agentId: a.id, content: '旧偏好', tier: 'profile' as const }
  147. const memory = await knowledge.writeMemory(owner, input)
  148. await knowledge.forget(owner, { ...input, requestId: randomUUID(), id: memory.id, expectedRevision: memory.revision })
  149. knowledge = new WorkspaceKnowledge(home, store)
  150. await expect(knowledge.writeMemory(owner, { ...input, requestId: randomUUID(), automatic: true, sources: [source('旧偏好')] }, { agentId: a.id })).rejects.toThrowError(expect.objectContaining({ code: 'memory_forgotten' }))
  151. expect(await knowledge.memories(owner, input)).toEqual([])
  152. expect((await knowledge.revisions(owner, input, memory.id))[0]?.operation).toBe('forget')
  153. })
  154. it('recovers a partially written multi-file transaction and does not duplicate its receipt or event', async () => {
  155. const input = { requestId: randomUUID(), scope: 'agent' as const, agentId: a.id, content: '需要恢复的事实', tier: 'profile' as const }
  156. knowledge.fault = path => { if (path.endsWith('profile.md')) throw new Error('simulated power loss') }
  157. await expect(knowledge.writeMemory(owner, input)).rejects.toThrow('simulated power loss')
  158. knowledge = new WorkspaceKnowledge(home, store)
  159. const restored = await knowledge.memories(owner, input)
  160. expect(restored).toHaveLength(1)
  161. expect(await knowledge.writeMemory(owner, input)).toEqual(restored[0])
  162. expect(store.events(owner, 0).filter(e => e.type === 'memory.changed')).toHaveLength(1)
  163. expect(await knowledge.revisions(owner, input, restored[0]!.id)).toHaveLength(1)
  164. })
  165. it('reports corrupted metadata without silently replacing it and rejects unsafe paths', async () => {
  166. const input = { requestId: randomUUID(), scope: 'agent' as const, agentId: a.id, content: '保留事实', tier: 'log' as const }
  167. await knowledge.writeMemory(owner, input)
  168. const path = join(home, 'bot-workspace', owner, 'agents', a.id, 'memory', '.dreaming', 'records.json')
  169. writeFileSync(path, '{broken')
  170. await expect(knowledge.memories(owner, input)).rejects.toThrowError(expect.objectContaining({ code: 'knowledge_file_corrupt' }))
  171. expect(readFileSync(path, 'utf8')).toBe('{broken')
  172. await expect(knowledge.memories(owner, { scope: 'project', projectId: '../other' })).rejects.toThrowError(expect.objectContaining({ code: 'knowledge_invalid_id' }))
  173. })
  174. })