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 { evaluateGoalAction } from '../src/gate.js' import { installObserver } from '../src/observe.js' import { detectRework, isGoalMutation, newBootId, newId } from '../src/records.js' import { SanshengStore } from '../src/store.js' async function tempStore() { const dir = await mkdtemp(join(tmpdir(), 'sansheng-')) const store = new SanshengStore(join(dir, 'state.json')) await store.load() return { store, dir, cleanup: () => rm(dir, { recursive: true, force: true }) } } const PROJECT = { id: 'prj-test0001', name: '测试项目', roomId: 'room-1', bots: { lead: 'bot-lead', shangshu: 'bot-shang', gongbu: 'bot-gong' }, maxReworks: 3, } function goalAt({ revision = 4, reworks = 0, status = 'active' } = {}) { return { id: 'goal-aaaa1111', revision, status, current: 0, objective: '交付示例', acceptance: '测试通过', constraints: [], stages: [{ id: 's1', title: '搭骨架', acceptance: '能跑', status: 'active', tasks: [{ id: 't1', botId: 'bot-gong', task: '写代码', status: 'doing', note: '' }], reworks, feedback: '', evidence: '', }], } } function fakeEnv({ goal = goalAt(), deliver } = {}) { const room = { id: 'room-1', name: '测试项目 · 三省六部', admin: 'bot-shang', members: ['bot-lead', 'bot-shang', 'bot-gong'], sessions: { 'bot-shang': 'sess-shang', 'bot-gong': 'sess-gong' }, goal, } const bots = { 'bot-lead': { id: 'bot-lead', name: '丞相' }, 'bot-shang': { id: 'bot-shang', name: '尚书' }, 'bot-gong': { id: 'bot-gong', name: '工部' }, } const dsbot = { selfOf: sessionId => ({ 'sess-shang': 'bot-shang', 'sess-gong': 'bot-gong', 'sess-lead': 'bot-lead' })[sessionId], roomOfSession: sessionId => (sessionId === 'sess-shang' ? 'room-1' : undefined), roomOf: () => room, botOf: id => bots[id], botByName: name => Object.values(bots).find(bot => bot.name === name), isMain: () => false, pickRoom: () => ({ error: 'no room' }), } const calls = [] const rt = { deliver: async payload => { calls.push(payload); if (deliver) return deliver(payload) }, } const ctx = { handlers: {}, on(event, handler) { this.handlers[event] = handler }, get() { return rt }, } return { room, dsbot, ctx, calls } } test('派发记录:prepared → in_flight → 回执,业务拒绝记为 rejected', async () => { const { store, cleanup } = await tempStore() try { await store.saveProject(PROJECT) const { dsbot, ctx } = fakeEnv() const bootId = newBootId() installObserver({ ctx, store, dsbot, bootId }) const exec = { name: 'group_goal', arguments: { action: 'pass', evidence: '测试输出' }, agent: { id: 'sess-shang' } } const result = await ctx.handlers['tools/execute'](exec, async () => { const last = store.peek().dispatches.at(-1) assert.equal(last.status, 'in_flight', '调用前先落意图并标记发送中') dsbot.roomOf().goal = goalAt({ revision: 5 }) return { content: [{ type: 'text', text: '已通过' }] } }) assert.equal(result.content[0].text, '已通过') const record = store.peek().dispatches.at(-1) assert.equal(record.status, 'confirmed') assert.equal(record.action, 'pass') assert.equal(record.projectId, PROJECT.id) assert.equal(record.actorRole, 'shangshu') await ctx.handlers['tools/execute']( { ...exec, arguments: { action: 'complete', summary: 'x', evidence: 'y' } }, async () => ({ isError: true, content: [{ type: 'text', text: 'Error: 还有阶段未通过' }] }), ) assert.equal(store.peek().dispatches.at(-1).status, 'rejected') } finally { await cleanup() } }) test('重启对账:停在 prepared 的派发标为待核实,核实后改状态且不重复', async () => { const { store, cleanup } = await tempStore() try { await store.saveProject(PROJECT) await store.beginDispatch({ id: 'dsp-0001', projectId: PROJECT.id, action: 'pass', goalId: 'goal-aaaa1111', goalRevision: 4 }) const marked = await store.reconcileDispatches('boot-2') assert.equal(marked, 1) assert.equal(store.unknownDispatches(PROJECT.id).length, 1) const confirmed = await store.resolveDispatch('dsp-0001', 'done', 'bot-shang') assert.equal(confirmed.changed, true) assert.equal(confirmed.record.status, 'confirmed') const again = await store.resolveDispatch('dsp-0001', 'not-done', 'bot-shang') assert.equal(again.changed, false, '已核实的记录不再改判') const { store: other, cleanup: cleanupOther } = await tempStore() try { await other.saveProject(PROJECT) await other.beginDispatch({ id: 'dsp-0002', projectId: PROJECT.id, action: 'rework' }) await other.reconcileDispatches('boot-3') await other.resolveDispatch('dsp-0002', 'not-done', 'bot-shang') assert.equal(other.peek().dispatches.at(-1).status, 'rejected') } finally { await cleanupOther() } } finally { await cleanup() } }) test('detectRework:认出被驳回的阶段与预算', () => { const before = goalAt({ revision: 4, reworks: 0 }) const after = goalAt({ revision: 5, reworks: 1 }) after.stages[0].feedback = '缺测试' const detected = detectRework({ before, after, reason: '' }) assert.equal(detected.stageNo, 1) assert.equal(detected.stageTitle, '搭骨架') assert.equal(detected.reason, '缺测试') assert.equal(detectRework({ before, after: goalAt({ revision: 4, reworks: 1 }) }), undefined, '版本没变不算返工') assert.equal(detectRework({ before, after: { ...after, id: 'goal-other' } }), undefined, '不是同一个目标') assert.equal(isGoalMutation('pass'), true) assert.equal(isGoalMutation('status'), false) assert.match(newId('dsp'), /^dsp-[0-9a-f]{8}$/) }) test('确认返工后自动把返工单交给工部', 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 exec = { name: 'group_goal', arguments: { action: 'rework', reason: '缺少边界测试' }, agent: { id: 'sess-shang' } } await ctx.handlers['tools/execute'](exec, async () => { dsbot.roomOf().goal = goalAt({ revision: 5, reworks: 1 }) return { content: [{ type: 'text', text: '已驳回' }] } }) assert.equal(calls.length, 1) assert.equal(calls[0].fromId, 'bot-shang') assert.equal(calls[0].toId, 'bot-gong') assert.equal(calls[0].sessionId, 'sess-gong') assert.equal(calls[0].role, 'request') assert.match(calls[0].text, /缺少边界测试/) assert.match(calls[0].text, /1\/3/) const reworks = store.reworksFor(PROJECT.id) assert.equal(reworks.length, 1) assert.equal(reworks[0].stageIndex, 1) assert.equal(reworks[0].budgetUsed, 1) // 同一版本重复观测不重复派单 await store.addRework({ ...reworks[0], id: 'rwk-dup' }) assert.equal(store.reworksFor(PROJECT.id).length, 1) } finally { await cleanup() } }) test('未绑定项目与关闭自动返工时不记账、不派单', async () => { const { store, cleanup } = await tempStore() try { const { dsbot, ctx, calls } = fakeEnv() installObserver({ ctx, store, dsbot, bootId: newBootId() }) await ctx.handlers['tools/execute']( { name: 'group_goal', arguments: { action: 'pass' }, agent: { id: 'sess-shang' } }, async () => ({ content: [] }), ) assert.equal(store.peek().dispatches.length, 0, '未绑定的群保持原生行为') await store.saveProject({ ...PROJECT, autoRework: false }) const env = fakeEnv({ goal: goalAt({ revision: 4, reworks: 0 }) }) installObserver({ ctx: env.ctx, store, dsbot: env.dsbot, bootId: newBootId() }) await env.ctx.handlers['tools/execute']( { name: 'group_goal', arguments: { action: 'rework', reason: '再改' }, agent: { id: 'sess-shang' } }, async () => { env.dsbot.roomOf().goal = goalAt({ revision: 5, reworks: 1 }) return { content: [] } }, ) assert.equal(env.calls.length, 0, '关闭自动返工不派单') assert.equal(store.reworksFor(PROJECT.id).length, 1, '返工仍要记账') assert.equal(calls.length, 0) } finally { await cleanup() } }) test('跨项目隔离:别的项目的 Bot 不能改本项目的目标', () => { const goal = goalAt() const members = [ { id: 'bot-lead', name: '丞相', role: 'lead' }, { id: 'bot-shang', name: '尚书', role: 'shangshu' }, { id: 'bot-gong', name: '工部', role: 'gongbu' }, ] const stranger = { kind: 'bot', botId: 'bot-x', botName: '外包', isMain: false, role: undefined } const verdict = evaluateGoalAction({ action: 'pass', actor: stranger, project: PROJECT, goal, reviews: [], members, args: {} }) assert.equal(verdict.allow, false) assert.equal(verdict.code, 'not-member') })