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 用非消费式 events 观察终态,不调用 wait、不抑制通知', async () => { const { store, cleanup } = await tempStore() try { await store.saveProject({ ...PROJECT, workDir: 'C:/work/background-root' }) let notify const subscriptions = [] const waitCalls = [] const jobs = { wait(...args) { waitCalls.push(args); return Promise.resolve({ status: 'completed' }) }, get: () => ({ id: 'pwsh-0123456789abcdef', status: 'running' }), events: { subscribe(filter, callback) { subscriptions.push({ filter, callback }) notify = callback return () => { notify = undefined } }, }, } 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(waitCalls.length, 0, '不能用 wait 消费原生完成通知') assert.deepEqual(subscriptions[0].filter, { owner: 'sess-shang' }) assert.match(store.rootLeaseOf('C:/work/background-root')?.holder ?? '', /^b-shang:call-bg:/, 'job 没结束前租约必须保留') notify({ type: 'settled', job: { id: 'pwsh-0123456789abcdef', status: 'completed' }, awaited: false }) await new Promise(resolve => setTimeout(resolve, 20)) assert.equal(store.rootLeaseOf('C:/work/background-root'), undefined, '终态事件后释放租约') } finally { await cleanup() } }) test('Q08f:订阅前 job 已终态也能立即释放租约', async () => { const { store, cleanup } = await tempStore() try { await store.saveProject({ ...PROJECT, workDir: 'C:/work/background-race' }) const jobs = { get: () => ({ id: 'pwsh-0123456789abcdef', status: 'completed' }), events: { subscribe: () => () => {} }, } const { dsbot, ctx } = fakeEnv({ goal: goalAt(), jobs }) installObserver({ ctx, store, dsbot, bootId: newBootId() }) await ctx.handlers['tools/execute']( { name: 'pwsh', id: 'call-race', arguments: { command: 'fast' }, agent: { id: 'sess-shang' } }, async () => ({ content: [{ type: 'text', text: 'started background job pwsh-0123456789abcdef' }] }), ) await new Promise(resolve => setTimeout(resolve, 20)) assert.equal(store.rootLeaseOf('C:/work/background-race'), undefined) } finally { await cleanup() } }) test('Q08g:父子嵌套根写同一文件时按实际目标路径互斥', async () => { const { store, cleanup } = await tempStore() try { await store.saveProject({ ...PROJECT, id: 'prj-a', roomId: 'room-a', workDir: 'C:/work', bots: { lead: 'b-a', shangshu: 'b-a-shang', gongbu: 'b-a-gong' } }) await store.saveProject({ ...PROJECT, id: 'prj-b', roomId: 'room-b', workDir: 'C:/work/sub', bots: { lead: 'b-b', shangshu: 'b-b-shang', gongbu: 'b-b-gong' } }) const rooms = { 'room-a': { id: 'room-a', name: 'A', members: ['b-a'], admin: 'b-a', sessions: {} }, 'room-b': { id: 'room-b', name: 'B', members: ['b-b'], admin: 'b-b', sessions: {} }, } const bots = { 'b-a': { id: 'b-a', name: 'A' }, 'b-b': { id: 'b-b', name: 'B' } } const dsbot = { selfOf: id => (id === 'sess-a' ? 'b-a' : id === 'sess-b' ? 'b-b' : undefined), roomOfSession: id => (id === 'sess-a' ? 'room-a' : id === 'sess-b' ? 'room-b' : undefined), roomOf: id => rooms[id], botOf: id => bots[id], isMain: () => false, pickRoom: () => ({ error: 'no' }), } const ctx = { handlers: {}, on(event, handler) { this.handlers[event] = handler }, get() { return undefined } } installObserver({ ctx, store, dsbot, bootId: newBootId() }) let release const gate = new Promise(resolve => { release = resolve }) const first = ctx.handlers['tools/execute']( { name: 'write', id: 'nested-1', arguments: { path: 'C:/work/sub/shared.txt' }, agent: { id: 'sess-a' } }, async () => { await gate; return 'written' }, ) await new Promise(resolve => setTimeout(resolve, 5)) const second = await ctx.handlers['tools/execute']( { name: 'write', id: 'nested-2', arguments: { path: 'C:/work/sub/shared.txt' }, agent: { id: 'sess-b' } }, async () => 'written', ) assert.match(String(second), /同一实际路径不能并发写/) release() await first } finally { await cleanup() } }) test('Q08h:文件工具目标越出项目工作根时明确拒绝', async () => { const { store, cleanup } = await tempStore() try { await store.saveProject({ ...PROJECT, workDir: 'C:/work/inside' }) const { dsbot, ctx } = fakeEnv({ goal: goalAt() }) installObserver({ ctx, store, dsbot, bootId: newBootId() }) let called = false const result = await ctx.handlers['tools/execute']( { name: 'write', id: 'outside', arguments: { path: 'C:/elsewhere/secret.txt' }, agent: { id: 'sess-shang' } }, async () => { called = true; return 'written' }, ) assert.equal(called, false) assert.match(String(result), /超出项目工作根/) assert.equal(store.rootLeaseOf('C:/work/inside'), undefined) } finally { await cleanup() } })