feat(sansheng): 派发回执与重启对账、返工预算记账与自动返工
This commit is contained in:
parent
f13601ce0c
commit
ad248a6d60
|
|
@ -1,6 +1,8 @@
|
|||
import { DsBotState } from './src/dsbot-state.js'
|
||||
import { installGates } from './src/gates.js'
|
||||
import { installObserver } from './src/observe.js'
|
||||
import { dsbotStatePath, sanshengStatePath } from './src/paths.js'
|
||||
import { newBootId } from './src/records.js'
|
||||
import { SanshengStore } from './src/store.js'
|
||||
import { installTools } from './src/tools.js'
|
||||
|
||||
|
|
@ -9,7 +11,8 @@ export const inject = ['tools']
|
|||
|
||||
/**
|
||||
* 三省六部伴侣插件。原生 group_goal 是阶段进度唯一权威;
|
||||
* 这里只补 DS Bot 没有的东西:项目三角色绑定、审查记录、目标门禁。
|
||||
* 这里只补 DS Bot 没有的东西:项目三角色绑定、审查记录、目标门禁、
|
||||
* 派发回执与返工预算。
|
||||
*/
|
||||
export async function apply(ctx, config = {}) {
|
||||
const home = typeof config.home === 'string' && config.home.trim() !== '' ? config.home : undefined
|
||||
|
|
@ -19,11 +22,18 @@ export async function apply(ctx, config = {}) {
|
|||
const dsbot = new DsBotState(
|
||||
typeof config.dsbotStatePath === 'string' && config.dsbotStatePath !== '' ? config.dsbotStatePath : dsbotStatePath(home),
|
||||
)
|
||||
const bootId = newBootId()
|
||||
try {
|
||||
await store.load()
|
||||
// 重启对账:上次启动里停在 intent 的派发,结果未知,标记待核实。
|
||||
const pending = await store.reconcileDispatches(bootId)
|
||||
if (pending > 0) {
|
||||
console.warn(`sansheng: ${pending} 条派发在上次退出时未拿到回执,已标记待核实(用 sansheng_reconcile 核对)。`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`sansheng: 无法读取 ${store.file}:${error?.message ?? error}`)
|
||||
}
|
||||
installGates({ ctx, store, dsbot })
|
||||
installTools({ ctx, store, dsbot })
|
||||
installObserver({ ctx, store, dsbot, bootId })
|
||||
installTools({ ctx, store, dsbot, bootId })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,136 @@
|
|||
import { budgetOf } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import { describeDispatch, detectRework, isGoalMutation, isToolError, newId } from './records.js'
|
||||
import { roleOfBot } from './roles.js'
|
||||
|
||||
/**
|
||||
* 观测 group_goal:调用前落一条派发意图,调用后补回执。
|
||||
* 原生机制仍是唯一执行者;这里只记账、对账,以及在确认返工时把返工单交给工部。
|
||||
* 任何记账失败都不能影响原生调用的结果。
|
||||
*/
|
||||
export function installObserver({ ctx, store, dsbot, bootId }) {
|
||||
return ctx.on('tools/execute', async (exec, next) => {
|
||||
if (!exec || exec.name !== 'group_goal') return next()
|
||||
const action = String(exec.arguments?.action ?? '')
|
||||
if (!isGoalMutation(action)) return next()
|
||||
|
||||
let record
|
||||
let before
|
||||
let project
|
||||
let roomId
|
||||
try {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
roomId = dsbot.roomOfSession(exec.agent?.id)
|
||||
if (!roomId) {
|
||||
const ref = String(exec.arguments?.group ?? '').trim()
|
||||
if (ref !== '' && actor.botId) {
|
||||
const picked = dsbot.pickRoom(actor.botId, ref)
|
||||
if (picked.error === undefined) roomId = picked.room.id
|
||||
}
|
||||
}
|
||||
project = roomId ? store.projectByRoom(roomId) : undefined
|
||||
if (project) {
|
||||
const room = dsbot.roomOf(roomId)
|
||||
before = room?.goal
|
||||
record = {
|
||||
id: newId('dsp'),
|
||||
bootId,
|
||||
projectId: project.id,
|
||||
roomId,
|
||||
goalId: before?.id ?? null,
|
||||
goalRevision: before?.revision ?? null,
|
||||
action,
|
||||
stageIndex: action === 'pass' || action === 'rework' ? (before?.current ?? -1) + 1 : null,
|
||||
actorBotId: actor.botId ?? null,
|
||||
actorRole: actor.kind === 'bot' ? roleOfBot(project, actor.botId) : 'user',
|
||||
actorName: actor.botName ?? null,
|
||||
reason: String(exec.arguments?.reason ?? '').trim() || null,
|
||||
}
|
||||
await store.beginDispatch(record)
|
||||
}
|
||||
} catch {
|
||||
record = undefined
|
||||
}
|
||||
|
||||
let result
|
||||
try {
|
||||
result = await next()
|
||||
} catch (error) {
|
||||
if (record) {
|
||||
try {
|
||||
await store.finishDispatch(record.id, { status: 'failed', note: String(error?.message ?? error) })
|
||||
} catch { /* 记账失败不影响调用 */ }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
if (record) {
|
||||
try {
|
||||
await settle({ ctx, store, dsbot, project, record, action, result, before, roomId })
|
||||
} catch { /* 记账失败不影响调用 */ }
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
async function settle({ ctx, store, dsbot, project, record, action, result, before, roomId }) {
|
||||
const failed = isToolError(result)
|
||||
const after = dsbot.roomOf(roomId)?.goal
|
||||
const revisionAfter = after?.revision ?? null
|
||||
await store.finishDispatch(record.id, {
|
||||
status: failed ? 'failed' : 'confirmed',
|
||||
revisionAfter,
|
||||
note: failed ? '原生调用返回失败。' : null,
|
||||
})
|
||||
await store.addEvent({
|
||||
kind: 'dispatch',
|
||||
projectId: project.id,
|
||||
summary: describeDispatch({ ...record, status: failed ? 'failed' : 'confirmed' }),
|
||||
action,
|
||||
})
|
||||
if (failed || action !== 'rework') return
|
||||
|
||||
const detected = detectRework({ before, after, reason: record.reason })
|
||||
if (!detected) return
|
||||
const budget = budgetOf(after, project)
|
||||
const rework = {
|
||||
id: newId('rwk'),
|
||||
projectId: project.id,
|
||||
goalId: after.id,
|
||||
stageIndex: detected.stageNo,
|
||||
stageTitle: detected.stageTitle,
|
||||
reason: detected.reason,
|
||||
goalRevision: revisionAfter,
|
||||
revisionAfter,
|
||||
budgetUsed: budget.used,
|
||||
budgetMax: budget.max,
|
||||
at: Date.now(),
|
||||
}
|
||||
const added = await store.addRework(rework)
|
||||
if (added.duplicate) return
|
||||
|
||||
if (project.autoRework === false) return
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
if (!rt || typeof rt.deliver !== 'function') return
|
||||
const room = dsbot.roomOf(roomId)
|
||||
const sessionId = room?.sessions?.[project.bots?.gongbu]
|
||||
const text = [
|
||||
`阶段 ${detected.stageNo}「${detected.stageTitle}」被驳回,请返工。`,
|
||||
detected.reason === '' ? '' : `驳回原因:${detected.reason}`,
|
||||
`这是第 ${budget.used}/${budget.max} 轮返工;完成后在群里 @尚书 回报,附改动与测试证据。`,
|
||||
].filter(line => line !== '').join('\n')
|
||||
try {
|
||||
await rt.deliver({
|
||||
fromId: project.bots.shangshu,
|
||||
toId: project.bots.gongbu,
|
||||
sessionId,
|
||||
roomId,
|
||||
text,
|
||||
role: 'request',
|
||||
note: '返工派单',
|
||||
})
|
||||
await store.finishDispatch(record.id, { autoRework: 'delivered' })
|
||||
} catch (error) {
|
||||
await store.finishDispatch(record.id, { autoRework: `failed: ${String(error?.message ?? error)}` })
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { budgetOf } from './gate.js'
|
||||
|
||||
const MUTATIONS = new Set(['draft', 'start', 'revise', 'task', 'pass', 'rework', 'complete', 'pause', 'resume', 'stop'])
|
||||
|
||||
export function isGoalMutation(action) {
|
||||
return MUTATIONS.has(String(action ?? ''))
|
||||
}
|
||||
|
||||
export function newId(prefix) {
|
||||
return `${prefix}-${randomUUID().replace(/-/g, '').slice(0, 8)}`
|
||||
}
|
||||
|
||||
/** 一次宿主启动的标识:派发记录带上它,重启后就能分辨「本次启动的」与「上次遗留的」。 */
|
||||
export function newBootId() {
|
||||
return `boot-${Date.now().toString(36)}-${randomUUID().replace(/-/g, '').slice(0, 6)}`
|
||||
}
|
||||
|
||||
/** 工具结果里的失败标记;不同版本可能用 isError 或 error 字段。 */
|
||||
export function isToolError(result) {
|
||||
if (result === undefined || result === null) return false
|
||||
if (result.isError === true || result.error !== undefined) return true
|
||||
const content = Array.isArray(result.content) ? result.content : []
|
||||
return content.some(part => part?.type === 'text' && String(part.text ?? '').startsWith('Error:'))
|
||||
}
|
||||
|
||||
function stageIndexOf(stageList, predicate) {
|
||||
const index = stageList.findIndex(predicate)
|
||||
return index === -1 ? undefined : index
|
||||
}
|
||||
|
||||
/**
|
||||
* 从目标前后快照里认出这次 rework 落在哪个阶段、预算用到第几轮。
|
||||
* 纯函数,便于单测;找不到增量时返回 undefined(例如调用被上游拒绝)。
|
||||
*/
|
||||
export function detectRework({ before, after, reason }) {
|
||||
if (!after || !before || after.id !== before.id) return undefined
|
||||
if ((after.revision ?? 0) <= (before.revision ?? 0)) return undefined
|
||||
const afterStages = after.stages ?? []
|
||||
const beforeStages = before.stages ?? []
|
||||
const stageIndex = stageIndexOf(afterStages, (stage, index) => {
|
||||
const old = beforeStages[index]
|
||||
return (Number(stage.reworks) || 0) > (Number(old?.reworks) || 0)
|
||||
})
|
||||
if (stageIndex === undefined) return undefined
|
||||
const stage = afterStages[stageIndex]
|
||||
return {
|
||||
stageIndex,
|
||||
stageNo: stageIndex + 1,
|
||||
stageTitle: stage.title,
|
||||
reason: String(reason ?? '').trim() || String(stage.feedback ?? '').trim(),
|
||||
reworksInStage: Number(stage.reworks) || 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** 派发记录前缀(状态展示用)。 */
|
||||
export function describeDispatch(record) {
|
||||
const status = {
|
||||
intent: '进行中',
|
||||
confirmed: '已确认',
|
||||
failed: '未执行',
|
||||
unknown: '待核实',
|
||||
}[record.status] ?? record.status
|
||||
const stage = Number.isInteger(record.stageIndex) ? ` 阶段${record.stageIndex}` : ''
|
||||
return `${record.id} ${record.action}${stage} → ${status}`
|
||||
}
|
||||
|
||||
export function budgetAfter(goal, project) {
|
||||
return budgetOf(goal, project)
|
||||
}
|
||||
|
|
@ -2,11 +2,14 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|||
import { dirname } from 'node:path'
|
||||
import { ROLE_IDS } from './roles.js'
|
||||
|
||||
const VERSION = 1
|
||||
const VERSION = 2
|
||||
export const REVIEW_LIMIT = 400
|
||||
export const DISPATCH_LIMIT = 600
|
||||
export const REWORK_LIMIT = 200
|
||||
export const EVENT_LIMIT = 300
|
||||
|
||||
export function emptyState() {
|
||||
return { version: VERSION, projects: {}, reviews: [] }
|
||||
return { version: VERSION, projects: {}, reviews: [], dispatches: [], reworks: [], events: [] }
|
||||
}
|
||||
|
||||
function normalize(raw) {
|
||||
|
|
@ -15,6 +18,9 @@ function normalize(raw) {
|
|||
version: VERSION,
|
||||
projects: state.projects !== null && typeof state.projects === 'object' ? state.projects : {},
|
||||
reviews: Array.isArray(state.reviews) ? state.reviews : [],
|
||||
dispatches: Array.isArray(state.dispatches) ? state.dispatches : [],
|
||||
reworks: Array.isArray(state.reworks) ? state.reworks : [],
|
||||
events: Array.isArray(state.events) ? state.events : [],
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -35,7 +41,8 @@ async function writeJsonAtomic(file, value) {
|
|||
}
|
||||
|
||||
/**
|
||||
* 三省六部的补充记录:项目绑定(ProjectBinding)与审查记录(ReviewRecord)。
|
||||
* 三省六部的补充记录:项目绑定(ProjectBinding)、审查记录(ReviewRecord)、
|
||||
* 派发记录(DispatchRecord)、返工记录(ReworkRecord)与审计事件。
|
||||
* 原生 group_goal 仍是阶段进度的唯一权威;这里只存它没有的东西。
|
||||
* 写入串行化,内存状态先更新再落盘,同步的 tools.guard 立即可见。
|
||||
*/
|
||||
|
|
@ -75,6 +82,15 @@ export class SanshengStore {
|
|||
if (this.#state.reviews.length > REVIEW_LIMIT) {
|
||||
this.#state.reviews = this.#state.reviews.slice(-REVIEW_LIMIT)
|
||||
}
|
||||
if (this.#state.dispatches.length > DISPATCH_LIMIT) {
|
||||
this.#state.dispatches = this.#state.dispatches.slice(-DISPATCH_LIMIT)
|
||||
}
|
||||
if (this.#state.reworks.length > REWORK_LIMIT) {
|
||||
this.#state.reworks = this.#state.reworks.slice(-REWORK_LIMIT)
|
||||
}
|
||||
if (this.#state.events.length > EVENT_LIMIT) {
|
||||
this.#state.events = this.#state.events.slice(-EVENT_LIMIT)
|
||||
}
|
||||
await writeJsonAtomic(this.#file, this.#state)
|
||||
return result
|
||||
})
|
||||
|
|
@ -92,6 +108,10 @@ export class SanshengStore {
|
|||
return Object.values(this.#state.projects).find(project => ROLE_IDS.some(role => project.bots?.[role] === botId))
|
||||
}
|
||||
|
||||
projectById(id) {
|
||||
return id ? this.#state.projects[id] : undefined
|
||||
}
|
||||
|
||||
resolveProject(ref) {
|
||||
const key = String(ref ?? '').trim()
|
||||
if (key === '') return undefined
|
||||
|
|
@ -132,4 +152,90 @@ export class SanshengStore {
|
|||
.filter(item => Object.entries(match).every(([key, value]) => item[key] === value))
|
||||
.sort((a, b) => (b.at ?? 0) - (a.at ?? 0))
|
||||
}
|
||||
|
||||
/**
|
||||
* 派发意图:先落盘再调用原生工具。进程中途消失时它停在 intent,
|
||||
* 下次启动对账会把它标成 unknown(待核实),而不是假装成功或盲目重发。
|
||||
*/
|
||||
async beginDispatch(record) {
|
||||
return this.transact(state => {
|
||||
state.dispatches.push({ ...record, status: 'intent', at: record.at ?? Date.now() })
|
||||
return record
|
||||
})
|
||||
}
|
||||
|
||||
async finishDispatch(id, patch) {
|
||||
return this.transact(state => {
|
||||
const record = state.dispatches.find(item => item.id === id)
|
||||
if (!record) return undefined
|
||||
Object.assign(record, patch, { finishedAt: Date.now() })
|
||||
return record
|
||||
})
|
||||
}
|
||||
|
||||
/** 重启对账:仍在 intent 的派发视为「结果未知」,保留待人工/尚书核实。 */
|
||||
async reconcileDispatches(bootId) {
|
||||
return this.transact(state => {
|
||||
let marked = 0
|
||||
for (const record of state.dispatches) {
|
||||
if (record.status !== 'intent') continue
|
||||
record.status = 'unknown'
|
||||
record.note = '宿主在派发途中退出;结果未知,需核实后再决定是否重发。'
|
||||
record.reconciledBy = bootId
|
||||
record.reconciledAt = Date.now()
|
||||
marked += 1
|
||||
}
|
||||
return marked
|
||||
})
|
||||
}
|
||||
|
||||
/** 尚书/用户核实一条 unknown 派发:done=确实执行过,not-done=没执行。 */
|
||||
async resolveDispatch(id, verdict, by) {
|
||||
return this.transact(state => {
|
||||
const record = state.dispatches.find(item => item.id === id)
|
||||
if (!record) return undefined
|
||||
if (record.status !== 'unknown') return { record, changed: false }
|
||||
record.status = verdict === 'done' ? 'confirmed' : 'failed'
|
||||
record.resolvedBy = by
|
||||
record.resolvedAt = Date.now()
|
||||
record.note = verdict === 'done' ? '核实:原生操作已执行。' : '核实:原生操作没有执行。'
|
||||
return { record, changed: true }
|
||||
})
|
||||
}
|
||||
|
||||
async addRework(record) {
|
||||
return this.transact(state => {
|
||||
const key = `${record.goalId}:${record.revisionAfter}`
|
||||
const existing = state.reworks.find(item => item.key === key)
|
||||
if (existing) return { rework: existing, duplicate: true }
|
||||
state.reworks.push({ ...record, key })
|
||||
return { rework: record, duplicate: false }
|
||||
})
|
||||
}
|
||||
|
||||
async addEvent(entry) {
|
||||
return this.transact(state => {
|
||||
state.events.push({ ...entry, at: entry.at ?? Date.now() })
|
||||
return entry
|
||||
})
|
||||
}
|
||||
|
||||
dispatchesFor(projectId, limit = 10) {
|
||||
return this.#state.dispatches
|
||||
.filter(item => projectId === undefined || item.projectId === projectId)
|
||||
.slice(-limit)
|
||||
.reverse()
|
||||
}
|
||||
|
||||
unknownDispatches(projectId) {
|
||||
return this.#state.dispatches.filter(item =>
|
||||
item.status === 'unknown' && (projectId === undefined || item.projectId === projectId))
|
||||
}
|
||||
|
||||
reworksFor(projectId, limit = 10) {
|
||||
return this.#state.reworks
|
||||
.filter(item => projectId === undefined || item.projectId === projectId)
|
||||
.slice(-limit)
|
||||
.reverse()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
|
|||
import { goalDigest, sha256, stageDigest } from './digest.js'
|
||||
import { budgetOf } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import { describeDispatch } from './records.js'
|
||||
import { ROLE_COLOR, ROLE_IDS, ROLE_LABEL } from './roles.js'
|
||||
|
||||
const TEXT_OUTPUT = {
|
||||
|
|
@ -34,7 +35,8 @@ function clampInt(value, fallback, min, max) {
|
|||
}
|
||||
|
||||
function shortId(id) {
|
||||
return String(id ?? '').slice(0, 8)
|
||||
const text = String(id ?? '')
|
||||
return text.length <= 14 ? text : `…${text.slice(-12)}`
|
||||
}
|
||||
|
||||
function instructionsFor(role, project, groupName) {
|
||||
|
|
@ -52,7 +54,7 @@ function projectBots(dsbot, project) {
|
|||
return ROLE_IDS.map(role => ({ role, id: project.bots?.[role], bot: dsbot.botOf(project.bots?.[role]) }))
|
||||
}
|
||||
|
||||
function projectLines(dsbot, project) {
|
||||
function projectLines(dsbot, store, 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(',')
|
||||
|
|
@ -60,8 +62,17 @@ function projectLines(dsbot, project) {
|
|||
`项目「${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}`,
|
||||
` 模型:${ROLE_IDS.map(role => `${ROLE_LABEL[role]}=${project.models?.[role] ?? dsbot.botOf(project.bots?.[role])?.model ?? '默认'}`).join(',')} 返工预算:${project.maxReworks ?? 3}`,
|
||||
]
|
||||
const unknown = store.unknownDispatches(project.id)
|
||||
const recent = store.dispatchesFor(project.id, 3)
|
||||
if (recent.length > 0) {
|
||||
lines.push(` 派发:待核实 ${unknown.length} 条;最近 ${recent.map(item => describeDispatch(item)).join(';')}`)
|
||||
}
|
||||
const reworks = store.reworksFor(project.id, 3)
|
||||
if (reworks.length > 0) {
|
||||
lines.push(` 返工记录:${reworks.map(item => `阶段${item.stageIndex} ${item.reason ?? ''}(${item.budgetUsed}/${item.budgetMax})`).join(';')}`)
|
||||
}
|
||||
if (!goal) {
|
||||
lines.push(' 目标:还没有(尚书用 group_goal draft/start 起草)')
|
||||
return lines
|
||||
|
|
@ -242,7 +253,48 @@ function status({ store, dsbot, args }) {
|
|||
? '还没有绑定任何项目。用 sansheng_provision 创建(三 Bot + 项目群),或 sansheng_bind 绑定现有群。'
|
||||
: `找不到项目「${args.project}」。用 sansheng_status 不带参数列出全部。`
|
||||
}
|
||||
return projects.map(project => projectLines(dsbot, project).join('\n')).join('\n\n')
|
||||
const blocks = projects.map(project => projectLines(dsbot, store, project).join('\n'))
|
||||
const unknown = store.unknownDispatches(args.project === undefined ? undefined : projects[0]?.id)
|
||||
if (unknown.length > 0) {
|
||||
blocks.push(`有 ${unknown.length} 条派发待核实(宿主退出时没拿到回执):${unknown.slice(0, 5).map(item => item.id).join('、')}。用 sansheng_reconcile id=… verdict=done|not-done 核对。`)
|
||||
}
|
||||
return blocks.join('\n\n')
|
||||
}
|
||||
|
||||
async function reconcile({ store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
const project = args.project === undefined || String(args.project).trim() === ''
|
||||
? actor.project
|
||||
: store.resolveProject(args.project)
|
||||
const id = String(args.id ?? '').trim()
|
||||
if (id === '') {
|
||||
const list = store.unknownDispatches(project?.id)
|
||||
if (list.length === 0) return '没有待核实的派发记录。'
|
||||
return [
|
||||
`待核实的派发 ${list.length} 条(一律先核对原生目标状态,不要盲目重发):`,
|
||||
...list.map(item => `- ${item.id}:${item.action} 目标 ${item.goalId ?? '—'} 版本 ${item.goalRevision ?? '—'},${new Date(item.at).toLocaleString('zh-CN')} 发起,执行者 ${item.actorName ?? item.actorBotId ?? '—'}`),
|
||||
'用 sansheng_reconcile id=<记录> verdict=done|not-done 标记核实结果。',
|
||||
].join('\n')
|
||||
}
|
||||
const record = store.peek().dispatches.find(item => item.id === id)
|
||||
if (!record) return `找不到派发记录 ${id}。`
|
||||
if (actor.kind === 'bot') {
|
||||
if (!actor.project || actor.project.id !== record.projectId) {
|
||||
return `派发 ${id} 属于其他项目,本项目的 Bot 不能核实。`
|
||||
}
|
||||
if (actor.role !== 'shangshu') {
|
||||
return `只有本项目的尚书能核实派发记录;当前是${actor.role ? ROLE_LABEL[actor.role] : '非项目成员'}。`
|
||||
}
|
||||
}
|
||||
const verdict = String(args.verdict ?? '').trim()
|
||||
if (verdict !== 'done' && verdict !== 'not-done') return 'verdict 必须是 done(确实执行过)或 not-done(没有执行)。'
|
||||
const result = await store.resolveDispatch(id, verdict, actor.botId ?? 'user')
|
||||
if (!result) return `找不到派发记录 ${id}。`
|
||||
if (!result.changed) return `派发 ${id} 当前是 ${result.record.status},不需要核实。`
|
||||
await store.addEvent({ kind: 'reconcile', projectId: record.projectId, summary: `${id} → ${verdict}`, action: record.action })
|
||||
return verdict === 'done'
|
||||
? `已核实 ${id}:原生操作确实执行过,记录改为已确认。`
|
||||
: `已核实 ${id}:原生操作没有执行,记录改为未执行;需要时再重新发起。`
|
||||
}
|
||||
|
||||
async function review({ store, dsbot, args, exec }) {
|
||||
|
|
@ -428,6 +480,19 @@ export function installTools({ ctx, store, dsbot }) {
|
|||
},
|
||||
},
|
||||
(args, exec) => review({ store, dsbot, args, exec })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_reconcile',
|
||||
'核对重启前未拿到回执的派发记录:不带 id 列出待核实项;带 id 与 verdict 标记为已执行或未执行。核实前先看原生目标状态,不要盲目重发。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名或 id;省略则用当前项目。' },
|
||||
id: { type: 'string', description: '派发记录 id(dsp-…);省略则列出待核实项。' },
|
||||
verdict: { type: 'string', enum: ['done', 'not-done'], description: 'done=原生操作确实执行过;not-done=没有执行。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => reconcile({ store, dsbot, args, exec })),
|
||||
]
|
||||
return disposers
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,56 @@
|
|||
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 { apply, inject, name } from '../index.js'
|
||||
|
||||
function fakeCtx() {
|
||||
const tools = []
|
||||
const guards = []
|
||||
const handlers = {}
|
||||
return {
|
||||
tools: {
|
||||
register(def) { tools.push(def); return () => {} },
|
||||
guard(fn) { guards.push(fn); return () => {} },
|
||||
},
|
||||
on(event, handler) { handlers[event] = handler; return () => {} },
|
||||
get() { return undefined },
|
||||
toolsList: tools,
|
||||
guards,
|
||||
handlers,
|
||||
}
|
||||
}
|
||||
|
||||
test('插件导出与注入符合 DSH 约定', () => {
|
||||
assert.equal(name, 'sansheng')
|
||||
assert.deepEqual(inject, ['tools'])
|
||||
})
|
||||
|
||||
test('apply 注册全部工具、门禁与派发观测,并能读损坏的 DS Bot 状态文件', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-plugin-'))
|
||||
try {
|
||||
const dsbotState = join(dir, 'bot-state.json')
|
||||
await writeFile(dsbotState, '{ 不是 JSON', 'utf8')
|
||||
const ctx = fakeCtx()
|
||||
await apply(ctx, { statePath: join(dir, 'sansheng.json'), dsbotStatePath: dsbotState })
|
||||
|
||||
const names = ctx.toolsList.map(def => def.name).sort()
|
||||
assert.deepEqual(names, [
|
||||
'sansheng_bind', 'sansheng_provision', 'sansheng_reconcile', 'sansheng_review', 'sansheng_status',
|
||||
])
|
||||
assert.equal(ctx.guards.length, 1, '装了 group_goal 门禁')
|
||||
assert.equal(typeof ctx.handlers['tools/execute'], 'function', '装了派发观测')
|
||||
|
||||
const status = ctx.toolsList.find(def => def.name === 'sansheng_status')
|
||||
const text = await status.execute({}, { agent: { id: 'some-session' } })
|
||||
assert.match(text, /还没有绑定任何项目/)
|
||||
|
||||
for (const def of ctx.toolsList) {
|
||||
assert.equal(def.parameters.type, 'object', `${def.name} 的参数是 JSON Schema`)
|
||||
assert.equal(typeof def.output?.render, 'function', `${def.name} 有文本渲染`)
|
||||
}
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,234 @@
|
|||
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('派发记录:intent → 回执,失败记为未执行', 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, 'intent', '调用前先落意图')
|
||||
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, 'failed')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('重启对账:停在 intent 的派发标为待核实,核实后改状态且不重复', 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, 'failed')
|
||||
} 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')
|
||||
})
|
||||
Loading…
Reference in New Issue