feat(sansheng): P1 三角色供给、绑定、状态与目标门禁
This commit is contained in:
parent
689e198e1f
commit
09f08b4520
|
|
@ -0,0 +1,65 @@
|
|||
# P1 · 三角色独立工作
|
||||
|
||||
状态:**代码与单测完成,本机插件已安装;DS-Bot 运行时待重启后验证**。
|
||||
|
||||
## 交付物
|
||||
|
||||
| 文件 | 作用 |
|
||||
| --- | --- |
|
||||
| `sansheng/package.json`、`sansheng/cordis.patch.yml` | 宿主插件清单,insert `sansheng` |
|
||||
| `sansheng/index.js` | 加载自有状态、只读 DS-Bot 状态,安装门禁与工具 |
|
||||
| `sansheng/src/store.js` | `$DSH_HOME/sansheng/state.json` 原子写、项目绑定、审查记录 |
|
||||
| `sansheng/src/dsbot-state.js` | 只读 `$DSH_HOME/bot/state.json`,会话 → Bot/群反查 |
|
||||
| `sansheng/src/identity.js` | 由执行会话解析真实调用者(用户 / Bot / 角色 / 项目) |
|
||||
| `sansheng/src/gate.js` | 纯函数角色与证据校验(可单测) |
|
||||
| `sansheng/src/gates.js` | 根 `ctx.tools.guard`,拦截 `group_goal` 变更 |
|
||||
| `sansheng/src/digest.js` | 目标/阶段指纹,证据随成果版本失效 |
|
||||
| `sansheng/src/tools.js` | `sansheng_provision` / `sansheng_bind` / `sansheng_status` / `sansheng_review` |
|
||||
| `sansheng/test/*.test.js` | 22 个纯逻辑测试 |
|
||||
|
||||
## 角色与门禁(P1 已生效)
|
||||
|
||||
| 动作 | 丞相 lead | 尚书 shangshu | 工部 gongbu |
|
||||
| --- | --- | --- | --- |
|
||||
| `group_goal` draft/start/revise/pause/resume/stop | 拒 | 放行 | 拒 |
|
||||
| `group_goal` task(派工) | 拒 | 放行,目标只能是工部 | 拒 |
|
||||
| `group_goal` pass | 拒 | 放行,需当前阶段 + 同 revision 的 `stage_pass` 记录 | 拒 |
|
||||
| `group_goal` rework | 拒 | 放行,需同 revision 的 `stage_reject` 记录,且累计返工 < 预算 | 拒 |
|
||||
| `group_goal` complete | 拒 | 放行,需全部阶段 passed + 同 revision 的 `goal_pass`(reviewerRole=lead) | 拒 |
|
||||
| `sansheng_review` stage_* | 拒 | 放行 | 拒 |
|
||||
| `sansheng_review` goal_* | 放行 | 拒 | 拒 |
|
||||
|
||||
- 只有绑定过的项目群受门禁约束;未绑定群保持 DS-Bot 原生行为。
|
||||
- Main Bot(`mainBotIds`)对已绑定项目一律拒绝变更。
|
||||
- 角色按**绑定项目**重新计算,跨项目复用的 Bot 不会串权。
|
||||
- 门禁内部异常 fail-closed:报“目标校验失败……本次修改未执行”。
|
||||
|
||||
## 安装与重启
|
||||
|
||||
```bash
|
||||
# 已执行(profile: desktop)
|
||||
dsh plugin --profile desktop add C:/Users/qyh15/三省六部/sansheng
|
||||
dsh plugin --profile desktop add C:/Users/qyh15/三省六部/vendor/ds-bot
|
||||
```
|
||||
|
||||
- `sansheng` 已被运行中的宿主热加载,四个工具可直接调用。
|
||||
- `vendor/ds-bot` 已写入 profile 依赖与 bundles;`dsbot-runtime` 服务需**重启 DSH** 后才可用(未重启时 `sansheng_provision` 会明确报“没有找到 DS-Bot 运行时”)。
|
||||
- 重启影响:DS-Bot 页面出现;`ui-settings-general` 被其补丁禁用;`web` 搜索提供方被覆盖为 auto。回退见 `docs/p0/README.md`。
|
||||
|
||||
## 重启后的验收步骤
|
||||
|
||||
1. `sansheng_provision({ project: "示例项目" })` → 三个 Bot + 一个群(尚书为管理员)。
|
||||
2. `sansheng_status()` → 三角色、群、模型、预算齐全。
|
||||
3. 在群里以尚书身份试 `group_goal` 的 `start`;用工部/丞相身份试改目标,应被拒。
|
||||
4. 尚书 `sansheng_review(stage_pass)` 后 `group_goal pass` 应通过;未审查时 pass 应被拒且提示缺证据。
|
||||
5. 返工:`sansheng_review(stage_reject)` → `group_goal rework` 通过;第 4 次累计返工应被预算拒绝。
|
||||
6. 丞相 `sansheng_review(goal_pass)` 后 `group_goal complete` 通过;无丞相记录时应被拒。
|
||||
7. 两个项目各建一套三角色,确认模型与会话互不影响。
|
||||
|
||||
## 单测
|
||||
|
||||
```bash
|
||||
cd sansheng && node --test --test-isolation=none test/*.test.js
|
||||
```
|
||||
|
||||
当前 22/22 通过。
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
# 三省六部伴侣插件:挂到 DSL(DeepSeek Harness)宿主,随 ds-bot 一起提供三角色治理。
|
||||
- insert:
|
||||
- id: sansheng
|
||||
name: 'dsh-sansheng-sansheng'
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import { DsBotState } from './src/dsbot-state.js'
|
||||
import { installGates } from './src/gates.js'
|
||||
import { dsbotStatePath, sanshengStatePath } from './src/paths.js'
|
||||
import { SanshengStore } from './src/store.js'
|
||||
import { installTools } from './src/tools.js'
|
||||
|
||||
export const name = 'sansheng'
|
||||
export const inject = ['tools']
|
||||
|
||||
/**
|
||||
* 三省六部伴侣插件。原生 group_goal 是阶段进度唯一权威;
|
||||
* 这里只补 DS Bot 没有的东西:项目三角色绑定、审查记录、目标门禁。
|
||||
*/
|
||||
export async function apply(ctx, config = {}) {
|
||||
const home = typeof config.home === 'string' && config.home.trim() !== '' ? config.home : undefined
|
||||
const store = new SanshengStore(
|
||||
typeof config.statePath === 'string' && config.statePath !== '' ? config.statePath : sanshengStatePath(home),
|
||||
)
|
||||
const dsbot = new DsBotState(
|
||||
typeof config.dsbotStatePath === 'string' && config.dsbotStatePath !== '' ? config.dsbotStatePath : dsbotStatePath(home),
|
||||
)
|
||||
try {
|
||||
await store.load()
|
||||
} catch (error) {
|
||||
console.warn(`sansheng: 无法读取 ${store.file}:${error?.message ?? error}`)
|
||||
}
|
||||
installGates({ ctx, store, dsbot })
|
||||
installTools({ ctx, store, dsbot })
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"name": "dsh-sansheng-sansheng",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "三省六部:在 DS Bot 团队上提供丞相/尚书/工部三角色、目标门禁与审查记录。",
|
||||
"type": "module",
|
||||
"main": "./index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dsh": {
|
||||
"manifestVersion": 1,
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test --test-isolation=none test/*.test.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import { createHash } from 'node:crypto'
|
||||
|
||||
/** 稳定的 JSON:对象键排序、丢弃 undefined,保证同一份目标算出同一个摘要。 */
|
||||
export function canonical(value) {
|
||||
return JSON.stringify(stable(value))
|
||||
}
|
||||
|
||||
function stable(value) {
|
||||
if (Array.isArray(value)) return value.map(stable)
|
||||
if (value !== null && typeof value === 'object') {
|
||||
const out = {}
|
||||
for (const key of Object.keys(value).sort()) {
|
||||
if (value[key] !== undefined) out[key] = stable(value[key])
|
||||
}
|
||||
return out
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
export function sha256(text) {
|
||||
return createHash('sha256').update(String(text), 'utf8').digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个阶段的“成果版本”:阶段标题、验收标准、每个工单的目标/状态/备注。
|
||||
* 任务状态或备注一变,摘要就变,之前记录的审查证据即视为过期。
|
||||
*/
|
||||
export function stageDigest(goal, stageIndex) {
|
||||
const index = Number(stageIndex)
|
||||
const stage = goal?.stages?.[index - 1]
|
||||
if (!stage) return undefined
|
||||
return sha256(canonical({
|
||||
goalId: goal.id ?? '',
|
||||
stageIndex: index,
|
||||
stageId: stage.id ?? '',
|
||||
title: stage.title ?? '',
|
||||
acceptance: stage.acceptance ?? '',
|
||||
status: stage.status ?? '',
|
||||
tasks: (stage.tasks ?? []).map(task => ({
|
||||
id: task.id ?? '',
|
||||
botId: task.botId ?? '',
|
||||
task: task.task ?? '',
|
||||
status: task.status ?? '',
|
||||
note: task.note ?? '',
|
||||
})),
|
||||
}))
|
||||
}
|
||||
|
||||
/** 整份目标(目标陈述、验收、约束、各阶段摘要),用于丞相的目标验收。 */
|
||||
export function goalDigest(goal) {
|
||||
if (!goal) return undefined
|
||||
const stages = goal.stages ?? []
|
||||
return sha256(canonical({
|
||||
goalId: goal.id ?? '',
|
||||
objective: goal.objective ?? '',
|
||||
acceptance: goal.acceptance ?? '',
|
||||
constraints: goal.constraints ?? [],
|
||||
stages: stages.map((stage, i) => ({
|
||||
index: i + 1,
|
||||
stageId: stage.id ?? '',
|
||||
digest: stageDigest(goal, i + 1),
|
||||
status: stage.status ?? '',
|
||||
})),
|
||||
}))
|
||||
}
|
||||
|
|
@ -0,0 +1,158 @@
|
|||
import { readFileSync, statSync } from 'node:fs'
|
||||
|
||||
function emptyState() {
|
||||
return { version: 1, mainBotIds: [], bots: {}, rooms: {} }
|
||||
}
|
||||
|
||||
function buildIndex(state) {
|
||||
const chats = new Map()
|
||||
const pastChats = new Map()
|
||||
for (const bot of Object.values(state.bots ?? {})) {
|
||||
chats.set(bot.sessionId ?? bot.id, bot.id)
|
||||
for (const segment of bot.segments ?? []) {
|
||||
if (segment?.sessionId) pastChats.set(segment.sessionId, bot.id)
|
||||
}
|
||||
}
|
||||
const groupSessions = new Map()
|
||||
const pastGroupSessions = new Map()
|
||||
const roomSessions = new Map()
|
||||
for (const room of Object.values(state.rooms ?? {})) {
|
||||
roomSessions.set(room.sessionId ?? room.id, room.id)
|
||||
for (const [botId, sessionId] of Object.entries(room.sessions ?? {})) {
|
||||
if (sessionId) groupSessions.set(sessionId, { botId, roomId: room.id })
|
||||
}
|
||||
for (const [botId, segments] of Object.entries(room.segments ?? {})) {
|
||||
for (const segment of segments ?? []) {
|
||||
if (segment?.sessionId) pastGroupSessions.set(segment.sessionId, { botId, roomId: room.id })
|
||||
}
|
||||
}
|
||||
}
|
||||
return { chats, pastChats, groupSessions, pastGroupSessions, roomSessions }
|
||||
}
|
||||
|
||||
/**
|
||||
* DS Bot 状态文件($DSH_HOME/bot/state.json)的只读视图。
|
||||
* 我们绝不写这个文件:DS Bot 用独占锁与原子替换维护它,外部写入会被判为丢失。
|
||||
* 读取按 mtime+size 缓存,guard 需要同步拿到最新映射。
|
||||
*/
|
||||
export class DsBotState {
|
||||
#file
|
||||
#stamp = '\u0000'
|
||||
#state = null
|
||||
#index = null
|
||||
|
||||
constructor(file) {
|
||||
this.#file = file
|
||||
}
|
||||
|
||||
get file() {
|
||||
return this.#file
|
||||
}
|
||||
|
||||
#refresh() {
|
||||
let stamp = 'missing'
|
||||
try {
|
||||
const stat = statSync(this.#file)
|
||||
stamp = `${stat.mtimeMs}:${stat.size}`
|
||||
} catch {
|
||||
stamp = 'missing'
|
||||
}
|
||||
if (stamp === this.#stamp && this.#state !== null) return
|
||||
this.#stamp = stamp
|
||||
if (stamp === 'missing') {
|
||||
this.#state = emptyState()
|
||||
this.#index = buildIndex(this.#state)
|
||||
return
|
||||
}
|
||||
try {
|
||||
this.#state = JSON.parse(readFileSync(this.#file, 'utf8'))
|
||||
this.#index = buildIndex(this.#state)
|
||||
} catch (error) {
|
||||
// 读到半截/损坏时保留上一份可用快照,绝不因此放开校验。
|
||||
if (this.#state === null) {
|
||||
this.#state = emptyState()
|
||||
this.#index = buildIndex(this.#state)
|
||||
}
|
||||
this.#stamp = `${stamp}:broken`
|
||||
}
|
||||
}
|
||||
|
||||
snapshot() {
|
||||
this.#refresh()
|
||||
return this.#state
|
||||
}
|
||||
|
||||
freshness() {
|
||||
this.#refresh()
|
||||
return { path: this.#file, stamp: this.#stamp }
|
||||
}
|
||||
|
||||
botOf(botId) {
|
||||
if (!botId) return undefined
|
||||
this.#refresh()
|
||||
return this.#state.bots?.[botId]
|
||||
}
|
||||
|
||||
botByName(name) {
|
||||
const key = String(name ?? '').trim()
|
||||
if (key === '') return undefined
|
||||
this.#refresh()
|
||||
const bots = Object.values(this.#state.bots ?? {})
|
||||
return bots.find(bot => bot.name === key)
|
||||
?? bots.find(bot => bot.name?.toLocaleLowerCase() === key.toLocaleLowerCase())
|
||||
}
|
||||
|
||||
/** 会话 id → Bot id;群会话、私聊当前段与历史段都能反查。 */
|
||||
selfOf(sessionId) {
|
||||
if (!sessionId) return undefined
|
||||
this.#refresh()
|
||||
return this.#index.chats.get(sessionId)
|
||||
?? this.#index.groupSessions.get(sessionId)?.botId
|
||||
?? this.#index.pastChats.get(sessionId)
|
||||
?? this.#index.pastGroupSessions.get(sessionId)?.botId
|
||||
}
|
||||
|
||||
roomOf(roomId) {
|
||||
if (!roomId) return undefined
|
||||
this.#refresh()
|
||||
return this.#state.rooms?.[roomId]
|
||||
}
|
||||
|
||||
roomOfSession(sessionId) {
|
||||
if (!sessionId) return undefined
|
||||
this.#refresh()
|
||||
return this.#index.roomSessions.get(sessionId)
|
||||
?? this.#index.groupSessions.get(sessionId)?.roomId
|
||||
?? this.#index.pastGroupSessions.get(sessionId)?.roomId
|
||||
}
|
||||
|
||||
isMain(botId) {
|
||||
if (!botId) return false
|
||||
this.#refresh()
|
||||
return (this.#state.mainBotIds ?? []).includes(botId)
|
||||
}
|
||||
|
||||
roomsOfBot(botId) {
|
||||
this.#refresh()
|
||||
return Object.values(this.#state.rooms ?? {}).filter(room => (room.members ?? []).includes(botId))
|
||||
}
|
||||
|
||||
/** 私聊里操作某个群目标时,按 id 或名字找这个 Bot 所在的群。 */
|
||||
pickRoom(botId, ref) {
|
||||
const key = String(ref ?? '').trim()
|
||||
if (key === '') return { error: '缺少群名。' }
|
||||
const rooms = this.roomsOfBot(botId)
|
||||
const exactId = rooms.find(room => room.id === key)
|
||||
if (exactId) return { room: exactId }
|
||||
const exactName = rooms.filter(room => room.name === key)
|
||||
if (exactName.length === 1) return { room: exactName[0] }
|
||||
const loose = rooms.filter(room => room.name?.toLocaleLowerCase() === key.toLocaleLowerCase())
|
||||
if (loose.length === 1) return { room: loose[0] }
|
||||
if (loose.length > 1) return { error: `有 ${loose.length} 个同名群「${key}」;改用群 id。` }
|
||||
return { error: `这个 Bot 不在名为「${key}」的群里。` }
|
||||
}
|
||||
|
||||
goalOfRoom(roomId) {
|
||||
return this.roomOf(roomId)?.goal
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
import { goalDigest, stageDigest } from './digest.js'
|
||||
import { roleLabel } from './roles.js'
|
||||
|
||||
export const GOAL_MUTATIONS = new Set([
|
||||
'draft', 'start', 'revise', 'task', 'pass', 'rework', 'complete', 'pause', 'resume', 'stop',
|
||||
])
|
||||
|
||||
const deny = (code, reason) => ({ allow: false, code, reason })
|
||||
|
||||
function findReview(reviews, match) {
|
||||
for (let i = (reviews?.length ?? 0) - 1; i >= 0; i -= 1) {
|
||||
const review = reviews[i]
|
||||
if (review.projectId !== match.projectId) continue
|
||||
if (review.goalId !== match.goalId) continue
|
||||
if (review.goalRevision !== match.revision) continue
|
||||
if (review.kind !== match.kind) continue
|
||||
if ((review.stageIndex ?? null) !== (match.stageIndex ?? null)) continue
|
||||
if (review.digest !== match.digest) continue
|
||||
if (review.verdict !== match.verdict) continue
|
||||
if (match.reviewerRole !== undefined && review.reviewerRole !== match.reviewerRole) continue
|
||||
return review
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 返工预算直接取原生目标里的阶段累计,revise/换阶段都不清零。 */
|
||||
export function budgetOf(goal, project) {
|
||||
const used = (goal?.stages ?? []).reduce((sum, stage) => sum + (Number(stage.reworks) || 0), 0)
|
||||
const max = Number.isInteger(project?.maxReworks) && project.maxReworks > 0 ? project.maxReworks : 3
|
||||
return { used, max, left: Math.max(0, max - used) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 纯函数门禁:尚书是唯一目标操作者;阶段通过/驳回要自己的审查记录,
|
||||
* 目标完成要丞相的验收记录;返工受预算限制;工部与丞相不得改目标。
|
||||
*/
|
||||
export function evaluateGoalAction({ action, actor, project, goal, reviews, members, args }) {
|
||||
if (!project) return { allow: true }
|
||||
if (!GOAL_MUTATIONS.has(action)) return { allow: true }
|
||||
// 用户从页面/会话直接操作时放行;Bot 才需要角色约束。
|
||||
if (actor?.kind !== 'bot') return { allow: true }
|
||||
|
||||
const shangshuName = members?.find(member => member.role === 'shangshu')?.name ?? '尚书'
|
||||
const leadName = members?.find(member => member.role === 'lead')?.name ?? '丞相'
|
||||
|
||||
if (actor.isMain) {
|
||||
return deny('main-bot', `Main Bot 不操作已绑定项目的目标:让${shangshuName}推进、${leadName}验收。`)
|
||||
}
|
||||
if (actor.role === undefined) {
|
||||
return deny('not-member', `${actor.botName ?? '这个 Bot'} 不是本项目三角色成员,不能修改目标。`)
|
||||
}
|
||||
if (actor.role === 'gongbu') {
|
||||
return deny('gongbu', '工部只执行任务和回报,不修改目标;目标由尚书起草推进,丞相验收。')
|
||||
}
|
||||
if (actor.role === 'lead') {
|
||||
return deny('lead', '丞相不直接操作目标;请用 sansheng_review 记录目标验收,阶段推进交给尚书。')
|
||||
}
|
||||
|
||||
const roleOfName = name => members?.find(member => member.name === name)?.role
|
||||
|
||||
if (action === 'task') {
|
||||
const name = String(args?.bot ?? '').trim()
|
||||
if (name !== '') {
|
||||
const targetRole = roleOfName(name)
|
||||
if (targetRole === undefined) return deny('task-target', `工单目标“${name}”不是本项目群成员。`)
|
||||
if (targetRole !== 'gongbu') return deny('task-target', `工单只能派给工部;“${name}”的角色是${roleLabel(targetRole)}。`)
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
if (action === 'start' || action === 'revise') {
|
||||
for (const stage of args?.stages ?? []) {
|
||||
for (const task of stage?.tasks ?? []) {
|
||||
const name = String(task?.bot ?? '').trim()
|
||||
if (name === '') continue
|
||||
const targetRole = roleOfName(name)
|
||||
if (targetRole === undefined) {
|
||||
return deny('stage-target', `阶段「${stage?.title ?? ''}」的工单目标“${name}”不是本项目群成员。`)
|
||||
}
|
||||
if (targetRole !== 'gongbu') {
|
||||
return deny('stage-target', `阶段「${stage?.title ?? ''}」的工单只能派给工部;“${name}”的角色是${roleLabel(targetRole)}。`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
if (!goal) return { allow: true }
|
||||
|
||||
if (action === 'pass') {
|
||||
const stageIndex = goal.current + 1
|
||||
const stage = goal.stages?.[stageIndex - 1]
|
||||
if (!stage) return deny('no-stage', '当前没有可通过的阶段。')
|
||||
const digest = stageDigest(goal, stageIndex)
|
||||
if (!findReview(reviews, { projectId: project.id, goalId: goal.id, revision: goal.revision, kind: 'stage', stageIndex, digest, verdict: 'pass' })) {
|
||||
return deny('no-stage-review', `通过阶段 ${stageIndex}「${stage.title}」前,先用 sansheng_review action=stage_pass stage=${stageIndex} evidence=... 记录尚书审查。`)
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
if (action === 'rework') {
|
||||
const stageIndex = goal.current + 1
|
||||
const budget = budgetOf(goal, project)
|
||||
if (budget.used >= budget.max) {
|
||||
return deny('budget', `返工预算已用尽(${budget.used}/${budget.max})。请与用户确认后用 revise 调整目标,或 stop 结束。`)
|
||||
}
|
||||
const digest = stageDigest(goal, stageIndex)
|
||||
if (!findReview(reviews, { projectId: project.id, goalId: goal.id, revision: goal.revision, kind: 'stage', stageIndex, digest, verdict: 'reject' })) {
|
||||
return deny('no-reject-review', `驳回阶段 ${stageIndex} 前,先用 sansheng_review action=stage_reject reason=... 记录审查发现。`)
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
if (action === 'complete') {
|
||||
const stages = goal.stages ?? []
|
||||
if (stages.length === 0 || stages.some(stage => stage.status !== 'passed')) {
|
||||
return deny('not-all-passed', '还有阶段未通过,不能完成目标。')
|
||||
}
|
||||
const digest = goalDigest(goal)
|
||||
if (!findReview(reviews, { projectId: project.id, goalId: goal.id, revision: goal.revision, kind: 'goal', stageIndex: null, digest, verdict: 'pass', reviewerRole: 'lead' })) {
|
||||
return deny('no-goal-review', `完成前先由丞相记录目标验收:sansheng_review action=goal_pass evidence=...(当前版本 revision ${goal.revision})。`)
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
return { allow: true }
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import { evaluateGoalAction, GOAL_MUTATIONS } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import { roleOfBot } from './roles.js'
|
||||
|
||||
/**
|
||||
* 根级 tools.guard:原生 group_goal 执行前同步判定。
|
||||
* 只处理绑定了三省六部项目的群;未绑定的群保持 DS Bot 原生行为。
|
||||
*/
|
||||
export function installGates({ ctx, store, dsbot }) {
|
||||
return ctx.tools.guard(exec => {
|
||||
try {
|
||||
if (!exec || exec.name !== 'group_goal') return undefined
|
||||
const action = String(exec.arguments?.action ?? '')
|
||||
if (!GOAL_MUTATIONS.has(action)) return undefined
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
if (actor.kind !== 'bot') return undefined
|
||||
|
||||
let roomId = dsbot.roomOfSession(exec.agent?.id)
|
||||
if (!roomId) {
|
||||
const ref = String(exec.arguments?.group ?? '').trim()
|
||||
if (ref === '') return undefined
|
||||
const picked = dsbot.pickRoom(actor.botId, ref)
|
||||
if (picked.error !== undefined) return undefined
|
||||
roomId = picked.room.id
|
||||
}
|
||||
const project = store.projectByRoom(roomId)
|
||||
if (!project) return undefined
|
||||
|
||||
const room = dsbot.roomOf(roomId)
|
||||
const members = (room?.members ?? []).map(id => ({
|
||||
id,
|
||||
name: dsbot.botOf(id)?.name ?? id,
|
||||
role: roleOfBot(project, id),
|
||||
}))
|
||||
const verdict = evaluateGoalAction({
|
||||
action,
|
||||
actor: { ...actor, role: roleOfBot(project, actor.botId) },
|
||||
project,
|
||||
goal: room?.goal,
|
||||
reviews: store.peek().reviews,
|
||||
members,
|
||||
args: exec.arguments ?? {},
|
||||
})
|
||||
if (!verdict.allow) return `三省六部:${verdict.reason}`
|
||||
return undefined
|
||||
} catch (error) {
|
||||
// 校验内部出错时拒绝而不是放行:目标状态比一次调用重要。
|
||||
return `三省六部:目标校验失败(${error?.message ?? error}),本次修改未执行。`
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { roleOfBot } from './roles.js'
|
||||
|
||||
/**
|
||||
* 一次工具调用的真实身份:DS Bot 的会话 id → Bot id → 项目角色。
|
||||
* 身份只来自执行 agent 的会话映射,绝不采信模型参数里的自称。
|
||||
*/
|
||||
export function resolveActor({ dsbot, store, sessionId }) {
|
||||
const botId = sessionId ? dsbot.selfOf(sessionId) : undefined
|
||||
if (!botId) return { kind: 'user', sessionId }
|
||||
const bot = dsbot.botOf(botId)
|
||||
const project = store.projectByBot(botId)
|
||||
return {
|
||||
kind: 'bot',
|
||||
sessionId,
|
||||
botId,
|
||||
botName: bot?.name ?? botId,
|
||||
isMain: dsbot.isMain(botId),
|
||||
project,
|
||||
role: project ? roleOfBot(project, botId) : undefined,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/** DSH 主目录,与宿主一致:优先 DSH_HOME,否则 ~/.dsh。 */
|
||||
export function dshHome() {
|
||||
const fromEnv = process.env.DSH_HOME
|
||||
if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return fromEnv
|
||||
return join(homedir(), '.dsh')
|
||||
}
|
||||
|
||||
/** DS Bot 自己的状态文件(本插件只读)。 */
|
||||
export function dsbotStatePath(home = dshHome()) {
|
||||
return join(home, 'bot', 'state.json')
|
||||
}
|
||||
|
||||
/** 三省六部自己的补充记录(项目绑定、审查记录)。 */
|
||||
export function sanshengStatePath(home = dshHome()) {
|
||||
return join(home, 'sansheng', 'state.json')
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
export const ROLE_IDS = Object.freeze(['lead', 'shangshu', 'gongbu'])
|
||||
|
||||
export const ROLE_LABEL = Object.freeze({
|
||||
lead: '丞相',
|
||||
shangshu: '尚书',
|
||||
gongbu: '工部',
|
||||
})
|
||||
|
||||
export const ROLE_COLOR = Object.freeze({
|
||||
lead: 'gold',
|
||||
shangshu: 'blue',
|
||||
gongbu: 'green',
|
||||
})
|
||||
|
||||
/** 项目绑定里这个 Bot 的角色,未绑定或不是三角色时返回 undefined。 */
|
||||
export function roleOfBot(project, botId) {
|
||||
if (!project || typeof botId !== 'string') return undefined
|
||||
for (const role of ROLE_IDS) {
|
||||
if (project.bots?.[role] === botId) return role
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function roleLabel(role) {
|
||||
return ROLE_LABEL[role] ?? '成员'
|
||||
}
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
||||
import { dirname } from 'node:path'
|
||||
import { ROLE_IDS } from './roles.js'
|
||||
|
||||
const VERSION = 1
|
||||
export const REVIEW_LIMIT = 400
|
||||
|
||||
export function emptyState() {
|
||||
return { version: VERSION, projects: {}, reviews: [] }
|
||||
}
|
||||
|
||||
function normalize(raw) {
|
||||
const state = raw !== null && typeof raw === 'object' ? raw : {}
|
||||
return {
|
||||
version: VERSION,
|
||||
projects: state.projects !== null && typeof state.projects === 'object' ? state.projects : {},
|
||||
reviews: Array.isArray(state.reviews) ? state.reviews : [],
|
||||
}
|
||||
}
|
||||
|
||||
async function readJsonFile(file) {
|
||||
try {
|
||||
return JSON.parse(await readFile(file, 'utf8'))
|
||||
} catch (error) {
|
||||
if (error?.code === 'ENOENT') return undefined
|
||||
throw new Error(`读不了 ${file}:${error?.message ?? error}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function writeJsonAtomic(file, value) {
|
||||
await mkdir(dirname(file), { recursive: true })
|
||||
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
|
||||
await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
|
||||
await rename(tmp, file)
|
||||
}
|
||||
|
||||
/**
|
||||
* 三省六部的补充记录:项目绑定(ProjectBinding)与审查记录(ReviewRecord)。
|
||||
* 原生 group_goal 仍是阶段进度的唯一权威;这里只存它没有的东西。
|
||||
* 写入串行化,内存状态先更新再落盘,同步的 tools.guard 立即可见。
|
||||
*/
|
||||
export class SanshengStore {
|
||||
#file
|
||||
#state
|
||||
#ready
|
||||
#queue = Promise.resolve()
|
||||
|
||||
constructor(file) {
|
||||
this.#file = file
|
||||
this.#state = emptyState()
|
||||
this.#ready = undefined
|
||||
}
|
||||
|
||||
get file() {
|
||||
return this.#file
|
||||
}
|
||||
|
||||
async load() {
|
||||
this.#ready ??= readJsonFile(this.#file).then(raw => {
|
||||
this.#state = normalize(raw)
|
||||
return this.#state
|
||||
})
|
||||
return this.#ready
|
||||
}
|
||||
|
||||
/** 同步快照;guard 只能同步读取。 */
|
||||
peek() {
|
||||
return this.#state
|
||||
}
|
||||
|
||||
async transact(mutate) {
|
||||
const run = this.#queue.then(async () => {
|
||||
await this.load()
|
||||
const result = await mutate(this.#state)
|
||||
if (this.#state.reviews.length > REVIEW_LIMIT) {
|
||||
this.#state.reviews = this.#state.reviews.slice(-REVIEW_LIMIT)
|
||||
}
|
||||
await writeJsonAtomic(this.#file, this.#state)
|
||||
return result
|
||||
})
|
||||
this.#queue = run.then(() => undefined, () => undefined)
|
||||
return run
|
||||
}
|
||||
|
||||
projectByRoom(roomId) {
|
||||
if (!roomId) return undefined
|
||||
return Object.values(this.#state.projects).find(project => project.roomId === roomId)
|
||||
}
|
||||
|
||||
projectByBot(botId) {
|
||||
if (!botId) return undefined
|
||||
return Object.values(this.#state.projects).find(project => ROLE_IDS.some(role => project.bots?.[role] === botId))
|
||||
}
|
||||
|
||||
resolveProject(ref) {
|
||||
const key = String(ref ?? '').trim()
|
||||
if (key === '') return undefined
|
||||
const projects = Object.values(this.#state.projects)
|
||||
return projects.find(project => project.id === key)
|
||||
?? projects.find(project => project.name === key)
|
||||
?? projects.find(project => project.name?.toLocaleLowerCase() === key.toLocaleLowerCase())
|
||||
}
|
||||
|
||||
async saveProject(project) {
|
||||
return this.transact(state => {
|
||||
const previous = state.projects[project.id] ?? {}
|
||||
state.projects[project.id] = { ...previous, ...project, updatedAt: Date.now() }
|
||||
return state.projects[project.id]
|
||||
})
|
||||
}
|
||||
|
||||
async removeProject(id) {
|
||||
return this.transact(state => {
|
||||
const existed = state.projects[id] !== undefined
|
||||
delete state.projects[id]
|
||||
return existed
|
||||
})
|
||||
}
|
||||
|
||||
/** 相同 eventKey 的审查只记一次(重试/重复事件幂等)。 */
|
||||
async addReview(review) {
|
||||
return this.transact(state => {
|
||||
const existing = state.reviews.find(item => item.eventKey === review.eventKey)
|
||||
if (existing) return { review: existing, duplicate: true }
|
||||
state.reviews.push(review)
|
||||
return { review, duplicate: false }
|
||||
})
|
||||
}
|
||||
|
||||
reviewsFor(match = {}) {
|
||||
return this.#state.reviews
|
||||
.filter(item => Object.entries(match).every(([key, value]) => item[key] === value))
|
||||
.sort((a, b) => (b.at ?? 0) - (a.at ?? 0))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,433 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { goalDigest, sha256, stageDigest } from './digest.js'
|
||||
import { budgetOf } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import { ROLE_COLOR, ROLE_IDS, ROLE_LABEL } from './roles.js'
|
||||
|
||||
const TEXT_OUTPUT = {
|
||||
schema: { type: 'string' },
|
||||
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
||||
}
|
||||
|
||||
const ROOM_NOTICE = '三省六部规则:丞相定目标并做最终验收;尚书是群管理员,唯一用 group_goal 起草、派工、通过阶段与完成目标的人;工部只按工单执行并回报。阶段通过前先记录尚书审查;目标完成前先记录丞相验收。'
|
||||
|
||||
function registerTextTool(ctx, name, description, parameters, handler) {
|
||||
return ctx.tools.register({
|
||||
name,
|
||||
description,
|
||||
parameters,
|
||||
output: TEXT_OUTPUT,
|
||||
async execute(args, exec) {
|
||||
try {
|
||||
return await handler(args ?? {}, exec)
|
||||
} catch (error) {
|
||||
return `三省六部:${error?.message ?? error}`
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function clampInt(value, fallback, min, max) {
|
||||
const number = Number(value)
|
||||
if (!Number.isInteger(number)) return fallback
|
||||
return Math.min(max, Math.max(min, number))
|
||||
}
|
||||
|
||||
function shortId(id) {
|
||||
return String(id ?? '').slice(0, 8)
|
||||
}
|
||||
|
||||
function instructionsFor(role, project, groupName) {
|
||||
const common = `你属于「${project}」项目,项目群是「${groupName}」。三省六部分工:丞相定目标与最终验收,尚书调度阶段与工单,工部执行并回报。`
|
||||
if (role === 'lead') {
|
||||
return `${common}\n你是丞相,负责把用户需求变成明确目标、验收标准与约束,并在最后验收整体交付。\n- 目标由尚书用 group_goal 起草和推进;你不要直接改目标。\n- 每个阶段由尚书核查通过;全部阶段完成后,你核对整体成果与用户要求,成功时用 sansheng_review action=goal_pass 记录验收,不通过时用 action=goal_reject 写明问题。\n- 验收看证据(改动、测试输出、结果),不走过场,也不替尚书做阶段审查。`
|
||||
}
|
||||
if (role === 'shangshu') {
|
||||
return `${common}\n你是尚书,项目群管理员,也是唯一操作目标的人。\n- 用 group_goal 起草/启动/修订目标,按阶段把工单派给工部(派工用 @工部名 写进群里),跟踪进度。\n- 每个阶段结束后亲自核查证据:通过前先 sansheng_review action=stage_pass(带 evidence),再 group_goal pass;不通过就 action=stage_reject 记账后 group_goal rework。\n- 返工最多 3 轮、按整个目标累计;预算用尽时停下来和用户确认,改写目标用 revise 或 stop。\n- 全部阶段通过后交给丞相验收;丞相记录 goal_pass 之后,你才 group_goal complete。不要替丞相验收。`
|
||||
}
|
||||
return `${common}\n你是工部,负责执行与回报。\n- 只做工单里的任务,按该阶段的验收标准交付;交付时给出证据:改了哪些文件、跑了什么测试、结果如何。\n- 在项目群里 @尚书 回报进度和阻塞;不修改目标,不做阶段/目标验收。\n- 遇到需求不清或范围变化,交回尚书与丞相对齐,不自行扩大范围。`
|
||||
}
|
||||
|
||||
function projectBots(dsbot, project) {
|
||||
return ROLE_IDS.map(role => ({ role, id: project.bots?.[role], bot: dsbot.botOf(project.bots?.[role]) }))
|
||||
}
|
||||
|
||||
function projectLines(dsbot, project) {
|
||||
const room = dsbot.roomOf(project.roomId)
|
||||
const goal = room?.goal
|
||||
const bots = projectBots(dsbot, project).map(item => `${ROLE_LABEL[item.role]}=${item.bot?.name ?? item.id ?? '?'}`).join(',')
|
||||
const lines = [
|
||||
`项目「${project.name}」${project.id}`,
|
||||
` 群:${room?.name ?? project.roomId}(${shortId(project.roomId)}) ${room ? `管理员=${dsbot.botOf(room.admin)?.name ?? '无'}` : '群已不存在'}`,
|
||||
` Bot:${bots}`,
|
||||
` 模型:${ROLE_IDS.map(role => `${ROLE_LABEL[role]}=${project.models?.[role] ?? '默认'}`).join(',')} 返工预算:${project.maxReworks ?? 3}`,
|
||||
]
|
||||
if (!goal) {
|
||||
lines.push(' 目标:还没有(尚书用 group_goal draft/start 起草)')
|
||||
return lines
|
||||
}
|
||||
const budget = budgetOf(goal, project)
|
||||
const stage = goal.stages?.[goal.current]
|
||||
const passed = (goal.stages ?? []).filter(item => item.status === 'passed').length
|
||||
lines.push(` 目标:${goal.status} rev ${goal.revision} · 阶段 ${passed}/${goal.stages?.length ?? 0}${stage ? ` · 当前「${stage.title}」` : ''} · 返工 ${budget.used}/${budget.max}`)
|
||||
return lines
|
||||
}
|
||||
|
||||
async function provision({ ctx, store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
if (actor.kind === 'bot') return '只有用户能创建项目;Bot 在现有项目群里工作。'
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
if (!rt || typeof rt.createBot !== 'function') {
|
||||
return '没有找到 DS-Bot 运行时(dsbot-runtime 服务)。请先安装并启用 ds-bot,再重启 DSH;并用带 ctx.provide 的基线补丁(见 docs/p0/README.md)。'
|
||||
}
|
||||
await rt.load()
|
||||
|
||||
const projectName = String(args.project ?? '').trim()
|
||||
if (projectName === '') return '请提供 project(项目名)。'
|
||||
if (projectName.length > 40) return '项目名最多 40 个字符。'
|
||||
const existing = Object.values(store.peek().projects).find(project => project.name === projectName)
|
||||
if (existing) return `项目「${projectName}」已经存在(${existing.id},群 ${existing.roomId})。用 sansheng_status 查看。`
|
||||
|
||||
const botNames = {
|
||||
lead: String(args.leadName ?? '丞相').trim(),
|
||||
shangshu: String(args.shangshuName ?? '尚书').trim(),
|
||||
gongbu: String(args.gongbuName ?? '工部').trim(),
|
||||
}
|
||||
for (const role of ROLE_IDS) {
|
||||
if (botNames[role] === '') return `缺少${ROLE_LABEL[role]}的名字。`
|
||||
if (botNames[role].length > 40) return `${ROLE_LABEL[role]}的名字最多 40 个字符。`
|
||||
}
|
||||
if (new Set(ROLE_IDS.map(role => botNames[role])).size !== 3) return '三个 Bot 的名字必须不同。'
|
||||
|
||||
const models = {}
|
||||
for (const role of ROLE_IDS) {
|
||||
const raw = args.models?.[role]
|
||||
if (raw === undefined || raw === null || String(raw).trim() === '') continue
|
||||
try {
|
||||
models[role] = await rt.resolveModel(String(raw).trim())
|
||||
} catch (error) {
|
||||
return `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}`
|
||||
}
|
||||
}
|
||||
|
||||
const groupName = String(args.groupName ?? `${projectName} · 三省六部`).trim().slice(0, 40)
|
||||
const workDir = args.workDir === undefined || args.workDir === null || String(args.workDir).trim() === ''
|
||||
? undefined
|
||||
: String(args.workDir).trim()
|
||||
const maxReworks = clampInt(args.maxReworks, 3, 1, 10)
|
||||
|
||||
const created = []
|
||||
let room
|
||||
try {
|
||||
for (const role of ROLE_IDS) {
|
||||
const bot = await rt.createBot({
|
||||
name: botNames[role],
|
||||
role: ROLE_LABEL[role],
|
||||
instructions: instructionsFor(role, projectName, groupName),
|
||||
color: ROLE_COLOR[role],
|
||||
brief: `「${projectName}」项目的${ROLE_LABEL[role]}。`,
|
||||
model: models[role],
|
||||
...(workDir === undefined ? {} : { workDir }),
|
||||
})
|
||||
created.push(bot.id)
|
||||
}
|
||||
room = await rt.createRoom({
|
||||
members: created,
|
||||
name: groupName,
|
||||
admin: created[1],
|
||||
mode: 'admin',
|
||||
createdBy: null,
|
||||
notice: ROOM_NOTICE,
|
||||
})
|
||||
} catch (error) {
|
||||
for (const id of created) {
|
||||
try { await rt.deleteBot(id) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
return `创建失败:${error?.message ?? error}。已回滚新建的 Bot。`
|
||||
}
|
||||
|
||||
const project = {
|
||||
id: `prj-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
name: projectName,
|
||||
workspaceId: args.workspaceId === undefined ? null : String(args.workspaceId),
|
||||
workDir: workDir ?? null,
|
||||
roomId: room.id,
|
||||
bots: { lead: created[0], shangshu: created[1], gongbu: created[2] },
|
||||
models,
|
||||
maxReworks,
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
try {
|
||||
await store.saveProject(project)
|
||||
} catch (error) {
|
||||
if (typeof rt.deleteRoom === 'function') {
|
||||
try { await rt.deleteRoom(room.id) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
for (const id of created) {
|
||||
try { await rt.deleteBot(id) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
return `保存项目绑定失败:${error?.message ?? error}。已回滚群与 Bot。`
|
||||
}
|
||||
|
||||
return [
|
||||
`已创建项目「${projectName}」${project.id}。`,
|
||||
`群「${room.name}」:管理员=尚书 ${botNames.shangshu}。`,
|
||||
`Bot:丞相 ${botNames.lead} / 尚书 ${botNames.shangshu} / 工部 ${botNames.gongbu}。`,
|
||||
`模型:${ROLE_IDS.map(role => `${ROLE_LABEL[role]}=${models[role] ?? 'DS Bot 默认'}`).join(',')}。`,
|
||||
`返工预算 ${maxReworks} 轮(按整个目标累计)。`,
|
||||
'下一步:在项目群发需求,让丞相对齐目标;尚书用 group_goal 起草/启动,并按阶段 @工部 派工。',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
async function bind({ store, dsbot, args }) {
|
||||
const roomRef = String(args.room ?? '').trim()
|
||||
if (roomRef === '') return '请提供 room(项目群名或 id)。'
|
||||
const state = dsbot.snapshot()
|
||||
const rooms = Object.values(state.rooms ?? {})
|
||||
const room = rooms.find(item => item.id === roomRef)
|
||||
?? rooms.find(item => item.name === roomRef)
|
||||
?? rooms.find(item => item.name?.toLocaleLowerCase() === roomRef.toLocaleLowerCase())
|
||||
if (!room) return `找不到群「${roomRef}」。确认群名,或先在 DS Bot 里建群。`
|
||||
const existing = store.projectByRoom(room.id)
|
||||
if (existing) return `群「${room.name}」已绑定项目「${existing.name}」(${existing.id})。`
|
||||
|
||||
const findBot = ref => {
|
||||
const key = String(ref ?? '').trim()
|
||||
if (key === '') return undefined
|
||||
return state.bots?.[key] ?? dsbot.botByName(key)
|
||||
}
|
||||
const bots = {}
|
||||
for (const role of ROLE_IDS) {
|
||||
let bot = findBot(args[role])
|
||||
if (!bot) {
|
||||
bot = Object.values(state.bots ?? {}).find(item =>
|
||||
(room.members ?? []).includes(item.id) && (item.role === ROLE_LABEL[role] || item.name === ROLE_LABEL[role]))
|
||||
}
|
||||
if (!bot) return `没找到${ROLE_LABEL[role]} Bot:请用 ${role} 参数给名字或 id,或先把它加入群。`
|
||||
if (!(room.members ?? []).includes(bot.id)) return `${ROLE_LABEL[role]}「${bot.name}」不在群「${room.name}」里。`
|
||||
bots[role] = bot.id
|
||||
}
|
||||
if (new Set(Object.values(bots)).size !== 3) return '丞相/尚书/工部必须是三个不同的 Bot。'
|
||||
if (room.admin !== bots.shangshu) {
|
||||
const admin = room.admin ? state.bots?.[room.admin]?.name ?? room.admin : '无'
|
||||
return `群管理员当前是 ${admin},必须是尚书。先在 DS Bot 的群设置里把管理员改成${ROLE_LABEL.shangshu},再绑定。`
|
||||
}
|
||||
|
||||
const project = {
|
||||
id: `prj-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
name: String(args.project ?? room.name).trim().slice(0, 40),
|
||||
workspaceId: args.workspaceId === undefined ? null : String(args.workspaceId),
|
||||
workDir: args.workDir === undefined || args.workDir === null ? null : String(args.workDir),
|
||||
roomId: room.id,
|
||||
bots,
|
||||
models: args.models ?? {},
|
||||
maxReworks: clampInt(args.maxReworks, 3, 1, 10),
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
await store.saveProject(project)
|
||||
return [
|
||||
`已把群「${room.name}」绑定为项目「${project.name}」(${project.id})。`,
|
||||
`丞相=${state.bots?.[bots.lead]?.name},尚书=${state.bots?.[bots.shangshu]?.name}(管理员),工部=${state.bots?.[bots.gongbu]?.name}。`,
|
||||
'从下一次 group_goal 起,角色、审查记录与返工预算开始生效。',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function status({ store, dsbot, args }) {
|
||||
const projects = args.project === undefined || String(args.project).trim() === ''
|
||||
? Object.values(store.peek().projects)
|
||||
: [store.resolveProject(args.project)].filter(Boolean)
|
||||
if (projects.length === 0) {
|
||||
const managed = Object.values(store.peek().projects).length
|
||||
return managed === 0
|
||||
? '还没有绑定任何项目。用 sansheng_provision 创建(三 Bot + 项目群),或 sansheng_bind 绑定现有群。'
|
||||
: `找不到项目「${args.project}」。用 sansheng_status 不带参数列出全部。`
|
||||
}
|
||||
return projects.map(project => projectLines(dsbot, project).join('\n')).join('\n\n')
|
||||
}
|
||||
|
||||
async function review({ store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
let project = actor.project
|
||||
if (!project && args.project !== undefined) project = store.resolveProject(args.project)
|
||||
if (!project) return '找不到项目:请在项目群里调用,或用 project 参数指定。'
|
||||
|
||||
const room = dsbot.roomOf(project.roomId)
|
||||
const goal = room?.goal
|
||||
if (!goal) return `项目「${project.name}」的目标还没起草,先让尚书用 group_goal draft/start。`
|
||||
|
||||
const action = String(args.action ?? '')
|
||||
const stageAction = action === 'stage_pass' || action === 'stage_reject'
|
||||
const goalAction = action === 'goal_pass' || action === 'goal_reject'
|
||||
if (!stageAction && !goalAction) return 'action 必须是 stage_pass / stage_reject / goal_pass / goal_reject。'
|
||||
|
||||
if (actor.kind === 'bot') {
|
||||
const needed = stageAction ? 'shangshu' : 'lead'
|
||||
if (actor.role !== needed) {
|
||||
return `${action} 只能由${ROLE_LABEL[needed]}记录;当前身份是${actor.role ? ROLE_LABEL[actor.role] : '非项目成员'}。`
|
||||
}
|
||||
}
|
||||
|
||||
const evidence = String(args.evidence ?? '').trim()
|
||||
const reason = String(args.reason ?? '').trim()
|
||||
|
||||
if (stageAction) {
|
||||
if (goal.status !== 'active') return `目标当前是 ${goal.status},不能记录阶段审查。`
|
||||
const stageIndex = Number.isInteger(args.stage) ? args.stage : goal.current + 1
|
||||
if (stageIndex < 1 || stageIndex > (goal.stages?.length ?? 0)) return `阶段号 ${stageIndex} 超出范围(1-${goal.stages?.length ?? 0})。`
|
||||
if (stageIndex !== goal.current + 1) {
|
||||
const current = goal.stages?.[goal.current]
|
||||
return `只能审查当前阶段 ${goal.current + 1}${current ? `「${current.title}」` : ''};已通过的阶段不能补记审查。`
|
||||
}
|
||||
const stage = goal.stages[stageIndex - 1]
|
||||
if (action === 'stage_pass' && evidence === '') return '通过阶段必须写 evidence:测试输出、改动文件或检查结果。'
|
||||
if (action === 'stage_reject' && reason === '') return '驳回阶段必须写 reason:缺什么、怎么改。'
|
||||
const digest = stageDigest(goal, stageIndex)
|
||||
const record = {
|
||||
id: `rev-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'stage',
|
||||
stageIndex,
|
||||
stageTitle: stage.title,
|
||||
digest,
|
||||
verdict: action === 'stage_pass' ? 'pass' : 'reject',
|
||||
reviewerRole: actor.kind === 'bot' ? 'shangshu' : 'user',
|
||||
reviewerBotId: actor.botId ?? null,
|
||||
reviewerSessionId: actor.sessionId ?? null,
|
||||
evidence: evidence === '' ? null : evidence,
|
||||
reason: reason === '' ? null : reason,
|
||||
at: Date.now(),
|
||||
}
|
||||
record.eventKey = sha256(JSON.stringify({
|
||||
projectId: record.projectId, goalId: record.goalId, goalRevision: record.goalRevision,
|
||||
kind: record.kind, stageIndex, digest, verdict: record.verdict,
|
||||
reviewerRole: record.reviewerRole, reviewerBotId: record.reviewerBotId,
|
||||
}))
|
||||
const result = await store.addReview(record)
|
||||
if (result.duplicate) return `同样的阶段审查已记录(${result.review.id}),没有重复写入。`
|
||||
if (record.verdict === 'pass') {
|
||||
return `已记录尚书阶段审查 ${record.id}:阶段 ${stageIndex}「${stage.title}」通过,目标版本 ${goal.revision}。现在可以 group_goal pass(evidence 用同一份证据)。`
|
||||
}
|
||||
const budget = budgetOf(goal, project)
|
||||
return `已记录尚书阶段审查 ${record.id}:阶段 ${stageIndex}「${stage.title}」驳回,目标版本 ${goal.revision}。可以 group_goal rework;返工将计为 ${budget.used + 1}/${budget.max}。`
|
||||
}
|
||||
|
||||
const oneGoal = goal
|
||||
if (oneGoal.status !== 'active') return `目标当前是 ${oneGoal.status},不能做目标验收。`
|
||||
const stages = oneGoal.stages ?? []
|
||||
if (stages.length === 0 || stages.some(stage => stage.status !== 'passed')) {
|
||||
const open = stages.findIndex(stage => stage.status !== 'passed')
|
||||
return `还有阶段没通过(第 ${open + 1} 阶段${stages[open]?.title ? `「${stages[open].title}」` : ''}),丞相不能做整体验收。`
|
||||
}
|
||||
if (action === 'goal_pass' && evidence === '') return '目标验收通过必须写 evidence:整体交付与验收标准的对照。'
|
||||
if (action === 'goal_reject' && reason === '') return '目标验收驳回必须写 reason:不满足哪条验收标准。'
|
||||
const digest = goalDigest(oneGoal)
|
||||
const record = {
|
||||
id: `rev-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
projectId: project.id,
|
||||
goalId: oneGoal.id,
|
||||
goalRevision: oneGoal.revision,
|
||||
kind: 'goal',
|
||||
stageIndex: null,
|
||||
stageTitle: null,
|
||||
digest,
|
||||
verdict: action === 'goal_pass' ? 'pass' : 'reject',
|
||||
reviewerRole: actor.kind === 'bot' ? 'lead' : 'user',
|
||||
reviewerBotId: actor.botId ?? null,
|
||||
reviewerSessionId: actor.sessionId ?? null,
|
||||
evidence: evidence === '' ? null : evidence,
|
||||
reason: reason === '' ? null : reason,
|
||||
at: Date.now(),
|
||||
}
|
||||
record.eventKey = sha256(JSON.stringify({
|
||||
projectId: record.projectId, goalId: record.goalId, goalRevision: record.goalRevision,
|
||||
kind: record.kind, stageIndex: null, digest, verdict: record.verdict,
|
||||
reviewerRole: record.reviewerRole, reviewerBotId: record.reviewerBotId,
|
||||
}))
|
||||
const result = await store.addReview(record)
|
||||
if (result.duplicate) return `同样的目标验收已记录(${result.review.id}),没有重复写入。`
|
||||
return record.verdict === 'pass'
|
||||
? `已记录丞相目标验收 ${record.id}(目标版本 ${oneGoal.revision})。尚书现在可以 group_goal complete。`
|
||||
: `已记录丞相目标验收驳回 ${record.id}(目标版本 ${oneGoal.revision})。让尚书 revise 目标或继续返工后重新验收。`
|
||||
}
|
||||
|
||||
export function installTools({ ctx, store, dsbot }) {
|
||||
const disposers = [
|
||||
registerTextTool(ctx,
|
||||
'sansheng_provision',
|
||||
'创建三省六部项目:三个 Bot(丞相/尚书/工部)和一个项目群(尚书为管理员),并写入项目绑定。只有用户可调用。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['project'],
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名,如“官网改版”。' },
|
||||
groupName: { type: 'string', description: '项目群名,默认“项目名 · 三省六部”。' },
|
||||
leadName: { type: 'string', description: '丞相 Bot 名,默认“丞相”。' },
|
||||
shangshuName: { type: 'string', description: '尚书 Bot 名,默认“尚书”。' },
|
||||
gongbuName: { type: 'string', description: '工部 Bot 名,默认“工部”。' },
|
||||
workDir: { type: 'string', description: '三个 Bot 的工作目录(可选)。' },
|
||||
workspaceId: { type: 'string', description: '工作区 id(可选,仅登记用)。' },
|
||||
models: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
lead: { type: 'string', description: '丞相使用的 provider/model。' },
|
||||
shangshu: { type: 'string', description: '尚书使用的 provider/model。' },
|
||||
gongbu: { type: 'string', description: '工部使用的 provider/model。' },
|
||||
},
|
||||
},
|
||||
maxReworks: { type: 'integer', minimum: 1, maximum: 10, description: '返工预算,按整个目标累计,默认 3。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => provision({ ctx, store, dsbot, args, exec })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_bind',
|
||||
'把已有的 DS Bot 群绑定为三省六部项目:校验三个角色都在群里、群管理员是尚书。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['room'],
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名,默认用群名。' },
|
||||
room: { type: 'string', description: '项目群名或群 id。' },
|
||||
lead: { type: 'string', description: '丞相 Bot 名或 id(可选,默认按角色名找)。' },
|
||||
shangshu: { type: 'string', description: '尚书 Bot 名或 id(可选)。' },
|
||||
gongbu: { type: 'string', description: '工部 Bot 名或 id(可选)。' },
|
||||
workDir: { type: 'string', description: '项目工作目录(登记用)。' },
|
||||
workspaceId: { type: 'string', description: '工作区 id(登记用)。' },
|
||||
maxReworks: { type: 'integer', minimum: 1, maximum: 10, description: '返工预算,默认 3。' },
|
||||
},
|
||||
},
|
||||
args => bind({ store, dsbot, args })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_status',
|
||||
'查看三省六部项目状态:三角色 Bot、项目群、目标阶段、返工预算。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名或 id;省略则列出全部。' },
|
||||
},
|
||||
},
|
||||
args => status({ store, dsbot, args })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_review',
|
||||
'记录审查:尚书记录阶段通过/驳回,丞相记录目标验收通过/驳回。门禁要求通过阶段前有尚书 stage_pass、完成目标前有丞相 goal_pass,且证据与当前目标版本一致。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['action'],
|
||||
properties: {
|
||||
action: { type: 'string', enum: ['stage_pass', 'stage_reject', 'goal_pass', 'goal_reject'], description: '审查类型。' },
|
||||
project: { type: 'string', description: '项目名或 id;在项目群内可省略。' },
|
||||
stage: { type: 'integer', minimum: 1, description: '阶段号,默认当前阶段。' },
|
||||
evidence: { type: 'string', description: 'stage_pass/goal_pass 必填:测试输出、改动文件、验收对照。' },
|
||||
reason: { type: 'string', description: 'stage_reject/goal_reject 必填:缺什么、怎么改。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => review({ store, dsbot, args, exec })),
|
||||
]
|
||||
return disposers
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { canonical, goalDigest, stageDigest } from '../src/digest.js'
|
||||
|
||||
test('canonical 与键顺序无关', () => {
|
||||
assert.equal(canonical({ b: 1, a: 2 }), canonical({ a: 2, b: 1 }))
|
||||
assert.equal(canonical({ a: [1, { d: 4, c: 3 }] }), '{"a":[1,{"c":3,"d":4}]}')
|
||||
})
|
||||
|
||||
const goal = () => ({
|
||||
id: 'goal-1',
|
||||
objective: 'o',
|
||||
acceptance: 'a',
|
||||
constraints: ['c'],
|
||||
stages: [
|
||||
{
|
||||
id: 's1',
|
||||
title: '一',
|
||||
acceptance: 'x',
|
||||
status: 'active',
|
||||
tasks: [{ id: 't1', botId: 'b', task: 'do', status: 'pending', note: '' }],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
test('stageDigest 随任务状态/备注变化', () => {
|
||||
const a = goal()
|
||||
const first = stageDigest(a, 1)
|
||||
a.stages[0].tasks[0].status = 'done'
|
||||
const second = stageDigest(a, 1)
|
||||
assert.notEqual(first, second)
|
||||
|
||||
a.stages[0].tasks[0].task = 'do more'
|
||||
assert.notEqual(second, stageDigest(a, 1))
|
||||
})
|
||||
|
||||
test('stageDigest 对不存在的阶段返回 undefined', () => {
|
||||
assert.equal(stageDigest(goal(), 2), undefined)
|
||||
})
|
||||
|
||||
test('goalDigest 含整体目标与阶段状态', () => {
|
||||
const a = goal()
|
||||
const first = goalDigest(a)
|
||||
a.stages[0].status = 'passed'
|
||||
assert.notEqual(first, goalDigest(a))
|
||||
a.acceptance = 'a2'
|
||||
assert.notEqual(first, goalDigest(a))
|
||||
})
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { DsBotState } from '../src/dsbot-state.js'
|
||||
|
||||
const state = {
|
||||
version: 1,
|
||||
mainBotIds: ['bot-lead'],
|
||||
bots: {
|
||||
'bot-lead': { id: 'bot-lead', name: '丞相', sessionId: 'sess-lead', segments: [{ sessionId: 'sess-lead-old' }] },
|
||||
'bot-shang': { id: 'bot-shang', name: '尚书', sessionId: 'sess-shang' },
|
||||
'bot-gong': { id: 'bot-gong', name: '工部', sessionId: 'sess-gong' },
|
||||
},
|
||||
rooms: {
|
||||
'room-1': {
|
||||
id: 'room-1',
|
||||
name: '示例 · 三省六部',
|
||||
members: ['bot-lead', 'bot-shang', 'bot-gong'],
|
||||
admin: 'bot-shang',
|
||||
sessions: { 'bot-lead': 'grp-lead', 'bot-shang': 'grp-shang', 'bot-gong': 'grp-gong' },
|
||||
segments: { 'bot-shang': [{ sessionId: 'grp-shang-old' }] },
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
test('会话与群成员可反查,且能按名字选群', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-state-'))
|
||||
try {
|
||||
const file = join(dir, 'state.json')
|
||||
await writeFile(file, JSON.stringify(state), 'utf8')
|
||||
const dsbot = new DsBotState(file)
|
||||
|
||||
assert.equal(dsbot.selfOf('sess-lead'), 'bot-lead')
|
||||
assert.equal(dsbot.selfOf('grp-gong'), 'bot-gong')
|
||||
assert.equal(dsbot.selfOf('grp-shang-old'), 'bot-shang')
|
||||
assert.equal(dsbot.selfOf('sess-lead-old'), 'bot-lead')
|
||||
assert.equal(dsbot.selfOf('nobody'), undefined)
|
||||
|
||||
assert.equal(dsbot.roomOfSession('grp-shang'), 'room-1')
|
||||
assert.equal(dsbot.roomOfSession('room-1'), 'room-1')
|
||||
assert.equal(dsbot.roomOfSession('sess-shang'), undefined)
|
||||
|
||||
assert.equal(dsbot.botOf('bot-gong').name, '工部')
|
||||
assert.equal(dsbot.botByName('尚书').id, 'bot-shang')
|
||||
assert.equal(dsbot.isMain('bot-lead'), true)
|
||||
assert.equal(dsbot.isMain('bot-shang'), false)
|
||||
|
||||
assert.equal(dsbot.roomsOfBot('bot-gong').length, 1)
|
||||
assert.equal(dsbot.pickRoom('bot-gong', '示例 · 三省六部').room.id, 'room-1')
|
||||
assert.equal(dsbot.pickRoom('bot-gong', 'room-1').room.id, 'room-1')
|
||||
assert.match(dsbot.pickRoom('bot-gong', '不存在').error, /不在名为/)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('文件不存在时返回空快照而非抛错', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-state-'))
|
||||
try {
|
||||
const dsbot = new DsBotState(join(dir, 'missing.json'))
|
||||
assert.deepEqual(dsbot.snapshot().bots, {})
|
||||
assert.equal(dsbot.selfOf('x'), undefined)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,217 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { goalDigest, stageDigest } from '../src/digest.js'
|
||||
import { budgetOf, evaluateGoalAction } from '../src/gate.js'
|
||||
|
||||
const project = {
|
||||
id: 'prj-1',
|
||||
name: '示例项目',
|
||||
bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' },
|
||||
maxReworks: 3,
|
||||
}
|
||||
|
||||
const members = [
|
||||
{ id: 'b-lead', name: '丞相', role: 'lead' },
|
||||
{ id: 'b-shang', name: '尚书', role: 'shangshu' },
|
||||
{ id: 'b-gong', name: '工部', role: 'gongbu' },
|
||||
]
|
||||
|
||||
function actorFor(role, extra = {}) {
|
||||
return {
|
||||
kind: 'bot',
|
||||
botId: project.bots[role],
|
||||
botName: { lead: '丞相', shangshu: '尚书', gongbu: '工部' }[role],
|
||||
role,
|
||||
isMain: false,
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
function makeGoal() {
|
||||
return {
|
||||
id: 'goal-1',
|
||||
revision: 5,
|
||||
status: 'active',
|
||||
objective: '交付官网',
|
||||
acceptance: '首页可访问且测试通过',
|
||||
constraints: ['不改数据库'],
|
||||
current: 0,
|
||||
stages: [
|
||||
{
|
||||
id: 's1',
|
||||
title: '搭骨架',
|
||||
acceptance: '页面能打开',
|
||||
status: 'active',
|
||||
reworks: 0,
|
||||
tasks: [{ id: 't1', botId: 'b-gong', task: '写页面', status: 'reported', note: '' }],
|
||||
},
|
||||
{
|
||||
id: 's2',
|
||||
title: '补内容',
|
||||
acceptance: '文案齐全',
|
||||
status: 'pending',
|
||||
reworks: 0,
|
||||
tasks: [{ id: 't2', botId: 'b-gong', task: '填文案', status: 'pending' }],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function stageReview(goal, stageIndex, verdict) {
|
||||
return {
|
||||
id: `rev-${stageIndex}-${verdict}`,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'stage',
|
||||
stageIndex,
|
||||
digest: stageDigest(goal, stageIndex),
|
||||
verdict,
|
||||
reviewerRole: 'shangshu',
|
||||
}
|
||||
}
|
||||
|
||||
function goalReview(goal, verdict) {
|
||||
return {
|
||||
id: `rev-goal-${verdict}`,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'goal',
|
||||
stageIndex: null,
|
||||
digest: goalDigest(goal),
|
||||
verdict,
|
||||
reviewerRole: 'lead',
|
||||
}
|
||||
}
|
||||
|
||||
const decide = (overrides = {}) => evaluateGoalAction({
|
||||
action: 'pass',
|
||||
actor: actorFor('shangshu'),
|
||||
project,
|
||||
goal: makeGoal(),
|
||||
reviews: [],
|
||||
members,
|
||||
args: {},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
test('未绑定项目的群保持原生行为', () => {
|
||||
assert.equal(decide({ project: undefined }).allow, true)
|
||||
})
|
||||
|
||||
test('用户身份放行', () => {
|
||||
assert.equal(decide({ actor: { kind: 'user' } }).allow, true)
|
||||
})
|
||||
|
||||
test('工部不能改目标', () => {
|
||||
const result = decide({ actor: actorFor('gongbu') })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'gongbu')
|
||||
})
|
||||
|
||||
test('丞相不能直接改目标', () => {
|
||||
const result = decide({ actor: actorFor('lead') })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'lead')
|
||||
})
|
||||
|
||||
test('Main Bot 不能操作已绑定项目', () => {
|
||||
const result = decide({ actor: actorFor('shangshu', { isMain: true }) })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'main-bot')
|
||||
})
|
||||
|
||||
test('尚书通过阶段前必须有同一版本的阶段审查', () => {
|
||||
const goal = makeGoal()
|
||||
const result = decide({ goal, reviews: [] })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'no-stage-review')
|
||||
|
||||
const ok = decide({ goal, reviews: [stageReview(goal, 1, 'pass')] })
|
||||
assert.equal(ok.allow, true)
|
||||
})
|
||||
|
||||
test('审查记录版本过期后失效', () => {
|
||||
const goal = makeGoal()
|
||||
const stale = stageReview(goal, 1, 'pass')
|
||||
goal.revision = 6
|
||||
const result = decide({ goal, reviews: [stale] })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'no-stage-review')
|
||||
})
|
||||
|
||||
test('审查后任务状态变了也算证据过期', () => {
|
||||
const goal = makeGoal()
|
||||
const review = stageReview(goal, 1, 'pass')
|
||||
goal.stages[0].tasks[0].status = 'done'
|
||||
const result = decide({ goal, reviews: [review] })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'no-stage-review')
|
||||
})
|
||||
|
||||
test('驳回需要尚书 reject 记录,且受返工预算限制', () => {
|
||||
const goal = makeGoal()
|
||||
const none = decide({ action: 'rework', goal, reviews: [], args: { reason: '缺测试' } })
|
||||
assert.equal(none.allow, false)
|
||||
assert.equal(none.code, 'no-reject-review')
|
||||
|
||||
const ok = decide({ action: 'rework', goal, reviews: [stageReview(goal, 1, 'reject')], args: { reason: '缺测试' } })
|
||||
assert.equal(ok.allow, true)
|
||||
|
||||
goal.stages[0].reworks = 3
|
||||
assert.deepEqual(budgetOf(goal, project), { used: 3, max: 3, left: 0 })
|
||||
const spent = decide({ action: 'rework', goal, reviews: [stageReview(goal, 1, 'reject')], args: { reason: '再来' } })
|
||||
assert.equal(spent.allow, false)
|
||||
assert.equal(spent.code, 'budget')
|
||||
})
|
||||
|
||||
test('完成目标需要丞相 goal_pass 记录', () => {
|
||||
const goal = makeGoal()
|
||||
goal.current = 2
|
||||
goal.stages[0].status = 'passed'
|
||||
goal.stages[1].status = 'passed'
|
||||
|
||||
const missing = decide({ action: 'complete', goal, reviews: [], args: { evidence: 'e', summary: 's' } })
|
||||
assert.equal(missing.allow, false)
|
||||
assert.equal(missing.code, 'no-goal-review')
|
||||
|
||||
const ok = decide({ action: 'complete', goal, reviews: [goalReview(goal, 'pass')], args: { evidence: 'e', summary: 's' } })
|
||||
assert.equal(ok.allow, true)
|
||||
|
||||
const stageOnly = decide({ action: 'complete', goal, reviews: [stageReview(goal, 1, 'pass')], args: {} })
|
||||
assert.equal(stageOnly.allow, false)
|
||||
})
|
||||
|
||||
test('阶段未全部通过时不能完成', () => {
|
||||
const goal = makeGoal()
|
||||
const result = decide({ action: 'complete', goal, reviews: [goalReview(goal, 'pass')], args: {} })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'not-all-passed')
|
||||
})
|
||||
|
||||
test('工单只能派给工部', () => {
|
||||
const bad = decide({ action: 'task', args: { bot: '丞相' } })
|
||||
assert.equal(bad.allow, false)
|
||||
assert.equal(bad.code, 'task-target')
|
||||
|
||||
const good = decide({ action: 'task', args: { bot: '工部' } })
|
||||
assert.equal(good.allow, true)
|
||||
})
|
||||
|
||||
test('启动目标时每个任务的执行者都必须是工部', () => {
|
||||
const stages = [{ title: '一', acceptance: 'a', tasks: [{ bot: '工部', task: '做' }] }]
|
||||
assert.equal(decide({ action: 'start', args: { stages } }).allow, true)
|
||||
|
||||
const bad = [{ title: '一', acceptance: 'a', tasks: [{ bot: '丞相', task: '做' }] }]
|
||||
const result = decide({ action: 'start', args: { stages: bad } })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'stage-target')
|
||||
})
|
||||
|
||||
test('暂停/停止/修订由尚书放行', () => {
|
||||
for (const action of ['pause', 'resume', 'stop', 'revise', 'draft']) {
|
||||
const result = decide({ action, args: {} })
|
||||
assert.equal(result.allow, true, `${action} 应放行`)
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
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 { SanshengStore } from '../src/store.js'
|
||||
|
||||
const project = {
|
||||
id: 'prj-1',
|
||||
name: '示例项目',
|
||||
workspaceId: 'ws-1',
|
||||
roomId: 'room-1',
|
||||
bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' },
|
||||
models: {},
|
||||
maxReworks: 3,
|
||||
}
|
||||
|
||||
function review(overrides = {}) {
|
||||
return {
|
||||
id: 'rev-1',
|
||||
projectId: 'prj-1',
|
||||
goalId: 'goal-1',
|
||||
goalRevision: 2,
|
||||
kind: 'stage',
|
||||
stageIndex: 1,
|
||||
digest: 'abc',
|
||||
verdict: 'pass',
|
||||
reviewerRole: 'shangshu',
|
||||
eventKey: 'same',
|
||||
at: 1,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
test('项目绑定与审查记录可持久化、可反查', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
const file = join(dir, 'state.json')
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
await store.saveProject(project)
|
||||
|
||||
assert.equal(store.projectByRoom('room-1').id, 'prj-1')
|
||||
assert.equal(store.projectByBot('b-gong').id, 'prj-1')
|
||||
assert.equal(store.resolveProject('示例项目').id, 'prj-1')
|
||||
|
||||
const first = await store.addReview(review())
|
||||
assert.equal(first.duplicate, false)
|
||||
const second = await store.addReview(review({ id: 'rev-2' }))
|
||||
assert.equal(second.duplicate, true)
|
||||
assert.equal(store.peek().reviews.length, 1)
|
||||
|
||||
const reloaded = new SanshengStore(file)
|
||||
await reloaded.load()
|
||||
assert.equal(reloaded.peek().projects['prj-1'].name, '示例项目')
|
||||
assert.equal(reloaded.peek().reviews.length, 1)
|
||||
assert.equal(reloaded.reviewsFor({ projectId: 'prj-1' }).length, 1)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('状态文件损坏时 load 明确报错而不是静默清空', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
const file = join(dir, 'state.json')
|
||||
const { writeFile } = await import('node:fs/promises')
|
||||
await writeFile(file, '{not json', 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), /读不了/)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
Loading…
Reference in New Issue