554 lines
25 KiB
JavaScript
554 lines
25 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 { apply } from '../index.js'
|
||
import { installGovernance } from '../src/governance.js'
|
||
import { resolveActor } from '../src/identity.js'
|
||
import { SanshengStore, SanshengStoreError } from '../src/store.js'
|
||
import { installTools } from '../src/tools.js'
|
||
|
||
function fakeCtx(services = {}) {
|
||
const tools = []
|
||
const provided = {}
|
||
return {
|
||
tools: {
|
||
register(def) { tools.push(def); return () => {} },
|
||
guard() { return () => {} },
|
||
},
|
||
on() { return () => {} },
|
||
effect(fn) { return typeof fn === 'function' ? fn() : undefined },
|
||
get(name, fallback) { return services[name] ?? fallback },
|
||
provide(name, value) { provided[name] = value },
|
||
toolsList: tools,
|
||
provided,
|
||
}
|
||
}
|
||
|
||
function fakeRuntime() {
|
||
const calls = { bots: [], rooms: [], deletedBots: [], deletedRooms: [], updated: [] }
|
||
const bots = new Map()
|
||
const rooms = new Map()
|
||
let counter = 0
|
||
const rt = {
|
||
async load() {},
|
||
findBot(ref) {
|
||
if (bots.has(ref)) return bots.get(ref)
|
||
return [...bots.values()].find(bot => bot.name === ref)
|
||
},
|
||
async resolveModel(ref) {
|
||
if (ref === 'bad') throw new Error('模型不存在')
|
||
return ref
|
||
},
|
||
async createBot(options) {
|
||
if ([...bots.values()].some(bot => bot.name === options.name)) throw new Error(`A Bot named ${options.name} already exists`)
|
||
counter += 1
|
||
const bot = { id: `bot-${counter}`, name: options.name, model: options.model, sessionId: `sess-${counter}` }
|
||
bots.set(bot.id, bot)
|
||
calls.bots.push({ ...options, id: bot.id })
|
||
return bot
|
||
},
|
||
botOf(id) { return bots.get(id) },
|
||
async updateBot(id, patch) {
|
||
const bot = bots.get(id)
|
||
if (!bot) throw new Error('Unknown Bot')
|
||
Object.assign(bot, patch)
|
||
calls.updated.push({ id, patch })
|
||
return bot
|
||
},
|
||
async deleteBot(id) {
|
||
calls.deletedBots.push(id)
|
||
bots.delete(id)
|
||
},
|
||
async createRoom(options) {
|
||
const room = { id: `room-${rooms.size + 1}`, name: options.name, members: options.members, admin: options.admin, sessions: {}, goal: undefined }
|
||
rooms.set(room.id, room)
|
||
calls.rooms.push(options)
|
||
return room
|
||
},
|
||
async deleteRoom(id) {
|
||
calls.deletedRooms.push(id)
|
||
rooms.delete(id)
|
||
},
|
||
goalControl: async () => ({}),
|
||
}
|
||
return { rt, calls, bots, rooms }
|
||
}
|
||
|
||
async function setup() {
|
||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-isolation-'))
|
||
const { rt, calls, bots, rooms } = fakeRuntime()
|
||
const ctx = fakeCtx({ 'dsbot-runtime': rt })
|
||
const statePath = join(dir, 'state.json')
|
||
const dsbotStatePath = join(dir, 'bot-state.json')
|
||
await apply(ctx, { statePath, dsbotStatePath })
|
||
const tool = name => ctx.toolsList.find(def => def.name === name)
|
||
const store = new SanshengStore(statePath)
|
||
await store.load()
|
||
const env = {
|
||
dir, rt, calls, bots, rooms, ctx, tool, store, statePath, dsbotStatePath,
|
||
reload: async () => {
|
||
const next = new SanshengStore(statePath)
|
||
await next.load()
|
||
env.store = next
|
||
return next
|
||
},
|
||
cleanup: () => rm(dir, { recursive: true, force: true }),
|
||
}
|
||
return env
|
||
}
|
||
|
||
const userExec = { agent: { id: 'user-session' } }
|
||
|
||
test('I01:连续创建 A/B 默认参数均成功,Bot 名唯一且角色独立', async () => {
|
||
const env = await setup()
|
||
try {
|
||
const a = await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
const b = await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||
await env.reload()
|
||
assert.match(a, /已创建项目「项目A」/)
|
||
assert.match(b, /已创建项目「项目B」/)
|
||
|
||
const namesA = env.calls.bots.slice(0, 3).map(bot => bot.name)
|
||
const namesB = env.calls.bots.slice(3, 6).map(bot => bot.name)
|
||
assert.equal(new Set([...namesA, ...namesB]).size, 6, '六个 Bot 名必须全局唯一')
|
||
assert.notDeepEqual(namesA, namesB)
|
||
|
||
const projects = Object.values(env.store.peek().projects)
|
||
assert.equal(projects.length, 2)
|
||
const botIds = projects.flatMap(project => Object.values(project.bots))
|
||
assert.equal(new Set(botIds).size, 6, '两个项目不共享角色 Bot')
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('I02:把 A 的尚书绑到 B 所在的群明确拒绝', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const projectA = Object.values(env.store.peek().projects)[0]
|
||
// 手工造一个群:成员是 A 的三个 Bot,管理员是 A 的尚书
|
||
const room = await env.rt.createRoom({
|
||
name: '另一个群', members: Object.values(projectA.bots), admin: projectA.bots.shangshu,
|
||
})
|
||
const botState = {
|
||
version: 1,
|
||
mainBotIds: [],
|
||
bots: Object.fromEntries(Object.entries(projectA.bots).map(([role, id]) => [id, { id, name: env.bots.get(id)?.name ?? role, role }])),
|
||
rooms: { [room.id]: { id: room.id, name: room.name, members: Object.values(projectA.bots), admin: projectA.bots.shangshu, sessions: {} } },
|
||
}
|
||
const { writeFile } = await import('node:fs/promises')
|
||
await writeFile(env.dsbotStatePath, JSON.stringify(botState), 'utf8')
|
||
const result = await env.tool('sansheng_bind').execute({
|
||
project: '项目B', room: room.id,
|
||
lead: projectA.bots.lead, shangshu: projectA.bots.shangshu, gongbu: projectA.bots.gongbu,
|
||
}, userExec)
|
||
assert.match(result, /已属于项目|只能属于一个项目/)
|
||
assert.equal(Object.values(env.store.peek().projects).length, 1, '不能产生半绑定')
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('I03:显式 project 与 Bot 所属项目冲突时拒绝', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||
await env.reload()
|
||
const [a, b] = Object.values(env.store.peek().projects)
|
||
// 让 A 的尚书会话记录审查,但显式要求写到 B
|
||
const room = { goal: { id: 'goal-1', revision: 1, status: 'active', stages: [] } }
|
||
const dsbot = {
|
||
botOf: id => ({ name: id }),
|
||
roomOf: id => (id === a.roomId ? room : undefined),
|
||
roomOfSession: () => a.roomId,
|
||
selfOf: () => a.bots.shangshu,
|
||
isMain: () => false,
|
||
}
|
||
const fakeStore = {
|
||
...env.store,
|
||
projectsByBot: id => (id === a.bots.shangshu ? [a] : []),
|
||
projectByBot: id => (id === a.bots.shangshu ? a : undefined),
|
||
projectByRoom: id => (id === a.roomId ? a : id === b.roomId ? b : undefined),
|
||
peek: () => ({ reviews: [], artifacts: {}, projects: { [a.id]: a, [b.id]: b }, reworks: [] }),
|
||
resolveProject: ref => (ref === b.name ? b : ref === a.name ? a : undefined),
|
||
}
|
||
const actor = resolveActor({ dsbot, store: fakeStore, sessionId: 'sess-shang', isBotSession: () => true })
|
||
assert.equal(actor.project.id, a.id)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('I03b:A 的尚书显式指定项目 B 记录审查时拒绝,不落 B 的记录', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||
await env.reload()
|
||
const [a, b] = Object.values(env.store.peek().projects)
|
||
const goal = { id: 'goal-a', revision: 3, status: 'active', current: 0, objective: 'A', acceptance: 'A', constraints: [], stages: [{ id: 's1', title: '一', acceptance: 'x', status: 'active', tasks: [] }] }
|
||
// 让插件内的 DsBotState 看到 A 的群与尚书会话
|
||
const { writeFile } = await import('node:fs/promises')
|
||
await writeFile(env.dsbotStatePath, JSON.stringify({
|
||
version: 1,
|
||
mainBotIds: [],
|
||
bots: Object.fromEntries(Object.entries(a.bots).map(([role, id]) => [id, { id, name: env.bots.get(id)?.name ?? role, role, sessionId: role === 'shangshu' ? 'sess-a-shang' : `sess-${role}` }])),
|
||
rooms: { [a.roomId]: { id: a.roomId, name: 'A 群', members: Object.values(a.bots), admin: a.bots.shangshu, sessions: {}, goal } },
|
||
}), 'utf8')
|
||
const result = await env.tool('sansheng_review').execute(
|
||
{ action: 'stage_pass', project: b.id, stage: 1, evidence: '测试' },
|
||
{ agent: { id: 'sess-a-shang' } },
|
||
)
|
||
assert.match(result, /项目冲突|不能跨项目/)
|
||
assert.equal(env.store.peek().reviews.length, 0, '不能把 A 的审查写进 B')
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Store 层拒绝重复 Bot/重复群绑定', async () => {
|
||
const env = await setup()
|
||
try {
|
||
const project = {
|
||
id: 'prj-1', name: 'A', roomId: 'room-1',
|
||
bots: { lead: 'b1', shangshu: 'b2', gongbu: 'b3' }, maxReworks: 3,
|
||
}
|
||
await env.store.saveProject(project)
|
||
await assert.rejects(
|
||
() => env.store.saveProject({ ...project, id: 'prj-2', name: 'B' }),
|
||
error => error instanceof SanshengStoreError && error.code === 'room-taken',
|
||
)
|
||
await assert.rejects(
|
||
() => env.store.saveProject({ ...project, id: 'prj-3', name: 'C', roomId: 'room-3' }),
|
||
error => error instanceof SanshengStoreError && error.code === 'bot-taken',
|
||
)
|
||
await assert.rejects(
|
||
() => env.store.saveProject({ ...project, id: 'prj-4', name: 'D', roomId: 'room-4', bots: { lead: 'x', shangshu: 'x', gongbu: 'y' } }),
|
||
error => error instanceof SanshengStoreError && error.code === 'roles-duplicated',
|
||
)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('I04:修改 A 模型配置只更新 A 的 Bot 与绑定', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||
await env.reload()
|
||
const [a, b] = Object.values(env.store.peek().projects)
|
||
const result = await env.tool('sansheng_config').execute({
|
||
project: a.id, models: { lead: 'magpie/new-lead' },
|
||
}, userExec)
|
||
assert.match(result, /已更新项目/)
|
||
const updatedIds = env.calls.updated.map(item => item.id)
|
||
assert.deepEqual(updatedIds, [a.bots.lead], '只更新 A 的丞相 Bot')
|
||
const reloaded = new SanshengStore(env.statePath)
|
||
await reloaded.load()
|
||
assert.equal(reloaded.projectById(a.id).models.lead, 'magpie/new-lead')
|
||
assert.equal(reloaded.projectById(b.id).models.lead, undefined)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('I05/I06:治理服务拒绝跨项目投递与 team 记忆', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||
await env.reload()
|
||
const [a, b] = Object.values(env.store.peek().projects)
|
||
const gov = installGovernance({ ctx: env.ctx, store: env.store })
|
||
assert.equal(gov.checkDelivery({ fromId: a.bots.shangshu, toId: b.bots.gongbu }).allow, false)
|
||
assert.equal(gov.checkDelivery({ fromId: a.bots.shangshu, toId: a.bots.gongbu }).allow, true)
|
||
assert.equal(gov.checkDelivery({ fromId: a.bots.shangshu, toId: 'bot-outsider' }).allow, false)
|
||
assert.equal(gov.checkDelivery({ fromId: b.bots.lead, toId: a.bots.gongbu, roomId: a.roomId }).allow, false)
|
||
|
||
assert.equal(gov.checkMemoryScope({ botId: a.bots.lead, scope: 'team' }).allow, false)
|
||
assert.equal(gov.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: a.roomId }).allow, true)
|
||
assert.equal(gov.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: b.roomId }).allow, false)
|
||
assert.equal(gov.checkMemoryScope({ botId: 'bot-outsider', scope: 'team' }).allow, true)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('写租约:同项目第二个写任务被拒绝,释放后可获取', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
const first = await env.store.acquireLease(project.id, { holder: 'bot-gongbu', taskId: 't1' })
|
||
assert.equal(first.ok, true)
|
||
const second = await env.store.acquireLease(project.id, { holder: 'bot-other', taskId: 't2' })
|
||
assert.equal(second.ok, false)
|
||
assert.match(second.reason, /正在被/)
|
||
await env.store.releaseLease(project.id, 'bot-gongbu')
|
||
const third = await env.store.acquireLease(project.id, { holder: 'bot-other', taskId: 't3' })
|
||
assert.equal(third.ok, true)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q11:模型配置先全部校验,任一无效时零修改', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
const before = env.calls.updated.length
|
||
const result = await env.tool('sansheng_config').execute({
|
||
project: project.id,
|
||
models: { lead: 'provider/ok', shangshu: 'bad' },
|
||
}, userExec)
|
||
assert.match(result, /不可用/)
|
||
assert.equal(env.calls.updated.length, before, '无效模型不应产生任何 updateBot')
|
||
assert.equal(env.store.projectById(project.id).models.lead, undefined)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q11b:中途 updateBot 失败时回滚已经修改的模型', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
const original = env.rt.updateBot
|
||
env.rt.updateBot = async (id, patch) => {
|
||
if (id === project.bots.shangshu && patch.model === 'provider/m2') throw new Error('模拟第二模型更新失败')
|
||
return original.call(env.rt, id, patch)
|
||
}
|
||
const result = await env.tool('sansheng_config').execute({
|
||
project: project.id,
|
||
models: { lead: 'provider/m1', shangshu: 'provider/m2' },
|
||
}, userExec)
|
||
assert.match(result, /已回滚/)
|
||
const updates = env.calls.updated.slice(-3)
|
||
assert.equal(updates[0].id, project.bots.lead)
|
||
assert.equal(updates[0].patch.model, 'provider/m1')
|
||
assert.equal(updates[1].id, project.bots.shangshu, '当前失败角色也要进入补偿')
|
||
assert.equal(updates[1].patch.model, undefined)
|
||
assert.equal(updates[2].id, project.bots.lead)
|
||
assert.equal(updates[2].patch.model, undefined, '回滚到原值')
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q02:状态损坏时 registry 中的受治理 Bot/群拒绝投递与记忆访问,恢复后放行', async () => {
|
||
const { readFile, writeFile } = await import('node:fs/promises')
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
const good = await readFile(env.statePath, 'utf8')
|
||
await writeFile(env.statePath, '{broken', 'utf8')
|
||
const broken = new SanshengStore(env.statePath)
|
||
await assert.rejects(() => broken.load())
|
||
const governance = installGovernance({ ctx: fakeCtx(), store: broken })
|
||
assert.equal(governance.checkDelivery({ fromId: project.bots.lead, toId: project.bots.shangshu, roomId: project.roomId }).allow, false)
|
||
assert.equal(governance.checkMemoryScope({ botId: project.bots.lead, scope: 'team' }).allow, false)
|
||
assert.equal(governance.checkMemoryScope({ botId: project.bots.lead, scope: 'group', roomId: project.roomId }).allow, false)
|
||
assert.equal(governance.checkMemoryScope({ botId: project.bots.lead, scope: 'bot', targetBotId: project.bots.gongbu }).allow, false)
|
||
|
||
await writeFile(env.statePath, good, 'utf8')
|
||
const restored = new SanshengStore(env.statePath)
|
||
await restored.load()
|
||
const healthy = installGovernance({ ctx: fakeCtx(), store: restored })
|
||
assert.equal(healthy.checkDelivery({ fromId: project.bots.lead, toId: project.bots.shangshu, roomId: project.roomId }).allow, true)
|
||
assert.equal(healthy.checkMemoryScope({ botId: project.bots.lead, scope: 'team' }).allow, false)
|
||
assert.equal(healthy.checkMemoryScope({ botId: project.bots.lead, scope: 'group', roomId: project.roomId }).allow, true)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q03:unknown 身份不能调用用户专属工具(provision/bind/config/control)', async () => {
|
||
const { mkdtemp } = await import('node:fs/promises')
|
||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-q03-'))
|
||
const store = new SanshengStore(join(dir, 'state.json'))
|
||
await store.load()
|
||
const defs = []
|
||
const ctx = {
|
||
tools: { register(def) { defs.push(def); return () => {} } },
|
||
get() { return undefined },
|
||
}
|
||
const dsbot = {
|
||
selfOf: () => undefined,
|
||
botOf: () => undefined,
|
||
isMain: () => false,
|
||
snapshot: () => ({ rooms: {}, bots: {} }),
|
||
roomOf: () => undefined,
|
||
}
|
||
installTools({ ctx, store, dsbot, isBotSession: id => id === 'bot-session' })
|
||
const exec = { agent: { id: 'bot-session' } }
|
||
const run = (name, args) => defs.find(def => def.name === name).execute(args, exec)
|
||
assert.match(await run('sansheng_bind', { room: 'x' }), /只有用户/)
|
||
assert.match(await run('sansheng_provision', { project: 'x' }), /只有用户/)
|
||
assert.match(await run('sansheng_config', { project: 'x' }), /只有用户|身份不明/)
|
||
assert.match(await run('sansheng_control', { project: 'x', action: 'pause' }), /只能由用户/)
|
||
assert.match(await run('sansheng_reconcile', { id: 'dsp-x', verdict: 'done' }), /找不到对应身份|当前 DS Bot 状态/)
|
||
assert.match(await run('sansheng_lease', { project: 'x', action: 'acquire' }), /找不到对应身份|当前 DS Bot 状态/)
|
||
await rm(dir, { recursive: true, force: true })
|
||
})
|
||
|
||
test('Q08:提交成果使用写租约并在成功/失败后释放', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
const submitted = await env.tool('sansheng_submit').execute({ project: project.id, task: 't1' }, userExec)
|
||
assert.match(submitted, /已提交成果快照/)
|
||
assert.equal(env.store.leaseOf(project.id), undefined, '提交完成后必须释放项目租约')
|
||
assert.equal(env.store.rootLeaseOf('C:/work/a'), undefined, '提交完成后必须释放工作根租约')
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q04:记忆作用域过滤覆盖群与目标 Bot,Main 身份不能绕过项目归属', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||
await env.reload()
|
||
const projects = Object.values(env.store.peek().projects)
|
||
const a = projects.find(project => project.name === '项目A')
|
||
const b = projects.find(project => project.name === '项目B')
|
||
const governance = installGovernance({ ctx: fakeCtx(), store: env.store })
|
||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: b.roomId }).allow, false)
|
||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'bot', targetBotId: b.bots.lead }).allow, false)
|
||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'bot', targetBotId: a.bots.lead }).allow, true)
|
||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: a.roomId }).allow, true)
|
||
// 即使 actor 是 Main,也先按项目归属拒绝(记忆补丁在 Main 豁免之前调用治理)。
|
||
env.rt.isMain = () => true
|
||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'bot', targetBotId: b.bots.lead }).allow, false)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q02b:主状态与 registry 双故障时治理/门禁不可判定为 unbound', async () => {
|
||
const { writeFile } = await import('node:fs/promises')
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
await writeFile(env.statePath, '{broken', 'utf8')
|
||
await writeFile(env.statePath.replace(/state\.json$/, 'registry.json'), '{broken', 'utf8')
|
||
const broken = new SanshengStore(env.statePath)
|
||
await assert.rejects(() => broken.load())
|
||
assert.equal(broken.health().registryStatus, 'broken')
|
||
const governance = installGovernance({ ctx: fakeCtx(), store: broken })
|
||
// 连从未见过的 Bot 也不能被静默当作 unbound。
|
||
assert.equal(governance.checkDelivery({ fromId: 'unknown-a', toId: 'unknown-b' }).allow, false)
|
||
assert.equal(governance.checkMemoryScope({ botId: 'unknown-a', scope: 'team' }).allow, false)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q13:服务端配置拒绝 needsKey/不可用模型,即使前端绕过下拉', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
env.rt.availabilityOf = async ref => (ref === 'provider/keyless'
|
||
? { available: false, needsKey: true, reason: '提供方尚未配置凭据' }
|
||
: { available: true })
|
||
const before = env.calls.updated.length
|
||
const result = await env.tool('sansheng_config').execute({ project: project.id, models: { lead: 'provider/keyless' } }, userExec)
|
||
assert.match(result, /不可用|凭据/)
|
||
assert.equal(env.calls.updated.length, before)
|
||
assert.equal(env.store.projectById(project.id).models.lead, undefined)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q11c:同一项目的并发配置串行,不互相覆盖', async () => {
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
const original = env.rt.updateBot
|
||
env.rt.updateBot = async (...args) => {
|
||
await new Promise(resolve => setTimeout(resolve, 15))
|
||
return original.apply(env.rt, args)
|
||
}
|
||
const [one, two] = await Promise.all([
|
||
env.tool('sansheng_config').execute({ project: project.id, models: { lead: 'provider/m1' } }, userExec),
|
||
env.tool('sansheng_config').execute({ project: project.id, models: { shangshu: 'provider/m2' } }, userExec),
|
||
])
|
||
assert.match(one, /已更新/)
|
||
assert.match(two, /已更新/)
|
||
const fresh = await env.reload()
|
||
const saved = fresh.projectById(project.id)
|
||
assert.equal(saved.models.lead, 'provider/m1')
|
||
assert.equal(saved.models.shangshu, 'provider/m2')
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q01c:真实 apply 启动链在主状态缺失时不覆盖 registry,provision 拒绝', async () => {
|
||
const { readFile, unlink } = await import('node:fs/promises')
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
const registryBefore = await readFile(env.statePath.replace(/state\.json$/, 'registry.json'), 'utf8')
|
||
await unlink(env.statePath)
|
||
const ctx2 = fakeCtx({ 'dsbot-runtime': env.rt })
|
||
await apply(ctx2, { statePath: env.statePath, dsbotStatePath: env.dsbotStatePath })
|
||
const provision = ctx2.toolsList.find(def => def.name === 'sansheng_provision')
|
||
const result = await provision.execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||
assert.match(String(result), /恢复|state-protected|缺失/)
|
||
const registryAfter = await readFile(env.statePath.replace(/state\.json$/, 'registry.json'), 'utf8')
|
||
assert.equal(registryAfter, registryBefore)
|
||
const missing = new SanshengStore(env.statePath)
|
||
await missing.load()
|
||
assert.equal(missing.health().status, 'missing')
|
||
assert.equal(missing.health().writable, false)
|
||
assert.equal(missing.registryProjectForBot(project.bots.lead), project.id)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|
||
|
||
test('Q11d:补偿失败写 config-recovery.jsonl,不再只返回一次文本', async () => {
|
||
const { readFile } = await import('node:fs/promises')
|
||
const env = await setup()
|
||
try {
|
||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||
await env.reload()
|
||
const project = Object.values(env.store.peek().projects)[0]
|
||
env.rt.updateBot = async (id, patch) => {
|
||
if (id === project.bots.shangshu) throw new Error('尚书模型写入永久失败')
|
||
return { id, ...patch }
|
||
}
|
||
const result = await env.tool('sansheng_config').execute({ project: project.id, models: { lead: 'provider/m1', shangshu: 'provider/m2' } }, userExec)
|
||
assert.match(result, /回滚失败|config-recovery/)
|
||
const sidecar = await readFile(join(env.dir, 'config-recovery.jsonl'), 'utf8')
|
||
assert.match(sidecar, /config-recovery|项目|shangshu|provider\/m2/)
|
||
} finally {
|
||
await env.cleanup()
|
||
}
|
||
})
|