302 lines
12 KiB
JavaScript
302 lines
12 KiB
JavaScript
import assert from 'node:assert/strict'
|
||
import { mkdtemp, rm } from 'node:fs/promises'
|
||
import { tmpdir } from 'node:os'
|
||
import { join } from 'node:path'
|
||
import test from 'node:test'
|
||
import { installObserver } from '../src/observe.js'
|
||
import { newBootId } from '../src/records.js'
|
||
import { SanshengStore } from '../src/store.js'
|
||
|
||
async function tempStore() {
|
||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-dispatch-'))
|
||
const store = new SanshengStore(join(dir, 'state.json'))
|
||
await store.load()
|
||
return { dir, store, cleanup: () => rm(dir, { recursive: true, force: true }) }
|
||
}
|
||
|
||
const PROJECT = {
|
||
id: 'prj-dispatch',
|
||
name: '派发项目',
|
||
roomId: 'room-1',
|
||
bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' },
|
||
maxReworks: 3,
|
||
}
|
||
|
||
function goalAt({ revision = 4, reworks = 0 } = {}) {
|
||
return {
|
||
id: 'goal-1',
|
||
revision,
|
||
status: 'active',
|
||
current: 0,
|
||
objective: '交付',
|
||
acceptance: '测试',
|
||
constraints: [],
|
||
stages: [{
|
||
id: 's1', title: '阶段一', acceptance: '能跑', status: 'active', reworks,
|
||
tasks: [{ id: 't1', botId: 'b-gong', task: '做', status: 'done', note: '' }],
|
||
feedback: '缺测试',
|
||
}],
|
||
}
|
||
}
|
||
|
||
function fakeEnv({ goal = goalAt(), deliver, jobs } = {}) {
|
||
const room = {
|
||
id: 'room-1', name: '派发项目 · 三省六部', admin: 'b-shang',
|
||
members: ['b-lead', 'b-shang', 'b-gong'],
|
||
sessions: { 'b-gong': 'sess-gong' },
|
||
goal,
|
||
}
|
||
const bots = {
|
||
'b-lead': { id: 'b-lead', name: '丞相' },
|
||
'b-shang': { id: 'b-shang', name: '尚书' },
|
||
'b-gong': { id: 'b-gong', name: '工部' },
|
||
}
|
||
const dsbot = {
|
||
selfOf: id => (id === 'sess-shang' ? 'b-shang' : undefined),
|
||
roomOfSession: id => (id === 'sess-shang' ? 'room-1' : undefined),
|
||
roomOf: () => room,
|
||
botOf: id => bots[id],
|
||
isMain: () => false,
|
||
pickRoom: () => ({ error: 'no room' }),
|
||
}
|
||
const calls = []
|
||
const rt = {
|
||
deliver: async payload => {
|
||
calls.push(payload)
|
||
if (deliver) await deliver(payload)
|
||
},
|
||
}
|
||
const ctx = {
|
||
handlers: {},
|
||
on(event, handler) { this.handlers[event] = handler },
|
||
get(name) { return name === 'jobs' ? jobs : rt },
|
||
}
|
||
return { room, dsbot, ctx, calls }
|
||
}
|
||
|
||
const exec = { name: 'group_goal', arguments: { action: 'rework', reason: '缺测试' }, agent: { id: 'sess-shang' } }
|
||
|
||
test('R01:业务拒绝字符串不记 confirmed,也不触发返工投递', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject(PROJECT)
|
||
const { dsbot, ctx, calls } = fakeEnv({ goal: goalAt() })
|
||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||
const result = await ctx.handlers['tools/execute'](exec, async () => ({
|
||
content: [{ type: 'text', text: 'Only 尚书, the admin of "派发项目", or a Main Bot changes its goal.' }],
|
||
}))
|
||
assert.match(result.content[0].text, /Only 尚书/)
|
||
const record = store.peek().dispatches.at(-1)
|
||
assert.equal(record.status, 'rejected', '业务拒绝不能当成功')
|
||
assert.match(record.nativeResult.text, /Only 尚书/)
|
||
assert.equal(calls.length, 0, '业务拒绝不触发返工')
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('R02:同 requestId 同 payload 重放不重复写,不同 payload 拒绝', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject(PROJECT)
|
||
const base = { id: 'dsp-1', requestId: 'req-1', payloadDigest: 'aaa', projectId: PROJECT.id, action: 'pass' }
|
||
const first = await store.beginDispatch(base)
|
||
assert.equal(first.replay, false)
|
||
const second = await store.beginDispatch({ ...base, id: 'dsp-2' })
|
||
assert.equal(second.replay, true)
|
||
assert.equal(second.record.id, 'dsp-1')
|
||
assert.equal(store.peek().dispatches.length, 1)
|
||
await assert.rejects(
|
||
() => store.beginDispatch({ ...base, id: 'dsp-3', payloadDigest: 'bbb' }),
|
||
error => error.code === 'payload-conflict',
|
||
)
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('R03:发送中重启后标为 unknown,已确认记录不被改写', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject(PROJECT)
|
||
await store.beginDispatch({ id: 'dsp-1', requestId: 'req-1', payloadDigest: 'a', projectId: PROJECT.id, action: 'pass' })
|
||
await store.markDispatchInFlight('dsp-1')
|
||
await store.beginDispatch({ id: 'dsp-2', requestId: 'req-2', payloadDigest: 'b', projectId: PROJECT.id, action: 'pass' })
|
||
await store.finishDispatch('dsp-2', { status: 'confirmed' })
|
||
const marked = await store.reconcileDispatches('boot-x')
|
||
assert.equal(marked, 1)
|
||
assert.equal(store.peek().dispatches.find(item => item.id === 'dsp-1').status, 'unknown')
|
||
assert.equal(store.peek().dispatches.find(item => item.id === 'dsp-2').status, 'confirmed')
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('R05:同一返工版本重复观测只投递一次', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject(PROJECT)
|
||
const before = goalAt({ revision: 4, reworks: 0 })
|
||
const { dsbot, ctx, calls } = fakeEnv({ goal: before })
|
||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||
const run = async () => {
|
||
dsbot.roomOf().goal = goalAt({ revision: 4, reworks: 0 })
|
||
return ctx.handlers['tools/execute'](exec, async () => {
|
||
dsbot.roomOf().goal = goalAt({ revision: 5, reworks: 1 })
|
||
return { content: [{ type: 'text', text: '已驳回' }] }
|
||
})
|
||
}
|
||
await run()
|
||
// 第二次模拟同一次返工回执重放:同样的目标版本与结果
|
||
await run()
|
||
assert.equal(calls.length, 1, '重复回执不能再次投递')
|
||
assert.equal(store.reworksFor(PROJECT.id).length, 1)
|
||
const auto = store.peek().dispatches.filter(item => item.action === 'auto_rework')
|
||
assert.equal(auto.length, 1, '同一返工版本只应有一条派发记录')
|
||
assert.equal(auto[0].status, 'confirmed')
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('R04:事务失败回滚内存状态,不留下虚假成功', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
const project = { ...PROJECT }
|
||
await store.saveProject(project)
|
||
await assert.rejects(
|
||
() => store.saveProject({ ...project, id: 'prj-other', name: '另一个', roomId: 'room-other' }),
|
||
error => error.code === 'bot-taken',
|
||
)
|
||
assert.equal(Object.keys(store.peek().projects).length, 1)
|
||
assert.equal(store.projectById('prj-other'), undefined)
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q05:派发意图写入失败时阻止原生执行,不留下“执行了但没记录”', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject(PROJECT)
|
||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||
store.beginDispatch = async () => { throw new Error('磁盘写失败') }
|
||
let called = false
|
||
const result = await ctx.handlers['tools/execute'](exec, async () => { called = true; return { content: [] } })
|
||
assert.equal(called, false, '记账失败必须停止原生命令')
|
||
assert.match(String(result), /无法写入派发记录/)
|
||
assert.equal(store.peek().dispatches.length, 0)
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q05b:markInFlight 失败时也阻止原生执行,并把记录标为 unknown', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject(PROJECT)
|
||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||
store.markDispatchInFlight = async () => { throw new Error('状态写失败') }
|
||
let called = false
|
||
const result = await ctx.handlers['tools/execute'](exec, async () => { called = true; return { content: [] } })
|
||
assert.equal(called, false)
|
||
assert.match(String(result), /本次目标修改未执行/)
|
||
assert.equal(store.peek().dispatches.at(-1).status, 'unknown')
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q08b:真实文件写入口按工作根互斥,执行结束释放', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject({ ...PROJECT, workDir: 'C:/work/shared-root' })
|
||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||
let release
|
||
const gate = new Promise(resolve => { release = resolve })
|
||
let firstCalled = false
|
||
let secondCalled = false
|
||
const first = ctx.handlers['tools/execute'](
|
||
{ name: 'write', id: 'call-1', arguments: { path: 'a.txt' }, agent: { id: 'sess-shang' } },
|
||
async () => { firstCalled = true; await gate; return 'written' },
|
||
)
|
||
await new Promise(resolve => setTimeout(resolve, 5))
|
||
const second = await ctx.handlers['tools/execute'](
|
||
{ name: 'write', id: 'call-2', arguments: { path: 'b.txt' }, agent: { id: 'sess-shang' } },
|
||
async () => { secondCalled = true; return 'written' },
|
||
)
|
||
assert.equal(secondCalled, false, '同一工作根并发写必须被拒绝')
|
||
assert.match(String(second), /同一实际路径不能并发写/)
|
||
release()
|
||
assert.equal(await first, 'written')
|
||
assert.equal(firstCalled, true)
|
||
assert.equal(store.rootLeaseOf('C:/work/shared-root'), undefined, '写完成后释放根租约')
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q05c:原生已执行但回执写入失败时,记录标为 unknown 而不是 confirmed', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject(PROJECT)
|
||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||
const original = store.finishDispatch.bind(store)
|
||
let first = true
|
||
store.finishDispatch = async (...args) => {
|
||
if (first) { first = false; throw new Error('回执写失败') }
|
||
return original(...args)
|
||
}
|
||
let called = false
|
||
const result = await ctx.handlers['tools/execute'](exec, async () => {
|
||
called = true
|
||
dsbot.roomOf().goal = goalAt({ revision: 5, reworks: 1 })
|
||
return { content: [{ type: 'text', text: '已驳回' }] }
|
||
})
|
||
assert.equal(called, true)
|
||
assert.match(result.content[0].text, /已驳回/)
|
||
const record = store.peek().dispatches.at(-1)
|
||
assert.equal(record.status, 'unknown')
|
||
assert.match(record.note, /回执记录失败/)
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q08e:后台 job 结果把租约交给 ctx.jobs.wait,job 结束才释放', async () => {
|
||
const { store, cleanup } = await tempStore()
|
||
try {
|
||
await store.saveProject({ ...PROJECT, workDir: 'C:/work/background-root' })
|
||
let finishJob
|
||
const jobDone = new Promise(resolve => { finishJob = resolve })
|
||
const waited = []
|
||
const jobs = {
|
||
wait(id, timeoutMs, caller) {
|
||
waited.push({ id, timeoutMs, caller })
|
||
return jobDone.then(() => ({ id, status: 'completed' }))
|
||
},
|
||
}
|
||
const { dsbot, ctx } = fakeEnv({ goal: goalAt(), jobs })
|
||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||
const result = await ctx.handlers['tools/execute'](
|
||
{ name: 'pwsh', id: 'call-bg', arguments: { command: 'long' }, agent: { id: 'sess-shang' } },
|
||
async () => ({ content: [{ type: 'text', text: 'started background job pwsh-0123456789abcdef' }] }),
|
||
)
|
||
assert.match(result.content[0].text, /background job/)
|
||
assert.equal(waited.length, 1, '应把 job 交给 wait')
|
||
assert.equal(waited[0].id, 'pwsh-0123456789abcdef')
|
||
assert.equal(waited[0].caller, 'sess-shang')
|
||
assert.match(store.rootLeaseOf('C:/work/background-root')?.holder ?? '', /^b-shang:call-bg:/, 'job 没结束前租约必须保留')
|
||
|
||
finishJob()
|
||
await new Promise(resolve => setTimeout(resolve, 20))
|
||
assert.equal(store.rootLeaseOf('C:/work/background-root'), undefined, 'job 结束后释放租约')
|
||
} finally {
|
||
await cleanup()
|
||
}
|
||
})
|