183 lines
9.3 KiB
JavaScript
183 lines
9.3 KiB
JavaScript
// Round-2 regression tests for the Mnemon LongMemory driver (#9 #10).
|
|
// Runs against the built lib/ output; no DSH host, no real service, no token.
|
|
// #9 the account-wide default space (no projectId) reads memories from any
|
|
// project the account can see, while project-bound spaces stay strict.
|
|
// #10 write receipts classify stored / pending / unknown from the explicit
|
|
// state first, never claim stored on a staged or malformed receipt.
|
|
import { mkdtempSync } from 'node:fs'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
|
|
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'dsh-mnemon-round2-'))
|
|
|
|
const { LongMemoryProvider, classifyWriteReceipt } = await import('./lib/mnemon/driver.js')
|
|
|
|
const results = []
|
|
function check(name, ok, detail) {
|
|
results.push({ name, ok })
|
|
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail === undefined ? '' : ` :: ${detail}`}`)
|
|
}
|
|
|
|
// ---- Stub LongMemory remote ---------------------------------------------------
|
|
const memories = [
|
|
{ id: 'm-none', content: '无项目记忆 alpha', project_id: null },
|
|
{ id: 'm-a', content: '项目A记忆 alpha', project_id: 'proj-a' },
|
|
{ id: 'm-b', content: '项目B记忆 beta', project_id: 'proj-b' },
|
|
]
|
|
function makeRemote(store = memories) {
|
|
return {
|
|
async search(query, k, project) {
|
|
const matches = store.filter((hit) =>
|
|
hit.content.includes(query) && (project === undefined || hit.project_id === project))
|
|
return { ok: true, data: { matches: matches.slice(0, k), total: matches.length } }
|
|
},
|
|
async read(id) {
|
|
const hit = store.find((item) => item.id === id)
|
|
return hit === undefined
|
|
? { ok: false, error: { status: 404, code: 'not_found', message: 'not found' } }
|
|
: { ok: true, data: hit }
|
|
},
|
|
async list(options = {}) {
|
|
const items = store.filter((hit) => options.project === undefined || hit.project_id === options.project)
|
|
return { ok: true, data: { items: items.slice(0, options.limit ?? 100), total: items.length } }
|
|
},
|
|
async add() { throw new Error('unexpected add') },
|
|
async projects() { return { ok: true, data: { projects: [] } } },
|
|
async storageStatus() { return { ok: true, data: {} } },
|
|
}
|
|
}
|
|
const makeProvider = (remote, authority) =>
|
|
new LongMemoryProvider(authority, {}, { forConnection: () => remote, current: () => remote })
|
|
|
|
const defaultSpace = { id: 'space-default', connection: {} }
|
|
const spaceA = { id: 'space-a', connection: { endpoint: 'https://lm.test/api/longmemory', token: 'cmt_fake', projectId: 'proj-a' } }
|
|
const spaceB = { id: 'space-b', connection: { projectId: 'proj-b' } }
|
|
|
|
// ═══ 1. Default (all) space: search across projects, then read each hit ══════
|
|
{
|
|
const provider = makeProvider(makeRemote())
|
|
const found = await provider.search(defaultSpace, { query: 'alpha' })
|
|
check('default space search returns project memories too',
|
|
found.results.length === 2 && found.results.some((item) => item.id === 'm-a'),
|
|
found.results.map((item) => item.id).join(','))
|
|
|
|
for (const hit of found.results) {
|
|
const got = await provider.get(defaultSpace, hit.id)
|
|
check(`default space follows search hit ${hit.id} with get`, got?.id === hit.id && got?.content === hit.content)
|
|
}
|
|
|
|
const noProject = await provider.get(defaultSpace, 'm-none')
|
|
check('default space reads a memory that has no project', noProject?.id === 'm-none', noProject?.id)
|
|
|
|
const projectB = await provider.get(defaultSpace, 'm-b')
|
|
check('default space reads a memory from any project the account can see', projectB?.id === 'm-b', projectB?.id)
|
|
|
|
const listed = await provider.list(defaultSpace, { limit: 10 })
|
|
check('default space list exposes project memories', listed.some((item) => item.id === 'm-a') && listed.some((item) => item.id === 'm-b'))
|
|
}
|
|
|
|
// ═══ 2. Project-bound space: same hit readable, cross-project rejected ═══════
|
|
{
|
|
const provider = makeProvider(makeRemote())
|
|
const found = await provider.search(spaceA, { query: 'alpha' })
|
|
check('project space search only returns its own project',
|
|
found.results.length === 1 && found.results[0].id === 'm-a',
|
|
found.results.map((item) => item.id).join(','))
|
|
|
|
const own = await provider.get(spaceA, 'm-a')
|
|
check('project space reads the same hit from search', own?.id === 'm-a' && own?.content === '项目A记忆 alpha')
|
|
|
|
const cross = await provider.get(spaceA, 'm-b')
|
|
check('project space rejects a memory from another project', cross === undefined, cross?.id)
|
|
|
|
const noProject = await provider.get(spaceA, 'm-none')
|
|
check('project space rejects a memory with no project', noProject === undefined, noProject?.id)
|
|
|
|
const otherProvider = makeProvider(makeRemote())
|
|
const otherCross = await otherProvider.get(spaceB, 'm-a')
|
|
check('project B space rejects project A memory', otherCross === undefined, otherCross?.id)
|
|
}
|
|
|
|
// ═══ 3. Authority-bound projectId is enforced exactly like body connection ══
|
|
{
|
|
const authority = {
|
|
list: () => [],
|
|
runner: { effectiveDataDir: () => process.env.DSH_HOME },
|
|
providerConnection: () => ({ endpoint: 'https://lm.test', token: 'cmt_fake', projectId: 'proj-a' }),
|
|
}
|
|
const provider = makeProvider(makeRemote(), authority)
|
|
const body = { id: 'space-authority', connection: {} }
|
|
check('authority-bound project reads its own memory', (await provider.get(body, 'm-a'))?.id === 'm-a')
|
|
check('authority-bound project rejects another project memory', (await provider.get(body, 'm-b')) === undefined)
|
|
}
|
|
|
|
// ═══ 4. Receipt classification matrix ═══════════════════════════════════════
|
|
const cases = [
|
|
['remote_saved true', { remote_saved: true, id: 'm1', revision: 1 }, 'stored'],
|
|
['remote_saved false', { remote_saved: false, id: 'm2' }, 'pending'],
|
|
['state pending beats id', { id: 'm1', state: 'pending' }, 'pending'],
|
|
['state queued', { id: 'm3', state: 'queued' }, 'pending'],
|
|
['state stored', { id: 'm4', state: 'stored' }, 'stored'],
|
|
['state saved', { state: 'saved' }, 'stored'],
|
|
['state completed', { state: 'completed' }, 'stored'],
|
|
['state pending uppercase', { state: 'PENDING' }, 'pending'],
|
|
['state with whitespace', { state: ' stored ' }, 'stored'],
|
|
['unknown state is unknown', { id: 'm5', state: 'processing' }, 'unknown'],
|
|
['stored state conflicts with remote_saved false', { id: 'm6', state: 'stored', remote_saved: false }, 'pending'],
|
|
['pending state conflicts with remote_saved true', { id: 'm7', state: 'pending', remote_saved: true }, 'pending'],
|
|
['empty receipt is unknown', {}, 'unknown'],
|
|
['null receipt is unknown', null, 'unknown'],
|
|
['undefined receipt is unknown', undefined, 'unknown'],
|
|
['string receipt is unknown', 'ok', 'unknown'],
|
|
['array receipt is unknown', [], 'unknown'],
|
|
['invalid state type falls through to remote_saved', { state: 42, remote_saved: true }, 'stored'],
|
|
['invalid remote_saved type is ignored', { remote_saved: 'true', id: 'm8' }, 'stored'],
|
|
['invalid id/revision types are unknown', { id: 123, revision: '1' }, 'unknown'],
|
|
['legacy id-only receipt is stored', { id: 'm9' }, 'stored'],
|
|
['legacy revision-only receipt is stored', { revision: 2 }, 'stored'],
|
|
]
|
|
for (const [name, receipt, expected] of cases) {
|
|
let actual
|
|
let failure
|
|
try {
|
|
actual = classifyWriteReceipt(receipt)
|
|
} catch (error) {
|
|
failure = error instanceof Error ? error.message : String(error)
|
|
}
|
|
check(`classify receipt: ${name}`, failure === undefined && actual === expected,
|
|
failure === undefined ? String(actual) : `threw ${failure}`)
|
|
}
|
|
|
|
// ═══ 5. remember() surfaces the same classification end to end ═════════════
|
|
async function rememberWith(data) {
|
|
const provider = makeProvider({ add: async () => ({ ok: true, data }) })
|
|
return provider.remember(defaultSpace, { content: '记住我' })
|
|
}
|
|
{
|
|
const pending = await rememberWith({ id: 'm1', state: 'pending' })
|
|
check('remember {id,state:pending} reports pending, not stored', pending.action === 'pending', JSON.stringify(pending))
|
|
|
|
const stored = await rememberWith({ remote_saved: true, id: 'm2', revision: 1 })
|
|
check('remember remote_saved true reports stored', stored.action === 'stored' && stored.id === 'm2', JSON.stringify(stored))
|
|
|
|
const staged = await rememberWith({ remote_saved: false, id: 'm3' })
|
|
check('remember remote_saved false reports pending', staged.action === 'pending', JSON.stringify(staged))
|
|
|
|
const empty = await rememberWith({})
|
|
check('remember empty receipt reports unknown', empty.action === 'unknown', JSON.stringify(empty))
|
|
|
|
const missing = await rememberWith(undefined)
|
|
check('remember missing receipt reports unknown', missing.action === 'unknown', JSON.stringify(missing))
|
|
|
|
const conflict = await rememberWith({ id: 'm4', state: 'stored', remote_saved: false })
|
|
check('remember conflicting receipt never reports stored', conflict.action === 'pending', JSON.stringify(conflict))
|
|
|
|
const malformed = await rememberWith({ id: 123, revision: '1', remote_saved: true })
|
|
check('remember malformed id/revision are not echoed back',
|
|
malformed.action === 'stored' && !('id' in malformed) && !('revision' in malformed), JSON.stringify(malformed))
|
|
}
|
|
|
|
const failed = results.filter((item) => !item.ok).length
|
|
console.log(failed === 0 ? `\nALL ${results.length} ROUND-2 CHECKS PASSED` : `\n${failed} CHECK(S) FAILED`)
|
|
process.exit(failed === 0 ? 0 : 1)
|