Package-root snapshot for v1.1.4 (2499dc4)

This commit is contained in:
qyh15 2026-11-28 12:47:26 +08:00
parent fc414a542b
commit 87b6b88f3d
36 changed files with 4346 additions and 659 deletions

View File

@ -1,4 +1,4 @@
# 三省六部(dsh-sansheng)· v1.1.2
# 三省六部(dsh-sansheng)· v1.1.4
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。

1215
client.js

File diff suppressed because it is too large Load Diff

View File

@ -4,6 +4,7 @@ import { SanshengStore } from './src/host/store.js'
import { GlobalModelStore } from './src/host/global-store.js'
import { createModelSync } from './src/host/model-sync.js'
import { createSeatActivity } from './src/host/seat-activity.js'
import { installWorkflowBlockage } from './src/host/workflow-blockage.js'
import { createApprovalCenter } from './src/host/approval-center.js'
import { createLeadReporter } from './src/host/lead-reporter.js'
import { createSeatDelivery } from './src/host/seat-delivery.js'
@ -14,6 +15,9 @@ import { installPromptSection } from './src/host/prompt.js'
import { installSeatTools } from './src/host/tools.js'
import { createTurnCommands } from './src/host/message-source.js'
import { createLeadBackground } from './src/host/lead-background.js'
import { createLeadSecretaries } from './src/host/lead-secretaries.js'
import { createProvinceAgents } from './src/host/province-agents.js'
import { SEATS } from './src/shared/roles.js'
import { sanshengStatePath, sanshengGlobalSettingPath } from './src/host/paths.js'
import { ROUTE } from './src/host/constants.js'
@ -51,15 +55,39 @@ export function apply(ctx, config = {}) {
const found = store.seatBySession(sessionId)
return found ? { projectId: found.project.id, seatId: found.seatId } : null
},
// 有新的原生审批时,先把“谁申请、要做什么、原因”作为正式回报推给丞相;
// 丞相再用 sansheng_card 挂审批卡,用户点卡后仍回到这个原生请求。
onPending: entry => {
const label = SEATS[entry.seatId]?.label ?? entry.seatId
const summary = `待你审批:${label}申请${entry.tool ? '「' + entry.tool + '」' : '一次操作'}${entry.reason ? ',原因:' + entry.reason : ''}。审批编号:${entry.id}`
void leadReporter.record(entry.projectId, {
taskId: null,
transitionId: 'approval:' + entry.id,
event: 'approval_request',
stage: null,
ownerSeatId: entry.seatId,
summary,
textSnapshot: summary,
needsUserDecision: true,
sourceKind: 'sansheng-report',
}).then(() => leadReporter.flush(entry.projectId)).catch(error => {
console.warn('[sansheng] 审批待办回报失败:', error?.message ?? error)
})
},
})
const seatActivity = createSeatActivity({ store, host, approvalCenter })
const provisioner = createProvisioner({ store, host, modelSync })
const seatDelivery = createSeatDelivery({ host })
const service = new SanshengService({ store, host, provisioner, globalStore, modelSync, seatActivity, leadReporter, approvalCenter, seatDelivery })
const serviceRef = { service: null }
const leadSecretaries = createLeadSecretaries({ ctx, store })
const provinceAgents = createProvinceAgents({ ctx, store, serviceRef, host })
const service = new SanshengService({ store, host, provisioner, globalStore, modelSync, seatActivity, leadReporter, approvalCenter, seatDelivery, provinceAgents, leadSecretaries })
serviceRef.service = service
const handle = createApiHandler(service)
ctx.effect(() => seatActivity.install(ctx), 'sansheng: seat activity')
ctx.effect(() => approvalCenter.install(), 'sansheng: approval center')
ctx.effect(() => installWorkflowBlockage(ctx, { store, agents: host.agents }), 'sansheng: workflow blockage')
ctx.effect(() => {
const timer = setInterval(() => {
for (const project of store.list()) void leadReporter.flush(project.id).catch(error => console.warn('[sansheng] 回报发送失败:', error?.message ?? error))
@ -80,9 +108,11 @@ export function apply(ctx, config = {}) {
ctx.effect(() => installPromptSection(ctx, { store }), 'sansheng: prompt section')
const leadBackground = createLeadBackground({ ctx, store })
ctx.effect(() => leadBackground.install(), 'sansheng: lead background')
ctx.effect(() => leadSecretaries.install(), 'sansheng: lead secretaries')
ctx.effect(() => provinceAgents.install(), 'sansheng: province agents')
ctx.effect(() => {
const turnCommands = createTurnCommands(ctx, store)
const disposeTools = installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground })
const disposeTools = installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground, leadSecretaries, provinceAgents })
return () => { disposeTools(); turnCommands.dispose() }
}, 'sansheng: seat tools')

View File

@ -1,6 +1,6 @@
{
"name": "dsh-sansheng-liubu",
"version": "1.1.2",
"version": "1.1.4",
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
"keywords": [
"dsh-plugin",

View File

@ -8,6 +8,7 @@ import { WorkbenchV2 } from './workbench-v2.js'
import { workspaceForSession, workspaceItemsFromSnapshot, sessionSummaryFromSnapshot } from './workspace.js'
import { request } from './transport.js'
import { CSS as WORKBENCH_CSS } from './styles.js'
import { SanshengCardRow } from './cards.js'
import { install as installNativePanel } from '../native/index.js'
export const inject = ['sessions', 'workspaces', 'uiWorkspace', 'uiConversation', 'slots', 'theme', 'layout', 'sidebarRightTabs', 'sidebarRight']
@ -110,6 +111,9 @@ export function apply(ctx) {
const get = (name) => { try { return ctx.get(name) } catch { return undefined } }
// 子插件(sansheng-better-sidebar)挂进来的右栏打开方法;为空时走宿主原生右栏。
let rightTabOpener = null
// ---------- 当前项目 / 工作区(特性探测,拿不到就提示用户先选项目) ----------
function sessionsSnapshot() {
return snapshotOf(get('sessions')?.list) ?? snapshotOf(get('sessions'))
@ -358,26 +362,27 @@ export function apply(ctx) {
const targetSessionId = (typeof sessionId === 'string' && sessionId) ? sessionId : rightMountedSessionId()
const existing = findRightWorkbenchTab(targetSessionId)
if (existing) return revealRightTab(targetSessionId)
// 桌面版右栏由 dsh-better-sidebar 接管:它自己的 openTab 会排队等待会话面板挂载,
// 主区正被切走时也不会丢;直接调宿主 sidebarRight 反而会因“没有挂载的会话面板”失败。
// 显式传 scope:新会话刚建立时 bs 的 active snapshot 可能还停在旧会话,不能靠猜。
const bs = get('betterSidebar')
if (bs && isFn(bs.openTab)) {
// 右栏增强交给并行的子插件:它注册 Better Sidebar 标签后,把打开方法挂回这里。
// 只要子插件在,打开失败就交回调用方走浮层/内嵌,不再注册原生类型,避免和 Better Sidebar 的 kind 冲突。
if (isFn(rightTabOpener)) {
try {
if (!targetSessionId) return false
const summary = sessionSummary(targetSessionId)
const scope = { sessionId: targetSessionId }
if (summary && typeof summary.cwd === 'string' && summary.cwd) scope.cwd = summary.cwd
bs.openTab({ type: TAB_KIND, title: '三省六部' }, scope)
scheduleRevealRightTab(targetSessionId)
return true
if (rightTabOpener(targetSessionId)) {
scheduleRevealRightTab(targetSessionId)
return true
}
} catch (error) {
console.warn('[sansheng] better-sidebar 打开失败,改用宿主接口:', error && error.message ? error.message : error)
console.warn('[sansheng] 子插件打开右栏失败:', error && error.message ? error.message : error)
}
return false
}
const right = get('sidebarRight')
if (!right || !isFn(right.openTab)) return false
if (!ensureRightTab()) return false
if (!ensureRightTab()) {
// 原生回退按需注册:有子插件时它已在 apply 时接管,这里不会注册;
// 没有子插件时第一次点导航再把原生类型和两个槽位挂上,避免和 Better Sidebar 的 kind 冲突。
registerRightTabType()
if (!ensureRightTab()) return false
}
try {
// 原生接口的 openTab 只能作用于 on-screen 会话;目标会话尚未 adopt 时,
// 如果宿主暴露了 openTabIn(跨会话目标通道)就用它,否则退回 openTab 并靠退避重试。
@ -394,72 +399,83 @@ export function apply(ctx) {
}
function SanshengTabBody(props) {
const sessionId = props && props.sessionId
return h('div', { className: 'ssw-tab-body', 'data-session-id': sessionId || undefined }, h(SanshengWorkbench, { sessionId }))
return h('div', {
className: 'ssw-tab-body',
'data-session-id': sessionId || undefined,
'data-sansheng-right-tab': 'native',
}, h(SanshengWorkbench, { sessionId }))
}
function SanshengTabTitle() {
return h('span', { className: 'ssw-tab-title' }, '三省六部')
}
// 宿主按 definition.id 选 slot(TabSlot: entryKey=definition.id),因此 slot key 必须等于类型 id。
function registerRightTabType() {
// 桌面版:向 better-sidebar 注册一个原生右侧标签(它自己负责正文/标题与落位)。
try {
const bs = get('betterSidebar')
if (bs && isFn(bs.registerTab)) {
const dispose = bs.registerTab({
id: TAB_KIND,
title: '三省六部',
description: '十席角色与独立会话的当前项目工作台',
icon: (size) => h(TreeIcon, { width: size, height: size }),
order: 32,
single: true,
component: (tabProps) => {
const scope = tabProps && tabProps.scope ? tabProps.scope : null
const sessionId = scope && scope.sessionId
return h('div', { className: 'ssw-tab-body', 'data-session-id': sessionId || undefined }, h(SanshengWorkbench, { sessionId }))
},
})
return () => { try { if (isFn(dispose)) dispose() } catch { /* 忽略 */ } }
}
} catch (error) {
console.warn('[sansheng] 注册 better-sidebar 标签失败:', error && error.message ? error.message : error)
// 原生右栏是主插件自带的回退;子插件接管时先 release,失败或卸载时 restore。
let nativeRightTabWanted = true
let nativeRightTabStop = null
function uninstallNativeRightTab() {
const stop = nativeRightTabStop
nativeRightTabStop = null
if (isFn(stop)) {
try { stop() } catch { /* 忽略 */ }
}
}
function registerRightTabType() {
if (!nativeRightTabWanted || nativeRightTabStop || isFn(rightTabOpener)) return
if (!isFn(ctx.inject)) return
try {
if (!isFn(ctx.inject)) return
ctx.inject(['sidebarRightTabs'], (injected) => {
nativeRightTabStop = ctx.inject(['sidebarRightTabs'], (injected) => {
if (!nativeRightTabWanted || isFn(rightTabOpener)) return
const tabs = injected.get('sidebarRightTabs')
if (!tabs || !isFn(tabs.register)) return
let disposeType = null, disposeBody = null, disposeTitle = null
try {
disposeType = tabs.register({
id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部',
guide: [{
id: `${TAB_TYPE_ID}:guide`, order: 32, title: () => '三省六部',
description: () => '十席角色与独立会话的当前项目工作台', icon: TreeIcon,
}],
})
disposeBody = ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
name: 'sidebar.right.pane.tab', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
}, SanshengTabBody))
disposeTitle = ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
name: 'sidebar.right.pane.tab.title', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
}, SanshengTabTitle))
} catch (error) {
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
try { disposeType && disposeType() } catch { /* 忽略 */ }
return
}
return () => {
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
try { disposeType && disposeType() } catch { /* 忽略 */ }
}
injected.effect(() => {
let disposeType = null, disposeBody = null, disposeTitle = null
const cleanup = () => {
try { disposeBody && disposeBody() } catch { /* 忽略 */ }
try { disposeTitle && disposeTitle() } catch { /* 忽略 */ }
try { disposeType && disposeType() } catch { /* 忽略 */ }
}
try {
disposeType = tabs.register({
id: TAB_TYPE_ID, kind: TAB_KIND, keepMounted: true, priority: 'extension', title: () => '三省六部',
guide: [{
id: `${TAB_TYPE_ID}:guide`, order: 32, title: () => '三省六部',
description: () => '十席角色与独立会话的当前项目工作台', icon: TreeIcon,
}],
})
// 正文和标题槽位要在类型注册后再注入:sidebar.right.pane.tab 是随类型声明的子槽位。
disposeBody = ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
name: 'sidebar.right.pane.tab', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
}, SanshengTabBody))
disposeTitle = ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
name: 'sidebar.right.pane.tab.title', key: TAB_TYPE_ID, inject: (sessionId) => ({ sessionId }),
}, SanshengTabTitle))
} catch (error) {
const message = error && error.message ? error.message : error
if (!/inactive context/.test(String(message))) {
console.warn('[sansheng] 注册右侧标签失败:', message)
}
cleanup()
return undefined
}
return cleanup
}, 'sansheng: native right tab fallback')
})
} catch (error) {
console.warn('[sansheng] 注册右侧标签失败:', error && error.message ? error.message : error)
nativeRightTabStop = null
const message = error && error.message ? error.message : error
if (!/inactive context/.test(String(message))) {
console.warn('[sansheng] 注册右侧标签失败:', message)
}
}
}
function releaseNativeRightTab() {
nativeRightTabWanted = false
uninstallNativeRightTab()
}
function restoreNativeRightTab() {
nativeRightTabWanted = true
registerRightTabType()
}
// 工作台会随宿主会话切换而重挂载;按项目记住选中的部门,避免又跳回丞相。
const selectedSeatCache = new Map()
@ -483,6 +499,26 @@ export function apply(ctx) {
})
}
// 并行子插件 sansheng-better-sidebar 通过这个服务拿工作台和右栏接管口。
// 主插件仍是工作台正文、导航和宿主原生右栏回退的所有者;子插件只负责 Better Sidebar 注册。
const workbenchService = {
version: 1,
Workbench: SanshengWorkbench,
tabKind: TAB_KIND,
tabTypeId: TAB_TYPE_ID,
title: '三省六部',
description: '十席角色与独立会话的当前项目工作台',
icon: (size) => h(TreeIcon, { width: size, height: size }),
sessionSummary,
attachRightTabOpener(fn) {
rightTabOpener = isFn(fn) ? fn : null
return () => { if (rightTabOpener === fn) rightTabOpener = null }
},
releaseNativeRightTab,
restoreNativeRightTab,
}
ctx.provide('sanshengWorkbench', workbenchService)
// ---------- 左侧导航入口 ----------
// 宿主正式扩展点是 sidebar.panellist:一行导航 + 一个同名 keyed main 页(插件/任务看板/记忆系统同机制)。
// 位置钉在记忆系统(order 30)与技能管理(31)之后、宿主「更多」之前。
@ -519,7 +555,7 @@ export function apply(ctx) {
function installRightDockPinning() {
const right = get('sidebarRight')
if (!right || !isFn(right.mounted?.subscribe)) return
const delays = [60, 140, 280, 560, 1000, 1800, 3000]
const delays = [400, 800, 1200, 1800, 2600, 3600, 5000]
let timer = null
let attempt = 0
const clear = () => {
@ -611,9 +647,7 @@ export function apply(ctx) {
}
function SanshengNavFallback() {
// 点击左侧「三省六部」整行时,优先把工作台停靠到右侧;打不开就在主区内嵌显示。
// 关键:openRightWorkbench 必须在组件仍挂载时同步尝试。旧逻辑先 backToChat,
// 组件随即卸载,定时器里的 setMode('inline') 落在已卸载实例上,主区就永远空白。
const hasBetterSidebar = !!get('betterSidebar')
// openRightWorkbench 必须在组件仍挂载时同步尝试,避免切走主区后定时器落在卸载实例上。
const [mode, setMode] = useState('pending')
useEffect(() => {
let opened = false
@ -623,20 +657,7 @@ export function apply(ctx) {
backToChat()
return undefined
}
if (!hasBetterSidebar) {
setMode('inline')
return undefined
}
// 桌面右栏宿主:先切回会话,再等会话重新挂载后重试打开右栏。
// 这些定时器不随本组件卸载取消,否则切回会话就把自己“清理”掉了。
backToChat()
let openedLater = false
for (const delay of [200, 600, 1200, 2000]) {
setTimeout(() => {
try { if (!openedLater && openRightWorkbench(currentSessionId())) { openedLater = true; backToChat() } } catch { /* 忽略 */ }
}, delay)
}
setTimeout(() => { if (!openedLater) setMode('inline') }, 2600)
setMode('inline')
return undefined
}, [])
useEffect(() => {
@ -682,11 +703,27 @@ export function apply(ctx) {
}
}
// 丞相会话里的卡片行:宿主公开的按工具名分发 slot,不需要自定义 session 事件。
function registerCardToolview() {
if (!ctx.slots || !isFn(ctx.slots.inject) || !isFn(ctx.slots.register)) return
try {
ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
name: 'tool.call.toolview',
key: 'sansheng_card',
}, SanshengCardRow))
} catch (error) {
console.warn('[sansheng] 注册卡片视图失败:', error && error.message ? error.message : error)
}
}
// 左侧导航行(宿主正式槽位,位置在记忆系统之后、更多之前)。
registerNavEntry()
registerCardToolview()
// 右侧工作台标签类型:需在 apply 时就注册(宿主按类型 id 选正文 slot)。
registerRightTabType()
// 原生右栏先等一个短窗口:若并行子插件已接管,rightTabOpener 会在 apply 时挂上,这里就跳过;
// 没有子插件时才注册原生类型,保证只装主插件时首次点击即可打开。
const nativeRightTabTimer = setTimeout(() => { try { registerRightTabType() } catch { /* 忽略 */ } }, 500)
if (isFn(ctx.effect)) ctx.effect(() => () => clearTimeout(nativeRightTabTimer), 'sansheng: native right tab timer')
installRightDockPinning()
// dsh-go 原生面板:浏览器(无 dshGo 服务)或桥未就绪时,install 内部安静退出。

View File

@ -90,7 +90,7 @@ function refreshList(value, previous, projectChanged = false) {
if (Array.isArray(value)) return value
return projectChanged ? [] : previous
}
const DELIVERY_LABELS = { pending: '待发送', sending: '发送中', unknown: '结果未知', accepted: '已接收', failed: '投递失败' }
const DELIVERY_LABELS = { pending: '待发送', sending: '发送中', unknown: '结果未知', accepted: '已接收' }
function deliveryLabel(state) { return DELIVERY_LABELS[state] || '' }
function pad2(n) { return String(n).padStart(2, '0') }
@ -243,9 +243,62 @@ function fmtModel(rec, options) {
return described.modelLabel
}
const DELIB_SEATS = ['zhongshu', 'menxia', 'shangshu']
const AVATAR_MIME = ['image/png', 'image/jpeg', 'image/webp']
const AVATAR_MAX_BYTES = 120 * 1024
function seatTone(seatId) {
return seatId === 'zhongshu' ? '#4c6ef5' : seatId === 'menxia' ? '#12b886' : seatId === 'shangshu' ? '#e8590c' : '#868e96'
}
// 默认头像用席位名的第一个字;自定义字符或缩放后的图片优先。
function avatarNode(seatId, avatars, size = 34, highlight = false) {
const custom = avatars?.[seatId]
const ring = highlight ? { boxShadow: '0 0 0 2px ' + seatTone(seatId), borderRadius: '50%' } : {}
if (custom?.type === 'image') {
return h('img', {
src: custom.dataUrl, alt: (SEATS[seatId]?.name ?? seatId) + '头像', width: size, height: size,
style: { width: size, height: size, borderRadius: '50%', objectFit: 'cover', flex: '0 0 auto', ...ring },
})
}
const text = custom?.type === 'char' ? custom.char : (SEATS[seatId]?.name ?? seatId).slice(0, 1)
return h('span', {
'aria-hidden': 'true',
style: {
width: size, height: size, borderRadius: '50%', background: seatTone(seatId), color: '#fff',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto',
fontSize: Math.max(12, Math.round(size * 0.42)), fontWeight: 600, ...ring,
},
}, text)
}
// 上传图先缩到 256×256 再入库;循环降质量保证 ≤120KB,绝不上传原图。
async function shrinkAvatar(file) {
if (!file || !AVATAR_MIME.includes(file.type)) throw new Error('头像只支持 PNG、JPEG 或 WebP 图片')
const bitmap = await createImageBitmap(file)
try {
const side = 256
const canvas = document.createElement('canvas')
canvas.width = side; canvas.height = side
const ctx2d = canvas.getContext('2d')
const scale = Math.max(side / bitmap.width, side / bitmap.height)
const width = Math.max(1, Math.round(bitmap.width * scale))
const height = Math.max(1, Math.round(bitmap.height * scale))
ctx2d.drawImage(bitmap, Math.round((side - width) / 2), Math.round((side - height) / 2), width, height)
for (const quality of [0.9, 0.8, 0.7, 0.6, 0.5]) {
const dataUrl = canvas.toDataURL('image/jpeg', quality)
if (Math.floor((dataUrl.length - dataUrl.indexOf(',') - 1) * 3 / 4) <= AVATAR_MAX_BYTES) return dataUrl
}
throw new Error('图片压缩后仍超过 120KB,请换一张更简单的图片')
} finally {
bitmap.close?.()
}
}
export function WorkbenchV2(props) {
const {
onClose,
sessionId,
resolveWorkspace,
navigateToSession,
openRightTab,
@ -281,6 +334,16 @@ export function WorkbenchV2(props) {
const [approvals, setApprovals] = useState([])
const [pendingApprovals, setPendingApprovals] = useState([])
const [approvalStatus, setApprovalStatus] = useState(null)
const [deliberations, setDeliberations] = useState([])
const [deliberation, setDeliberation] = useState(null)
const [delibSelectedId, setDelibSelectedId] = useState(null)
const [delibDraft, setDelibDraft] = useState({ topic: '', taskId: '', requirementId: '', maxRounds: '3' })
const [delibEndNote, setDelibEndNote] = useState('')
const [delibBusy, setDelibBusy] = useState(false)
const [page, setPage] = useState('overview')
const [delibSettingsOpen, setDelibSettingsOpen] = useState(false)
const [avatarEdit, setAvatarEdit] = useState(null)
const [agentRuns, setAgentRuns] = useState([])
const [reqView, setReqView] = useState('requirements')
const [artifacts, setArtifacts] = useState([])
const [artifactDraft, setArtifactDraft] = useState({ title: '', path: '', summary: '' })
@ -322,7 +385,12 @@ export function WorkbenchV2(props) {
loadedProjectId.current = nextProjectId
setView(projectView); setModels(modelCatalog); setMemory(memoryData)
setMemoryDraft({ goal: memoryData?.goal ?? '', constraints: (memoryData?.constraints ?? []).join('\n'), acceptance: (memoryData?.acceptance ?? []).join('\n'), decisions: '' })
if (projectChanged) setSelectedTask(null)
if (projectChanged) {
setSelectedTask(null)
setDelibSelectedId(null)
setDeliberation(null)
setDeliberations([])
}
if (projectChanged || taskAnswerVersion.current === answerVersion) setTasks(previous => refreshList(taskRes.value?.tasks, previous, projectChanged))
setArtifacts(previous => refreshList(artifactRes.value?.artifacts, previous, projectChanged))
setRequirements(previous => refreshList(requirementData.value?.requirements, previous, projectChanged))
@ -384,6 +452,155 @@ export function WorkbenchV2(props) {
}
}, [projectId])
async function refreshDeliberations() {
if (!projectId) return
const [data, agentsData] = await Promise.allSettled([
request('deliberations', { projectId }),
request('agents', { projectId }),
])
if (!alive.current || loadedProjectId.current !== projectId) return
if (agentsData.status === 'fulfilled') setAgentRuns(Array.isArray(agentsData.value?.runs) ? agentsData.value.runs : [])
const list = Array.isArray(data.value?.deliberations) ? data.value.deliberations : []
setDeliberations(list)
const target = delibSelectedId || list.find(item => item.status === 'running')?.id || list[0]?.id || null
if (!target) { setDeliberation(null); return }
const full = await request('deliberation', { projectId, deliberationId: target })
if (!alive.current || loadedProjectId.current !== projectId) return
setDeliberation(full?.deliberation ?? null)
}
useEffect(() => {
if (page !== 'deliberations' || !projectId) return undefined
let disposed = false
let running = false
let timer = null
const tick = async () => {
if (disposed || running) return
running = true
try { await refreshDeliberations() } catch (error) {
if (!disposed && alive.current) console.warn('[sansheng] 议政刷新失败:', error?.message ?? error)
} finally { running = false }
}
timer = setInterval(tick, 1500)
void tick()
return () => { disposed = true; if (timer !== null) clearInterval(timer) }
}, [page, projectId, delibSelectedId])
async function startDeliberation() {
if (!projectId || delibBusy) return
const topic = String(delibDraft.topic || '').trim()
if (!topic) { setError('请先填写议政议题'); return }
setDelibBusy(true); setError(null)
try {
const maxRounds = delibDraft.maxRounds === '' ? 3 : Number(delibDraft.maxRounds)
const data = await request('deliberationStart', {
projectId,
topic,
taskId: delibDraft.taskId || undefined,
requirementId: delibDraft.requirementId || undefined,
maxRounds,
originSessionId: sessionId || undefined,
})
if (!alive.current || loadedProjectId.current !== projectId) return
setDelibSelectedId(data.deliberation.id)
setDeliberation(data.deliberation)
setDelibDraft(previous => ({ ...previous, topic: '' }))
setNotice(data.receipt?.text || '议政已发起,已叫中书。')
} catch (error) {
if (alive.current) setError(error && error.message ? error.message : '议政发起失败')
} finally { if (alive.current) setDelibBusy(false) }
}
async function endDeliberation() {
const deliberationId = delibSelectedId || deliberations.find(item => item.status === 'running')?.id
if (!projectId || !deliberationId || delibBusy) return
setDelibBusy(true); setError(null)
try {
await request('deliberationEnd', { projectId, deliberationId, note: delibEndNote.trim() || undefined })
if (!alive.current || loadedProjectId.current !== projectId) return
setDelibEndNote('')
setNotice('议政已结束,结论已记录。')
await refreshDeliberations()
} catch (error) {
if (alive.current) setError(error && error.message ? error.message : '结束议政失败')
} finally { if (alive.current) setDelibBusy(false) }
}
async function stopDeliberation() {
const deliberationId = delibSelectedId || deliberations.find(item => item.status === 'running')?.id
if (!projectId || !deliberationId || delibBusy) return
setDelibBusy(true); setError(null)
try {
const data = await request('deliberationStop', { projectId, deliberationId, note: delibEndNote.trim() || undefined })
if (!alive.current || loadedProjectId.current !== projectId) return
setDelibEndNote('')
setNotice(data.receipt?.text || '议政已停止。')
setDeliberation(data.deliberation)
await refreshDeliberations()
} catch (error) {
if (alive.current) setError(error && error.message ? error.message : '停止议政失败')
} finally { if (alive.current) setDelibBusy(false) }
}
async function retryDeliberation() {
const deliberationId = delibSelectedId || deliberations.find(item => item.status === 'running')?.id
if (!projectId || !deliberationId || delibBusy) return
setDelibBusy(true); setError(null)
try {
const data = await request('deliberationRetry', { projectId, deliberationId })
if (!alive.current || loadedProjectId.current !== projectId) return
setDeliberation(data.deliberation)
setNotice(data.delivery?.ok ? '已重试当前席位。' : '重试没有成功,页面会保留当前状态。')
await refreshDeliberations()
} catch (error) {
if (alive.current) setError(error && error.message ? error.message : '重试议政失败')
} finally { if (alive.current) setDelibBusy(false) }
}
async function saveAvatar(seatId, payload = {}) {
if (!projectId) return
setDelibBusy(true); setError(null)
try {
const data = payload.clear
? await request('clearAvatar', { projectId, seatId })
: await request('setAvatar', { projectId, seatId, ...payload })
if (!alive.current || loadedProjectId.current !== projectId) return
setView(previous => {
if (!previous?.project) return previous
const avatars = { ...(previous.project.avatars ?? {}) }
if (data.avatar) avatars[seatId] = data.avatar
else delete avatars[seatId]
return { ...previous, project: { ...previous.project, avatars } }
})
setAvatarEdit(null)
setNotice(data.avatar ? '头像已更新。' : '头像已恢复默认。')
} catch (error) {
if (alive.current) setError(error && error.message ? error.message : '保存头像失败')
} finally { if (alive.current) setDelibBusy(false) }
}
async function pickAvatarFile(seatId, file) {
try {
const dataUrl = await shrinkAvatar(file)
await saveAvatar(seatId, { dataUrl })
} catch (error) {
if (alive.current) setError(error && error.message ? error.message : '图片处理失败')
}
}
async function stopAgentRun(run) {
if (!projectId || delibBusy) return
setDelibBusy(true); setError(null)
try {
await request('agentStop', { projectId, runId: run.id, kind: run.kind })
if (!alive.current || loadedProjectId.current !== projectId) return
setNotice('已停止「' + (run.label || run.seatId || '后台子 Agent') + '」,不会再产生新动作。')
await refreshDeliberations()
} catch (error) {
if (alive.current) setError(error && error.message ? error.message : '停止失败')
} finally { if (alive.current) setDelibBusy(false) }
}
useEffect(() => {
if (!projectId || !selectionCache) return
const saved = selectionCache.get(projectId)
@ -636,7 +853,7 @@ export function WorkbenchV2(props) {
const todayTasks = tasks.filter(task => Number(task.createdAt) >= todayStart)
const todayDone = todayTasks.filter(task => task.status === 'done')
const reviewTasks = tasks.filter(task => task.ownerSeatId === 'menxia' && OPEN_STATUS.has(task.status))
const anomalyTasks = tasks.filter(task => task.status === 'failed' || task.deliveryState === 'failed')
const anomalyTasks = tasks.filter(task => task.workflowBlockage || task.status === 'failed')
const projectDurationMs = tasks.reduce((sum, task) => sum + taskDurationMs(task), 0)
function latestTaskOf(seatId) {
@ -653,12 +870,14 @@ export function WorkbenchV2(props) {
: (notice ? h('p', { className: 'ssv-banner is-notice', role: 'status' }, notice) : null)
function renderTopbar(title, extra) {
const shortcuts = tab === 'overview'
? [
h('button', { type: 'button', key: 'memory', className: 'icon-btn', title: '记忆', 'aria-label': '记忆', onClick: () => setTab('memory') }, h(BookIcon)),
h('button', { type: 'button', key: 'settings', className: 'icon-btn', title: '设置', 'aria-label': '设置', onClick: () => setTab('settings') }, h(SlidersIcon)),
]
: []
const shortcuts = [
...(tab === 'overview'
? [
h('button', { type: 'button', key: 'memory', className: 'icon-btn', title: '记忆', 'aria-label': '记忆', onClick: () => setTab('memory') }, h(BookIcon)),
h('button', { type: 'button', key: 'settings', className: 'icon-btn', title: '设置', 'aria-label': '设置', onClick: () => setTab('settings') }, h(SlidersIcon)),
]
: []),
]
return h('header', { className: 'topbar' },
h('div', { className: 'topbar-title' },
h('h1', null, title),
@ -723,7 +942,7 @@ export function WorkbenchV2(props) {
task.approvalId ? h('span', null, task.approvalId) : null,
),
h(SummaryBlock, { text: task.goal || task.requirement || '', label: '任务说明', empty: '(无任务说明)', max: 110 }),
h(SummaryBlock, { text: task.result || task.note || task.blockedReason || '', label: '当前结果 / 阻塞', empty: '(尚未回报)', max: 110 }),
h(SummaryBlock, { text: task.workflowBlockage ? task.workflowBlockage.label + ' · ' + task.workflowBlockage.reason : (task.result || task.note || task.blockedReason || ''), label: '当前结果 / 阻塞', empty: '(尚未回报)', max: 110 }),
h('div', { className: 'rc-actions' }, h('span', { className: 'spacer' }), h('button', { type: 'button', className: 'r-open', onClick: () => setSelectedTask(task) }, '查看详情 →')),
)))
: h('p', { className: 'empty-note' }, '还没有流转任务。丞相下派需求后会出现在这里。')
@ -1031,7 +1250,7 @@ export function WorkbenchV2(props) {
h('tbody', null, filtered.map(task => h('tr', { key: task.id, className: 'clickable', tabIndex: 0, onClick: () => openTask(task), onKeyDown: event => { if (event.key === 'Enter') openTask(task) } },
h('td', null, h('span', { className: 'task-name' }, task.title), h('br'), h('span', { className: 'task-id' }, task.id)),
h('td', null, SEATS[task.ownerSeatId]?.label || task.ownerSeatId || '—'),
h('td', null, h('span', { className: 'pill ' + taskTone(task.status) }, h('i'), taskLabel(task.status)), task.deliveryState && task.deliveryState !== 'none' ? h('span', { className: 'pill ' + (['failed', 'unknown'].includes(task.deliveryState) ? 'fail' : 'idle'), style: { marginLeft: '4px' } }, h('i'), deliveryLabel(task.deliveryState)) : null),
h('td', null, h('span', { className: 'pill ' + taskTone(task.status) }, h('i'), taskLabel(task.status)), task.deliveryState && task.deliveryState !== 'none' ? h('span', { className: 'pill ' + (task.deliveryState === 'unknown' ? 'fail' : 'idle'), style: { marginLeft: '4px' } }, h('i'), deliveryLabel(task.deliveryState)) : null),
h('td', { className: 'result-cell' }, task.result ? shortText(task.result, 42) : '—'),
h('td', { className: 'dur' }, taskDurationMs(task) > 0 ? durationText(taskDurationMs(task)) : '—'),
h('td', { className: 'time' }, task.dispatchedAt ? dateText(task.dispatchedAt) : '—'),
@ -1222,16 +1441,368 @@ export function WorkbenchV2(props) {
))),
) : null,
h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '承办与状态'), h('p', null, '承办席位:' + (seat ? seat.label : task.ownerSeatId) + ' · 模型:' + modelLabelOf(task.ownerSeatId) + ' · 状态:' + taskLabel(task.status) + (task.deliveryState && task.deliveryState !== 'none' ? ' · ' + deliveryLabel(task.deliveryState) : ''))),
task.workflowBlockage ? h('div', { className: 'm-sec' },
h('span', { className: 't-label' }, '当前阻塞'),
h('p', null, task.workflowBlockage.label + ' · ' + task.workflowBlockage.reason),
h('button', { type: 'button', className: 'btn', disabled: busy, onClick: () => openSeat(task.ownerSeatId) }, '打开' + (seat?.label || '承办席位') + '会话'),
) : null,
h('div', { className: 'm-sec' }, h('span', { className: 't-label' }, '任务完成情况'), h('div', { className: 'm-rich' }, task.result ? renderRichText(task.result) : h('p', { className: 'empty-note' }, '(暂无结果)'))),
h('div', { className: 'modal-actions' }, h('button', { type: 'button', className: 'btn', onClick: () => setSelectedTask(null) }, '关闭')),
),
)
}
function renderDeliberations() {
const active = deliberations.find(item => item.status === 'running') || null
const shownId = delibSelectedId || active?.id || deliberations[0]?.id || null
const summary = deliberations.find(item => item.id === shownId) || null
const full = deliberation && deliberation.id === shownId ? deliberation : null
const shown = full || summary || null
const isActive = Boolean(shown && shown.status === 'running')
const seatLabel = id => (SEATS[id] && SEATS[id].label) || id || '—'
const stanceLabel = stance => stance === 'agree' ? '同意' : (stance === 'dissent' ? '有分歧' : '未表态')
const turnLabel = status => ({
waiting: '待叫席', delivering: '投递中', delivered: '已叫席', failed: '叫席失败', timeout: '未回',
}[status] || '待发言')
const taskOptions = tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution')
const maxText = shown && shown.maxRounds > 0 ? String(shown.maxRounds) + ' 轮' : '不限'
const missingText = shown && Array.isArray(shown.missing) && shown.missing.length
? '未回:' + shown.missing.map(item => seatLabel(item.seatId) + '(第 ' + item.round + ' 轮 '
+ (item.reason === 'unknown' ? '发送结果未知' : item.reason === 'timeout' ? '超时' : '失败') + ')').join(';')
: ''
const startForm = h('section', { className: 'card', 'aria-label': '发起议政' },
h('h3', null, '发起议政'),
h('p', { className: 'foot-note' }, '三省各派代表,按中书 → 门下 → 尚书轮流发言;后发言者能看到前文。'),
h('label', { className: 'cfg-row', style: { display: 'block', marginTop: '10px' } }, '议题',
h('textarea', {
rows: 3, className: 'ssv-textarea', value: delibDraft.topic,
placeholder: '例如:多语言页面首版先做哪些语言?',
onChange: event => setDelibDraft(previous => ({ ...previous, topic: event.target.value })),
}),
),
h('div', { className: 'cfg-grid', style: { marginTop: '8px' } },
h('label', { className: 'cfg-row' }, '关联任务(可选)',
h('select', {
value: delibDraft.taskId,
onChange: event => setDelibDraft(previous => ({ ...previous, taskId: event.target.value })),
},
h('option', { value: '' }, '不关联任务'),
taskOptions.map(task => h('option', { key: task.id, value: task.id }, task.id + ' · ' + task.title)),
),
),
h('label', { className: 'cfg-row' }, '关联需求(可选)',
h('select', {
value: delibDraft.requirementId,
onChange: event => setDelibDraft(previous => ({ ...previous, requirementId: event.target.value })),
},
h('option', { value: '' }, '不关联需求'),
requirements.map(req => h('option', { key: req.id, value: req.id }, req.id + ' v' + req.revision + ' · ' + req.title)),
),
),
h('label', { className: 'cfg-row' }, '轮次上限',
h('input', {
type: 'number', min: 0, max: 20, value: delibDraft.maxRounds,
onChange: event => setDelibDraft(previous => ({ ...previous, maxRounds: event.target.value })),
}),
h('span', { className: 'foot-note' }, '默认 3;填 0 表示不限。'),
),
),
h('div', { className: 'ws-actions' },
h('button', { type: 'button', className: 'btn primary', disabled: delibBusy || Boolean(active), onClick: startDeliberation },
delibBusy ? '发起中…' : (active ? '已有进行中的议政' : '发起议政')),
),
)
const activeHead = isActive
? h('section', { className: 'card', 'aria-label': '当前议政' },
h('div', { className: 'rc-head' },
h('h3', null, shown.topic),
h('span', { className: 'rc-status run' }, h('i'), '进行中'),
),
h('div', { className: 'req-meta' },
h('span', null, '第 ' + shown.round + ' 轮 / 上限 ' + maxText),
h('span', null, '当前当值:' + (shown.currentSeatLabel || seatLabel(shown.currentSeatId))),
h('span', null, '叫席:' + turnLabel(shown.turn && shown.turn.status)),
shown.turn && shown.turn.attempts ? h('span', null, '第 ' + shown.turn.attempts + ' 次投递') : null,
),
shown.turn && shown.turn.error ? h('p', { className: 'ssv-banner is-error' }, shown.turn.error) : null,
missingText ? h('p', { className: 'foot-note' }, missingText) : null,
shown.originSessionId ? h('p', { className: 'foot-note' }, '发起会话:' + shown.originSessionId.slice(0, 8)) : null,
shown.turn && ['failed', 'timeout'].includes(shown.turn.status)
? h('div', { className: 'ws-actions' },
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: retryDeliberation }, '重试当前席位'),
)
: null,
h('div', { className: 'ws-actions', style: { marginTop: '10px' } },
h('input', {
type: 'text', value: delibEndNote, placeholder: '结束或停止说明(可选)',
onChange: event => setDelibEndNote(event.target.value),
style: { flex: '1 1 180px' },
}),
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: endDeliberation }, '结束并收束'),
h('button', {
type: 'button', className: 'btn', disabled: delibBusy, onClick: stopDeliberation,
title: '立刻中断当前席位,不再叫下一位',
}, '立即停止'),
),
h('p', { className: 'foot-note' }, '「结束并收束」按正常流程生成结论;「立即停止」会立刻落状态、中断当前席位,之后不再叫下一位。'),
)
: null
const stoppedHead = shown && shown.status === 'stopped'
? h('section', { className: 'card', 'aria-label': '已停止的议政' },
h('div', { className: 'rc-head' },
h('h3', null, shown.topic),
h('span', { className: 'rc-status fail' }, h('i'), '已停止'),
),
h('div', { className: 'req-meta' },
h('span', null, '停在第 ' + (shown.stoppedTurn?.round ?? shown.round) + ' 轮'),
h('span', null, '停在:' + (shown.stoppedTurn?.seatLabel || seatLabel(shown.stoppedTurn?.seatId))),
shown.stoppedAt ? h('span', null, '停止时间:' + new Date(shown.stoppedAt).toLocaleString()) : null,
),
shown.stoppedNote ? h('p', { className: 'foot-note' }, '停止说明:' + shown.stoppedNote) : null,
h('p', { className: 'foot-note' }, '停止后不会再叫下一位;已有发言保留在下方转写。'),
)
: null
const transcript = shown && Array.isArray(shown.speeches) ? shown.speeches : []
const transcriptBlock = h('section', { className: 'card', 'aria-label': '议政转写' },
h('h3', null, '议政转写'),
transcript.length === 0
? h('p', { className: 'empty-note' }, '还没有发言。')
: h('div', { className: 'review-list' }, transcript.map(speech => h('article', { className: 'review-card', key: speech.id },
h('div', { className: 'rc-head' },
h('div', { className: 'rc-title' }, seatLabel(speech.seatId) + ' · 第 ' + speech.round + ' 轮'),
h('span', { className: 'rc-status ' + (speech.stance === 'agree' ? 'done' : speech.stance === 'dissent' ? 'fail' : 'review') },
h('i'), stanceLabel(speech.stance)),
),
h('p', { className: 'card-summary-text', style: { whiteSpace: 'pre-wrap' } }, speech.text),
speech.openIssues ? h('p', { className: 'foot-note' }, '未决:' + speech.openIssues) : null,
speech.pending ? h('p', { className: 'foot-note' }, '本席仍有待决问题。') : null,
))),
)
const conclusionBlock = shown && shown.conclusion
? h('section', { className: 'card', 'aria-label': '议政结论' },
h('h3', null, '结论'),
h('p', { className: 'card-summary-text', style: { whiteSpace: 'pre-wrap' } }, shown.conclusion.text),
h('p', { className: 'foot-note' }, shown.conclusion.needsUserDecision ? '有分歧或未回席位,需要用户决定。' : '三省已一致。'),
)
: null
const history = deliberations.filter(item => item.status !== 'running')
const historyBlock = h('section', { className: 'card', 'aria-label': '历史议政' },
h('h3', null, '历史议政'),
history.length === 0
? h('p', { className: 'empty-note' }, '还没有已收束的议政。')
: h('div', { className: 'review-list' }, history.map(item => h('article', {
className: 'review-card', key: item.id, style: { cursor: 'pointer' },
onClick: () => setDelibSelectedId(item.id),
},
h('div', { className: 'rc-head' },
h('div', { className: 'rc-title' }, item.topic),
h('span', { className: 'rc-status ' + (item.status === 'stopped' ? 'fail' : 'done') }, h('i'), item.status === 'stopped' ? '已停止' : '已收束'),
),
h('p', { className: 'foot-note' }, item.id + ' · 第 ' + item.round + ' 轮 · 发言 ' + item.speechCount + ' 条'
+ (item.status === 'stopped' && item.stoppedTurn ? ' · 停在第 ' + item.stoppedTurn.round + ' 轮 ' + (item.stoppedTurn.seatLabel || seatLabel(item.stoppedTurn.seatId)) : '')),
item.conclusion ? h('p', { className: 'card-summary-text' }, shortText(item.conclusion.text, 140)) : null,
))),
)
return h('div', { className: 'page' },
renderTopbar('三省议政', [
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => { void refreshDeliberations().catch(() => {}) } }, '刷新'),
active && shown && shown.id !== active.id
? h('button', { type: 'button', className: 'btn primary', onClick: () => setDelibSelectedId(active.id) }, '回到进行中')
: null,
]),
startForm,
activeHead,
stoppedHead,
transcriptBlock,
conclusionBlock,
historyBlock,
)
}
function renderChatDeliberations() {
const avatars = view?.project?.avatars ?? {}
const active = deliberations.find(item => item.status === 'running') || null
const shownId = delibSelectedId || active?.id || deliberations[0]?.id || null
const summary = deliberations.find(item => item.id === shownId) || null
const full = deliberation && deliberation.id === shownId ? deliberation : null
const shown = full || summary || null
const isActive = Boolean(shown && shown.status === 'running')
const currentSeat = isActive ? (shown.currentSeatId || shown.turn?.seatId || null) : null
const seatLabel = id => (SEATS[id] && (SEATS[id].name || SEATS[id].label)) || id || '—'
const statusText = !shown ? '还没有议政' : isActive
? '第 ' + shown.round + ' 轮 · ' + (currentSeat ? seatLabel(currentSeat) + '正在说' : '等待叫席')
: shown.status === 'stopped'
? '停在第 ' + (shown.stoppedTurn?.round ?? shown.round) + ' 轮 · ' + (shown.stoppedTurn?.seatLabel || seatLabel(shown.stoppedTurn?.seatId))
: '已收束 · 第 ' + shown.round + ' 轮'
const statusTone = isActive ? 'run' : shown?.status === 'stopped' ? 'fail' : 'done'
const statusBar = h('div', { className: 'card', style: { display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', marginBottom: 6 } },
h('span', { className: 'rc-status ' + statusTone }, h('i'), isActive ? '进行中' : shown?.status === 'stopped' ? '已停止' : '已收束'),
h('span', { style: { fontSize: 13 } }, statusText),
h('span', { style: { flex: 1 } }),
shown?.id ? h('span', { className: 'foot-note' }, shown.id) : null,
isActive ? h('button', {
type: 'button', className: 'btn', title: '立刻中断当前席位,不再叫下一位',
style: { height: 24, padding: '0 8px', fontSize: 12 }, disabled: delibBusy, onClick: stopDeliberation,
}, '停止') : null,
)
const seatRow = h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', margin: '2px 0 8px' } },
DELIB_SEATS.map(seatId => h('button', {
key: seatId, type: 'button', title: '换' + seatLabel(seatId) + '头像',
style: {
display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', padding: 2,
opacity: !isActive || currentSeat === seatId ? 1 : 0.5,
},
onClick: () => setAvatarEdit(previous => previous?.seatId === seatId ? null : { seatId, char: '' }),
}, avatarNode(seatId, avatars, 30, isActive && currentSeat === seatId), h('span', { style: { fontSize: 12 } }, seatLabel(seatId)))),
h('span', { style: { flex: 1 } }),
h('button', {
type: 'button', className: 'btn', style: { height: 24, padding: '0 8px', fontSize: 12 },
onClick: () => setDelibSettingsOpen(value => !value),
}, '设置'),
)
const settings = delibSettingsOpen ? h('div', { className: 'card', style: { padding: 10, marginBottom: 6, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'end' } },
h('label', { className: 'cfg-row' }, '轮次上限',
h('input', {
type: 'number', min: 0, max: 20, value: delibDraft.maxRounds, style: { width: 64 },
onChange: event => setDelibDraft(prev => ({ ...prev, maxRounds: event.target.value })),
}),
),
h('label', { className: 'cfg-row' }, '关联任务',
h('select', { value: delibDraft.taskId, onChange: event => setDelibDraft(prev => ({ ...prev, taskId: event.target.value })) },
h('option', { value: '' }, '不关联'),
tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution').map(task => h('option', { key: task.id, value: task.id }, task.id + ' ' + task.title)),
),
),
h('label', { className: 'cfg-row' }, '关联需求',
h('select', { value: delibDraft.requirementId, onChange: event => setDelibDraft(prev => ({ ...prev, requirementId: event.target.value })) },
h('option', { value: '' }, '不关联'),
requirements.map(req => h('option', { key: req.id, value: req.id }, req.id + ' v' + req.revision + ' ' + req.title)),
),
),
h('span', { className: 'foot-note' }, '默认 3 轮,填 0 表示不限'),
) : null
const avatarEditor = avatarEdit ? h('div', { className: 'card', style: { padding: 10, marginBottom: 6 } },
h('div', { style: { display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' } },
avatarNode(avatarEdit.seatId, avatars, 40),
h('label', { className: 'btn', style: { cursor: 'pointer' } }, '选图片',
h('input', {
type: 'file', accept: 'image/png,image/jpeg,image/webp', style: { display: 'none' },
onChange: event => { const file = event.target.files?.[0]; if (file) void pickAvatarFile(avatarEdit.seatId, file); event.target.value = '' },
}),
),
h('input', {
type: 'text', maxLength: 8, placeholder: '或填一个字/emoji', value: avatarEdit.char, style: { width: 130 },
onChange: event => setAvatarEdit(prev => ({ ...prev, char: event.target.value })),
}),
h('button', { type: 'button', className: 'btn primary', disabled: delibBusy || !avatarEdit.char.trim(), onClick: () => void saveAvatar(avatarEdit.seatId, { char: avatarEdit.char.trim() }) }, '保存字符'),
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => void saveAvatar(avatarEdit.seatId, { clear: true }) }, '恢复默认'),
h('span', { style: { flex: 1 } }),
h('button', { type: 'button', className: 'btn', onClick: () => setAvatarEdit(null) }, '关闭'),
),
h('p', { className: 'foot-note' }, '图片缩到 256×256 后保存,限 120KB;默认头像沿用席位名。'),
) : null
const transcript = shown?.speeches ?? []
const bubbles = transcript.length === 0
? h('p', { className: 'empty-note', style: { textAlign: 'center', padding: '34px 0' } }, '还没开始议政,说一句就能开。')
: h('div', { style: { display: 'flex', flexDirection: 'column', gap: 12, padding: '6px 2px 10px' } },
transcript.map(speech => h('div', { key: speech.id, style: { display: 'flex', gap: 10, alignItems: 'flex-start' } },
avatarNode(speech.seatId, avatars, 32, isActive && currentSeat === speech.seatId),
h('div', { style: { maxWidth: '78%' } },
h('div', { style: { fontSize: 12, color: '#6b7280', marginBottom: 3 } },
seatLabel(speech.seatId) + ' · 第 ' + speech.round + ' 轮'
+ (speech.stance === 'dissent' ? ' · 有分歧' : speech.pending ? ' · 仍有待决' : '')),
h('div', {
style: {
background: speech.seatId === 'zhongshu' ? '#eef2ff' : speech.seatId === 'menxia' ? '#e6fcf5' : '#fff4e6',
borderRadius: 12, padding: '9px 12px', fontSize: 14, lineHeight: 1.65, whiteSpace: 'pre-wrap',
},
}, speech.text),
speech.openIssues ? h('div', { className: 'foot-note', style: { marginTop: 4 } }, '未决:' + speech.openIssues) : null,
),
)),
)
const stoppedNote = shown?.status === 'stopped'
? h('p', { className: 'foot-note', style: { textAlign: 'center', padding: '5px 0 8px' } },
'停在第 ' + (shown.stoppedTurn?.round ?? shown.round) + ' 轮 · ' + (shown.stoppedTurn?.seatLabel || seatLabel(shown.stoppedTurn?.seatId))
+ ',不会再叫下一位。' + (shown.stoppedNote ? ' 说明:' + shown.stoppedNote : ''))
: null
const conclusion = shown?.conclusion && !isActive
? h('section', { className: 'card', style: { marginTop: 8 } },
h('h3', null, '结论'),
h('p', { className: 'card-summary-text', style: { whiteSpace: 'pre-wrap' } }, shown.conclusion.text),
)
: null
const composer = h('div', { className: 'card', style: { display: 'flex', gap: 8, alignItems: 'center', marginTop: 8, padding: 8 } },
h('input', {
type: 'text', value: delibDraft.topic, placeholder: isActive ? '这一场还在进行,先看他们说完' : '说一句要三省议的事…',
disabled: Boolean(active), style: { flex: 1, minWidth: 0 },
onChange: event => setDelibDraft(prev => ({ ...prev, topic: event.target.value })),
onKeyDown: event => { if (event.key === 'Enter' && !active) void startDeliberation() },
}),
h('button', { type: 'button', className: 'btn primary', disabled: delibBusy || Boolean(active) || !delibDraft.topic.trim(), onClick: startDeliberation },
delibBusy ? '发起中…' : '发起'),
)
const runsBlock = agentRuns.length
? h('section', { className: 'card', style: { marginTop: 8 } },
h('h3', null, '后台子 Agent'),
h('div', { className: 'review-list' }, agentRuns.map(run => h('div', { key: run.id, className: 'review-card', style: { display: 'flex', alignItems: 'center', gap: 8 } },
h('span', { className: 'rc-title', style: { flex: 1, fontSize: 13 } },
(run.label || run.seatId) + (run.deliberationId ? ' · ' + run.deliberationId + ' 第 ' + run.round + ' 轮' : '')
+ (run.kind === 'order' && run.brief ? ' · ' + shortText(run.brief, 36) : '')),
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => void stopAgentRun(run) }, '停止'),
))),
)
: null
const history = deliberations.filter(item => item.status !== 'running')
const historyBlock = history.length
? h('section', { className: 'card', style: { marginTop: 8 } },
h('h3', null, '历史议政'),
h('div', { className: 'review-list' }, history.slice(0, 6).map(item => h('button', {
key: item.id, type: 'button', className: 'review-card', style: { textAlign: 'left', cursor: 'pointer' },
onClick: () => setDelibSelectedId(item.id),
},
h('span', { className: 'rc-title' }, item.topic),
h('span', { className: 'foot-note' }, item.id + ' · ' + (item.status === 'stopped' ? '已停止' : '已收束') + ' · 发言 ' + item.speechCount + ' 条'),
))),
)
: null
return h('div', { className: 'page' },
renderTopbar('三省议政', [
h('button', { type: 'button', className: 'btn', disabled: delibBusy, onClick: () => { void refreshDeliberations().catch(() => {}) } }, '刷新'),
]),
statusBar,
seatRow,
settings,
avatarEditor,
h('div', { className: 'card', style: { padding: '2px 10px' } }, bubbles, stoppedNote),
composer,
runsBlock,
conclusion,
historyBlock,
)
}
function renderPage() {
if (phase === 'loading') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '正在载入工作台…'))
if (phase === 'no-workspace') return h('div', { className: 'page' }, h('p', { className: 'empty-note' }, '请先在宿主中选择或建立一个项目工作区,再打开三省六部工作台。'))
if (phase === 'error' && !view) return h('div', { className: 'page' }, h('p', { className: 'ssv-banner is-error', role: 'alert' }, error || '工作台加载失败'), errorRetryable ? h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', onClick: loadProject }, '重试')) : null)
if (page === 'deliberations') return renderChatDeliberations()
if (tab === 'memory') return renderMemory()
if (tab === 'settings') return renderSettings()
return renderOverview()
@ -1241,9 +1812,14 @@ export function WorkbenchV2(props) {
h('div', { className: 'main' },
h('div', { className: 'panel-top' },
h('div', { className: 'brand' }, h('span', { className: 'seal' }, '三省六部'), h('span', { className: 'sub' }, 'DSH 工作台')),
tab !== 'overview' ? h('div', { className: 'panel-actions' },
h('button', { type: 'button', className: 'btn', onClick: () => setTab('overview') }, '← 总览'),
) : null,
tab !== 'overview' || page !== 'overview' ? h('div', { className: 'panel-actions' },
h('button', { type: 'button', className: 'btn' + (page === 'overview' && tab === 'overview' ? ' primary' : ''), onClick: () => { setPage('overview'); setTab('overview') } }, '概览'),
h('button', { type: 'button', className: 'btn' + (page === 'deliberations' ? ' primary' : ''), onClick: () => setPage('deliberations') }, '议政'),
tab !== 'overview' ? h('button', { type: 'button', className: 'btn', onClick: () => setTab('overview') }, '← 总览') : null,
) : h('div', { className: 'panel-actions' },
h('button', { type: 'button', className: 'btn primary', onClick: () => { setPage('overview'); setTab('overview') } }, '概览'),
h('button', { type: 'button', className: 'btn', onClick: () => setPage('deliberations') }, '议政'),
),
),
statusBanner,
renderPage(),

View File

@ -15,6 +15,11 @@ function requireTaskId(payload) {
if (typeof id !== 'string' || id.trim() === '') throw bad('缺少 taskId')
return id
}
function requireDeliberationId(payload) {
const id = payload?.deliberationId
if (typeof id !== 'string' || id.trim() === '') throw bad('缺少 deliberationId')
return id
}
// 生成 POST /api/sansheng 的处理函数:{endpoint,payload} -> {ok,value}|{ok,error}
export function createApiHandler(service) {
@ -88,6 +93,40 @@ export function createApiHandler(service) {
return { ok: true, value: await service.approvals(requireProjectId(payload)) }
case 'leadReports':
return { ok: true, value: await service.leadReports(requireProjectId(payload)) }
case 'cardGet':
return { ok: true, value: await service.cardGet(payload?.cardId) }
case 'cardAnswer':
return { ok: true, value: await service.cardAnswer(payload?.cardId, payload?.choice) }
case 'cards':
return { ok: true, value: await service.cards(requireProjectId(payload)) }
case 'deliberations':
return { ok: true, value: await service.deliberations(requireProjectId(payload)) }
case 'deliberation':
return { ok: true, value: await service.deliberation(requireProjectId(payload), requireDeliberationId(payload)) }
case 'deliberationStart':
return { ok: true, value: await service.startDeliberation(requireProjectId(payload), payload ?? {}) }
case 'deliberationEnd':
return { ok: true, value: await service.endDeliberation(requireProjectId(payload), requireDeliberationId(payload), payload ?? {}) }
case 'deliberationStop':
return { ok: true, value: await service.stopDeliberation(requireProjectId(payload), requireDeliberationId(payload), payload ?? {}) }
case 'order':
return { ok: true, value: await service.startOrder(requireProjectId(payload), payload ?? {}, {}) }
case 'agents':
return { ok: true, value: await service.agentRuns(requireProjectId(payload)) }
case 'agentStop':
return { ok: true, value: await service.stopAgentRun(requireProjectId(payload), payload?.runId, payload?.kind) }
case 'setAvatar': {
const seatId = payload?.seatId
if (!SEAT_IDS.includes(seatId)) throw bad('未知席位')
return { ok: true, value: await service.setAvatar(requireProjectId(payload), seatId, payload ?? {}) }
}
case 'clearAvatar': {
const seatId = payload?.seatId
if (!SEAT_IDS.includes(seatId)) throw bad('未知席位')
return { ok: true, value: await service.clearAvatar(requireProjectId(payload), seatId) }
}
case 'deliberationRetry':
return { ok: true, value: await service.retryDeliberation(requireProjectId(payload), requireDeliberationId(payload)) }
case 'seatStatus':
return { ok: true, value: await service.statusSnapshot(payload?.projectId) }
case 'approvalAnswer': {

View File

@ -7,7 +7,8 @@ export class ApprovalCenterError extends Error {
}
export const APPROVAL_STATUSES = Object.freeze(['pending', 'answered', 'cancelled', 'error'])
const CHOICES = new Set(['allow', 'reject'])
const OUTCOME_BY_CHOICE = new Map([['allow', 'allowed-once'], ['reject', 'rejected']])
const NATIVE_OUTCOMES = new Set(['allowed-once', 'rejected', 'cancelled', 'unavailable'])
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
function copy(value) { try { return structuredClone(value) } catch { return JSON.parse(JSON.stringify(value)) } }
@ -20,7 +21,7 @@ export function redactApprovalDetail(detail) {
return { text: text.slice(0, 500), code: code.slice(0, 200) }
}
export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = () => Date.now(), idFactory = randomUUID, outcomeFor } = {}) {
export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = () => Date.now(), idFactory = randomUUID, onPending = null } = {}) {
if (typeof resolveSeatBySessionId !== 'function') throw new ApprovalCenterError('sansheng/approval-config', '需要 resolveSeatBySessionId')
const clock = typeof now === 'function' ? now : () => Number(now)
const pending = new Map()
@ -40,22 +41,13 @@ export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = (
return () => listeners.delete(listener)
}
function buildOutcome(choice) {
if (typeof outcomeFor === 'function') return outcomeFor(choice)
return choice
}
function finalize(entry, status, payload) {
function finalize(entry, outcome) {
if (!entry || entry.settled) return false
entry.settled = true
entry.status = status
entry.finishedAt = clock()
entry.status = outcome === 'unavailable' ? 'error' : (outcome === 'cancelled' ? 'cancelled' : 'answered')
pending.delete(entry.id)
try { entry.linked?.abort?.() } catch { /* ignore */ }
if (status === 'answered') entry.resolve(buildOutcome(payload))
else if (status === 'cancelled') entry.resolve({ cancelled: true })
else entry.reject(payload instanceof Error ? payload : new ApprovalCenterError('sansheng/approval-error', String(payload?.message ?? payload ?? 'approval error')))
emit({ type: 'closed', entry: publicEntry(entry), status })
entry.resolve(outcome)
emit({ type: 'closed', entry: publicEntry(entry), status: entry.status, outcome })
return true
}
@ -78,46 +70,33 @@ export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = (
const id = idFactory()
const entry = {
id, sessionId, projectId: located.projectId, seatId: located.seatId,
tool: cleanText(request.tool ?? request.name ?? request.toolName),
tool: cleanText(request.toolName ?? request.tool ?? request.name),
reason: cleanText(request.reason ?? request.message ?? ''),
detail: redactApprovalDetail(request.detail ?? request.data),
callId: cleanText(request.callId ?? request.id) || null,
at: clock(), status: 'pending', settled: false,
linked: new AbortController(), nativeCalled: false,
resolve: null, reject: null,
resolve: null,
}
const outcomePromise = new Promise((resolve, reject) => { entry.resolve = resolve; entry.reject = reject })
const outcomePromise = new Promise(resolve => { entry.resolve = resolve })
// 先建 Promise/监听,再登记与通知,防止“同步应答”时找不到 entry。
const onAbort = () => finalize(entry, 'cancelled', null)
const onAbort = () => finalize(entry, 'cancelled')
const originalSignal = request.signal
if (originalSignal) {
if (originalSignal.aborted) { finalize(entry, 'cancelled', null); return outcomePromise }
if (originalSignal.aborted) return 'cancelled'
try { originalSignal.addEventListener('abort', onAbort, { once: true }) } catch { /* ignore */ }
}
pending.set(id, entry)
emit({ type: 'open', entry: publicEntry(entry) })
if (typeof onPending === 'function') {
try { onPending(publicEntry(entry)) } catch { /* 通知失败不影响原生审批 */ }
}
const settleNative = result => {
// 工作台与原生卡共用一个结果。原生卡的应答按 DSH 的结果码透传。
void Promise.resolve().then(async () => {
if (entry.settled) return
if (result && typeof result === 'object' && result.cancelled) finalize(entry, 'cancelled', null)
else finalize(entry, 'answered', result && typeof result === 'object' && 'choice' in result ? result.choice : result)
}
const callNext = () => {
if (!pending.has(id) || disposed || entry.settled) return undefined
entry.nativeCalled = true
try {
const native = typeof next === 'function' ? next() : undefined
if (native && typeof native.then === 'function') {
native.then(settleNative, error => finalize(entry, 'error', error))
} else if (native !== undefined) settleNative(native)
return native
} catch (error) {
finalize(entry, 'error', error)
return undefined
}
}
// 延后一拍再开原生卡:若 open 同步回答了,不会迟开。
Promise.resolve().then(callNext).catch(error => finalize(entry, 'error', error))
const native = await next?.()
finalize(entry, NATIVE_OUTCOMES.has(native) ? native : 'unavailable')
}).catch(() => finalize(entry, 'unavailable'))
try { return await outcomePromise } finally {
try { originalSignal?.removeEventListener?.('abort', onAbort) } catch { /* ignore */ }
}
@ -134,13 +113,18 @@ export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = (
function answer(id, identity = {}, choice) {
if (disposed) throw new ApprovalCenterError('sansheng/approval-disposed', '审批中心已卸载')
if (!CHOICES.has(choice)) throw new ApprovalCenterError('sansheng/approval-invalid', 'choice 必须是 allow 或 reject')
if (!OUTCOME_BY_CHOICE.has(choice)) throw new ApprovalCenterError('sansheng/approval-invalid', 'choice 必须是 allow 或 reject')
const entry = pending.get(cleanText(id))
if (!entry) throw new ApprovalCenterError('sansheng/approval-stale', '审批已处理或不存在')
if (identity.projectId !== entry.projectId || identity.seatId !== entry.seatId || identity.sessionId !== entry.sessionId) {
if (identity.projectId !== entry.projectId) {
throw new ApprovalCenterError('sansheng/approval-forbidden', '审批归属不匹配')
}
const ok = finalize(entry, 'answered', choice)
// 丞相可以代表本项目回答任一席的审批;其他席位仍必须精确匹配自己的申请。
const leadAnswer = identity.seatId === 'lead'
if (!leadAnswer && (identity.seatId !== entry.seatId || identity.sessionId !== entry.sessionId)) {
throw new ApprovalCenterError('sansheng/approval-forbidden', '审批归属不匹配')
}
const ok = finalize(entry, OUTCOME_BY_CHOICE.get(choice))
if (!ok) throw new ApprovalCenterError('sansheng/approval-stale', '审批已处理或不存在')
return { ok: true, status: 'answered', choice }
}
@ -153,7 +137,7 @@ export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = (
function cancelForSession(sessionId) {
let count = 0
for (const entry of [...pending.values()]) {
if (entry.sessionId === sessionId) { if (finalize(entry, 'cancelled', null)) count += 1 }
if (entry.sessionId === sessionId && finalize(entry, 'cancelled')) count += 1
}
return count
}
@ -183,7 +167,7 @@ export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = (
function dispose() {
if (disposed) return
disposed = true
for (const entry of [...pending.values()]) finalize(entry, 'cancelled', null)
for (const entry of [...pending.values()]) finalize(entry, 'cancelled')
listeners.clear()
}

View File

@ -1,6 +1,6 @@
// R-006:消息来源标签。真实用户 = source.kind="user" 且带 clientTimeZone(或宿主确认 trusted)。
// 内部任务/回报必须标记 sansheng-task / sansheng-report / sansheng-summary,绝不能冒充 user。
export const INTERNAL_SOURCE_KINDS = Object.freeze(['sansheng-task', 'sansheng-report', 'sansheng-summary'])
export const INTERNAL_SOURCE_KINDS = Object.freeze(['sansheng-task', 'sansheng-report', 'sansheng-summary', 'sansheng-deliberation'])
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
@ -11,12 +11,13 @@ export function userMessageSource({ clientTimeZone, trusted = false } = {}) {
return source
}
export function internalSource(kind, { seatId, taskId, reportId, at } = {}) {
export function internalSource(kind, { seatId, taskId, reportId, deliberationId, at } = {}) {
if (!INTERNAL_SOURCE_KINDS.includes(kind)) throw new Error('内部消息来源非法:' + String(kind))
const source = { kind }
if (cleanText(seatId)) source.seatId = seatId
if (cleanText(taskId)) source.taskId = taskId
if (cleanText(reportId)) source.reportId = reportId
if (cleanText(deliberationId)) source.deliberationId = deliberationId
if (Number.isFinite(at)) source.at = at
return source
}
@ -76,7 +77,6 @@ export function createTurnCommands(ctx, store) {
const [message] = messages ?? []
if (messages?.length === 1 && isTrustedUserMessage(message) && cleanText(message.source?.rpcId)) {
entry.messageId = cleanText(message.id)
entry.text = textOfMessage(message)
}
return next()
})
@ -91,9 +91,12 @@ export function createTurnCommands(ctx, store) {
}
const message = event.data
if (event.type !== 'user/message' || !entry.messageId || message?.id !== entry.messageId) return
if (!isTrustedUserMessage(message) || textOfMessage(message) !== entry.text) return
if (!isTrustedUserMessage(message)) return
if (!Number.isSafeInteger(event.seq) || event.seq <= entry.boundary) return
entry.command = { text: entry.text, messageId: entry.messageId, seq: event.seq }
// 正文只认宿主落盘事件;空正文不算命令。消息身份由 id、来源和轮次确认。
const text = textOfMessage(message)
if (!text) return
entry.command = { text, messageId: entry.messageId, seq: event.seq }
})
return {
read(exec) {

View File

@ -47,9 +47,10 @@ export function createModelSync({ store, globalStore, host, normalizeCatalog, no
function setStatus(projectId, seatId, patch) {
const key = keyOf(projectId, seatId)
const previous = statuses.get(key) ?? {}
// agentRef 是活 Agent,不能深拷贝;状态对外只通过 publicStatus 去掉它。
const next = { ...previous, ...patch, updatedAt: clock() }
statuses.set(key, next)
return copy(next)
return publicStatus(next)
}
function publicStatus(record) {
if (!record) return null

View File

@ -15,25 +15,30 @@ export function renderSeatPrompt({ project, seatId, seat }) {
if (seatId === 'lead') {
lines.push(
'',
'你负责需求澄清、协调与交付。讨论、查资料或提到「下派」的例句均无执行授权。用户表达「照这个做」「安排下去」等清楚行动意图时,整理需求后可直接用 sansheng_requirement_publish 交给中书。多项候选无法判断时问清楚。',
'你负责需求澄清、协调与交付。讨论、查资料或提到「下派」的例句均无执行授权。用户表达「照这个做」「安排下去」等清楚行动意图时,整理需求后可直接用 sansheng_requirement_publish 交给中书。下派只需要需求标题、用户原话和你的明确授权;范围、非目标和验收标准可以留空,由中书拟案补齐,不必为此先追问。多项候选无法判断时问清楚。用户说「发布009吧」「下派 009」就是下派 R-009,直接调用工具,无需用户补写 R- 或「给中书」。以前聊天里的固定口令已经废止。遇到工具错误时报告实际错误。',
'只有 judgement 明确为 not_now 时才阻止下派;空白或 needs_discussion 都可在用户明确授权后进入中书,由中书拟案判断可行性。',
'四位项目主簿与记室:用 sansheng_lead_secretary 按 role 启动——zhongshu 对接中书,menxia 对接门下,shangshu 对接尚书,requirement 是记室、记录用户需求;启动记室时把用户原话放进 brief。主簿与记室在后台只读调查和记录,不阻塞你和用户聊天,也不得代办发布、批准或派工。',
'向中书下达具体指令、需要留回执时,用 sansheng_order:工具先返回回执(谁下的、关联任务或需求版本),中书接令子 Agent 核对后把用户原话和要点交给中书主席。不要用普通聊天消息替代接令回执。',
'收到来源为 sansheng-report 的省级正式回报,或后台主簿或记室交回的结果时,立即用零基础白话向用户说明:发生了什么、对当前任务的影响、是否需要用户决定、下一步;不要等其它省或后台主簿或记室。向用户提问也只用零基础白话,一次问一个关键问题。',
'需要用户回答或审批时用 sansheng_card 挂卡:问题卡给 2 到 5 个选项;审批卡必须带审批报告里的审批编号作为 approvalId,正文写清谁申请、要做什么、原因、同意和拒绝的后果。卡片不阻塞聊天,用户可以继续说话或回头答旧卡;你只解释,不代批。审批结论由用户点卡送回原审批请求。',
'Grill Me 需求澄清规则:只有会显著改变范围、验收、成本或风险的歧义才调用 skill({ name: "grilling" })。技能不可用时说明实际情况。先自行查证事实,一次问一个会改变方案的问题。用户主动要求 Grill Me 时按技能处理。必要信息已齐或用户要求停止时结束追问。仅讨论和查资料时无需追问。用户明确要求「问清楚就做」时,在同一条需求草稿保存 dispatchAfterClarification=true;得到必要答复后设置 authorization=clarified 下派。扩大范围、换目标、拒绝或撤回时清除预授权,等新的授权。',
'需求清单保存用户原话、已确认范围、非目标和验收标准。需求改变时更新同一条需求并携带 expectedRevision。新需求涉及已知偏好时可按已知偏好处理,避免重复问。',
'需求清单保存用户原话和已确认内容。用户已确认的范围、非目标和验收标准保持原样;未确认的可留空交中书补齐。需求改变时更新同一条需求并携带 expectedRevision。新需求涉及已知偏好时可按已知偏好处理,避免重复问。',
'工作独立且会占用用户等待时间时,用 sansheng_lead_background 分出需求整理、派工准备、跟踪或反馈。可同时安排互不依赖的工作,收到启动回执后继续当前对话。助手回报是建议,检查任务和需求版本后再正式办理。',
'门下通过后由尚书安排。收到会商分歧时,先按同项目已知偏好判断,用 sansheng_task_consult 将结论发给相关席。实质分歧仍不确定时用 sansheng_task_decision 请求确认。不要代替执行席回报。',
)
} else {
lines.push(
'',
'回报硬性规则:你必须使用 sansheng_task_report 工具回报真实状态(running 执行中、done 完成、failed 失败);done 必须附真实结果(文件路径、输出或验证结果),不得虚报。丞相不能代替部门报告。',
'交接消息包含任务编号、用户原话和已确认内容。材料齐全时直接完成本阶段,只有缺少关键事实才查询。提交拟案、审核、派工、汇总和验收会直接记录进度,省略额外的开工回报。工具明确返回审批拒绝、取消或通道不可用时,停止重复提交,在当前回复里说明被阻止的动作。',
)
if (seatId === 'zhongshu') {
lines.push('中书流程规则:收到丞相发布的需求后,只读调查并完成拟案,使用 sansheng_workflow_submit 提交门下审核。拟案阶段不得修改工程、不得向六部派工、不得跳过门下。')
lines.push('中书拟案:根据用户原话和已确认内容写出交付项、实现步骤和关键验收点。需求缺少范围、非目标、验收标准或风险时,用 sansheng_workflow_submit 的结构化字段补入任务快照;只补空缺,用户已确认的字段保持原样,需求正文和版本不动。门下退回后可修订自己补的字段,省略字段保留已有快照值,也不借拟案扩大授权。范围明确、依赖少的任务用短拟案,必要时只读核实。用 sansheng_workflow_submit 一次提交门下。')
} else if (seatId === 'menxia') {
lines.push('门下审核中书拟案,通过后直交尚书。允许一次说明原因的退回。需要进一步对齐时先用 sansheng_task_consult,会商不定交丞相。后续负责验收尚书汇总。')
lines.push('门下审核:对照交接中的范围与验收标准,批准前确认需求的 scope 和 acceptanceCriteria 已齐全;缺则说明原因退回中书补齐。发现实质问题时用 sansheng_workflow_review 说明原因退回,方案足够时用同一工具提交通过,系统接着交尚书。一次退回后仍有实质分歧时先会商,无法解决再交丞相。验收阶段使用 sansheng_workflow_accept。')
} else if (seatId === 'shangshu') {
lines.push('尚书依据门下通过的当前需求版本,通过 sansheng_workflow_dispatch 分派六部。各席结束后汇总真实结果交门下验收。')
lines.push('尚书调度:用 sansheng_workflow_dispatch 一次派发,沿用门下批准的范围和需求快照。单一交付由一个主责席承办,只有可独立推进的交付才拆给多席。执行结束后用 sansheng_workflow_summarize 提交真实结果。')
} else if (['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].includes(seatId)) {
lines.push('六部在尚书下派的范围内工作,必要时用 sansheng_task_consult 与同一流程任务的其他执行席协调。用 sansheng_task_report 回报真实文件和验证结果。')
lines.push('六部按下派范围执行,必要时与参与席会商。结束时用 sansheng_task_report 提交一次终态回报,完成附文件和验证结果,失败附具体阻塞。')
}
}
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')

View File

@ -12,44 +12,25 @@ export async function deliverToSeat(host, input = {}) {
return createSeatDelivery({ host }).deliverToSeat(input)
}
export function createSeatDelivery({ host = {}, now = () => Date.now() } = {}) {
const clock = typeof now === 'function' ? now : () => Number(now)
const attempts = new Map() // attemptId -> record
function attemptOf(attemptId, patch = {}) {
const previous = attempts.get(attemptId) ?? { attemptId, createdAt: clock() }
const next = { ...previous, ...patch, updatedAt: clock() }
attempts.set(attemptId, next)
return { ...next }
}
// 发送结果只有三类:
// sent followup 与 flush 都完成;
// not-sent 从未调用 followup(会话不可用、领取失效、Agent 变更、建消息失败),可安全重试;
// unknown 调用过 followup 或 flush 抛错,结果未知,只能人工核对后显式重投。
export function createSeatDelivery({ host = {} } = {}) {
async function deliverToSeat(input = {}) {
const sessionId = cleanText(input.sessionId)
const attemptId = cleanText(input.attemptId) || randomUUID()
const deliveryId = cleanText(input.deliveryId) || null
const attemptId = cleanText(input.attemptId) || randomUUID()
const sourceKind = cleanText(input.sourceKind) || 'sansheng-task'
if (!sessionId) throw new SeatDeliveryError('sansheng/invalid', '缺少 sessionId')
let resolved
try { resolved = await host.sessionController?.resolveAgent?.(sessionId) } catch (error) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: error?.message ?? String(error) })
return { ok: false, status: 'unknown', reason: 'resolve-failed', error: error?.message ?? String(error), attemptId }
return { ok: false, status: 'not-sent', reason: 'resolve-failed', error: error?.message ?? String(error), attemptId, deliveryId }
}
if (!resolved || ('error' in resolved && resolved.error)) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: 'session-unavailable' })
return { ok: false, status: 'unknown', reason: 'session-unavailable', attemptId }
return { ok: false, status: 'not-sent', reason: 'session-unavailable', attemptId, deliveryId }
}
const agent = resolved.agent
// 调用方在 resolveAgent 返回后完成唯一一次领取;领取失败不得投递。
if (typeof input.verifyClaim === 'function' && !(await input.verifyClaim())) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: 'claim-changed' })
return { ok: false, status: 'unknown', reason: 'claim-changed', attemptId }
}
// mutate 后无 await 的同步身份复核。
if (host.agents?.get?.(sessionId) !== agent) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: 'agent-changed' })
return { ok: false, status: 'unknown', reason: 'agent-changed', attemptId }
}
attemptOf(attemptId, { state: 'queued', deliveryId })
const content = [{ type: 'text', text: cleanText(input.text) }]
const source = internalSource(sourceKind, { seatId: input.seatId, taskId: input.taskId, reportId: input.reportId })
let message
@ -57,31 +38,30 @@ export function createSeatDelivery({ host = {}, now = () => Date.now() } = {}) {
const factory = typeof host.createUserMessage === 'function' ? host.createUserMessage : null
message = factory ? await Promise.resolve(factory({ content, source })) : { role: 'user', content, source }
} catch (error) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: error?.message ?? String(error) })
return { ok: false, status: 'unknown', reason: 'message-factory-failed', error: error?.message ?? String(error), attemptId }
return { ok: false, status: 'not-sent', reason: 'message-factory-failed', error: error?.message ?? String(error), attemptId, deliveryId }
}
// 最后一个 await 之后同步复核:Agent 未被替换、领取仍属于本次尝试,紧接着 followup。
if (host.agents?.get?.(sessionId) !== agent) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: 'agent-changed-before-followup' })
return { ok: false, status: 'unknown', reason: 'agent-changed-before-followup', attemptId }
return { ok: false, status: 'not-sent', reason: 'agent-changed', attemptId, deliveryId }
}
if (typeof input.verifyClaim === 'function' && !input.verifyClaim()) {
return { ok: false, status: 'not-sent', reason: 'claim-changed', attemptId, deliveryId }
}
if (typeof agent?.followup !== 'function') {
return { ok: false, status: 'not-sent', reason: 'followup-unavailable', attemptId, deliveryId }
}
try {
if (typeof agent.followup !== 'function') throw new SeatDeliveryError('sansheng/delivery-failed', 'Agent 不支持 followup')
await agent.followup(message)
} catch (error) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: error?.message ?? String(error) })
return { ok: false, status: 'unknown', reason: 'followup-failed', error: error?.message ?? String(error), attemptId }
return { ok: false, status: 'unknown', reason: 'followup-failed', error: error?.message ?? String(error), attemptId, deliveryId }
}
try {
if (typeof host.sessions?.flush === 'function') await host.sessions.flush(sessionId)
} catch (error) {
attemptOf(attemptId, { state: 'unknown', deliveryId, error: 'flush-failed' })
return { ok: false, status: 'unknown', reason: 'flush-failed', error: error?.message ?? String(error), attemptId }
return { ok: false, status: 'unknown', reason: 'flush-failed', error: error?.message ?? String(error), attemptId, deliveryId }
}
attemptOf(attemptId, { state: 'sent', deliveryId, sentAt: clock() })
return { ok: true, status: 'sent', attemptId, deliveryId }
}
function attempt(attemptId) { return attempts.get(attemptId) ?? null }
return { deliverToSeat, attempt, attempts }
}
return { deliverToSeat }
}

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,17 @@ function normalizeProjects(state) {
if (!Array.isArray(project.artifacts)) project.artifacts = []
if (!Array.isArray(project.requirements)) project.requirements = []
if (!Array.isArray(project.approvals)) project.approvals = []
if (!Array.isArray(project.cards)) project.cards = []
if (!Array.isArray(project.deliberations)) project.deliberations = []
if (!Number.isFinite(project.deliberationSeq)) project.deliberationSeq = 0
if (!Array.isArray(project.provinceRuns)) project.provinceRuns = []
if (project.avatars === null || typeof project.avatars !== 'object' || Array.isArray(project.avatars)) project.avatars = {}
if (!Array.isArray(project.leadReports)) project.leadReports = []
if (!Array.isArray(project.secretaryRuns)) project.secretaryRuns = []
if (!Array.isArray(project.secretaryReports)) project.secretaryReports = []
if (!Array.isArray(project.requirementLog)) project.requirementLog = []
if (typeof project.secretarySessionId !== 'string' && project.secretarySessionId !== null && project.secretarySessionId !== undefined) project.secretarySessionId = null
if (typeof project.secretaryAgentId !== 'string' && project.secretaryAgentId !== null && project.secretaryAgentId !== undefined) project.secretaryAgentId = null
if (project.commandLedgers === null || typeof project.commandLedgers !== 'object' || Array.isArray(project.commandLedgers)) project.commandLedgers = {}
if (!Number.isFinite(project.taskSeq)) project.taskSeq = 0
if (!Number.isFinite(project.artifactSeq)) project.artifactSeq = 0
@ -143,7 +153,16 @@ export class SanshengStore {
await mkdir(dirname(this.file), { recursive: true })
const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp`
await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf8')
await rename(tmp, this.file)
// Windows 上杀毒/索引可能短暂占用刚写完的临时文件,rename 会 EPERM;短重试后仍失败才报错。
for (let attempt = 0; ; attempt += 1) {
try {
await rename(tmp, this.file)
return
} catch (error) {
if (attempt >= 4) throw error
await new Promise(resolve => setTimeout(resolve, 15 * (attempt + 1)))
}
}
}
// 确保项目记录存在;已存在则只补空字段,不覆盖既有会话/配置。

View File

@ -65,12 +65,12 @@ function actorOf(located) {
return { seatId: located.seatId, sessionId: located.sessionId }
}
function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
function seatToolDefinitions({ store, service, turnCommands, leadBackground, leadSecretaries, provinceAgents }) {
const definitions = []
definitions.push({
name: 'sansheng_requirement_upsert',
description: '丞相专用:把与用户商讨出的需求整理进需求清单。新增或更新同一个需求条目都不会创建任务、不会派工;用户同意下派后才会进入中书省。条目包含判断、范围、非目标、验收标准、风险/依赖/待补信息。',
description: '丞相专用:把与用户商讨出的需求整理进需求清单。新增或更新同一个需求条目都不会创建任务、不会派工;用户明确同意下派后才会进入中书省。下派只需标题和用户原话;范围、非目标、验收标准可以留空,由中书拟案补齐。judgement 明确 not_now 时暂时阻止下派。',
parameters: {
type: 'object',
properties: {
@ -81,9 +81,9 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
originalText: { type: 'string', description: '用户原始要求,尽量保留原话' },
judgement: { type: 'string', enum: ['can_do', 'needs_discussion', 'not_now'], description: '丞相判断:可立项 / 需商讨 / 暂不可做' },
judgementReason: { type: 'string', description: '判断理由' },
scope: { type: 'string', description: '范围(可发布必填)' },
nonGoals: { type: 'string', description: '非目标' },
acceptanceCriteria: { type: 'string', description: '验收标准(可发布必填)' },
scope: { type: 'string', description: '范围;可留空,由中书拟案补齐,用户已确认的保留' },
nonGoals: { type: 'string', description: '非目标;可留空,由中书拟案补齐' },
acceptanceCriteria: { type: 'string', description: '验收标准;可留空,由中书拟案补齐,用户已确认的保留' },
risks: { type: 'string', description: '风险' },
dependencies: { type: 'string', description: '依赖' },
missingInfo: { type: 'string', description: '待补信息' },
@ -116,22 +116,21 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
definitions.push({
name: 'sansheng_requirement_publish',
description: '丞相专用:用户明确同意下派,或回答已授权下派的需求的澄清问题时使用。保存后在后台交中书。讨论中不得调用。',
description: '丞相专用:用户明确同意下派,或回答已授权下派的需求的澄清问题时使用。需求有标题和用户原话、judgement 不是 not_now 即可下派;范围与验收标准可留空,由中书拟案补齐。识别「发布009吧」为下派 R-009。讨论中不得调用。',
parameters: {
type: 'object',
properties: {
requirementId: { type: 'string', description: '需求 id,如 R-001' },
expectedRevision: { type: 'number', description: '要下派的最新 revision' },
authorization: { type: 'string', enum: ['direct', 'clarified'], description: '当前用户直接同意用 direct,当前用户回答此前已授权的澄清用 clarified' },
targetSeatId: { type: 'string', enum: ['zhongshu'], description: '只能发布给中书省' },
targetSeatId: { type: 'string', enum: ['zhongshu'], description: '兼容旧调用,省略时自动交中书' },
},
required: ['targetSeatId'],
},
async execute(args = {}, exec) {
let located
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以发布需求' }
const targetSeatId = text(args.targetSeatId)
const targetSeatId = args.targetSeatId === undefined ? 'zhongshu' : text(args.targetSeatId)
if (targetSeatId !== 'zhongshu') {
return { ok: false, reason: 'workflow-route-forbidden', error: `丞相只能把需求发布给中书省,不能直接派给「${labelOf(targetSeatId) || targetSeatId}」。未创建任务、未写入共识、未投递任何会话。` }
}
@ -152,12 +151,18 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
definitions.push({
name: 'sansheng_workflow_submit',
description: '中书省专用:把拟案提交门下省审核。拟案阶段只能只读调查,不能修改工程、不能向六部派工。',
description: '中书省专用:把拟案提交门下省审核。需求缺少范围、非目标、验收标准或风险时,用结构化字段补入任务快照;只补空缺,用户已确认的字段保持原样,需求正文和版本不变。门下退回后可修订中书自己补的字段,省略字段保留已有快照值。拟案阶段只能只读调查,不能修改工程、不能向六部派工。',
parameters: {
type: 'object',
properties: {
taskId: { type: 'string', description: '流程任务 id' },
draft: { type: 'string', description: '完整拟案:目标、范围、非目标、验收标准、风险、执行步骤' },
scope: { type: 'string', description: '范围;仅在需求该字段为空时补入任务快照,退回重提可修订' },
nonGoals: { type: 'string', description: '非目标;仅在需求该字段为空时补入任务快照,退回重提可修订' },
acceptanceCriteria: { type: 'string', description: '验收标准;仅在需求该字段为空时补入任务快照,退回重提可修订' },
risks: { type: 'string', description: '风险;仅在需求该字段为空时补入任务快照,退回重提可修订' },
dependencies: { type: 'string', description: '依赖;仅在需求该字段为空时补入任务快照,退回重提可修订' },
missingInfo: { type: 'string', description: '待补信息;仅在需求该字段为空时补入任务快照,退回重提可修订' },
},
required: ['taskId', 'draft'],
},
@ -165,14 +170,22 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
let located
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
try {
return await service.workflowSubmitDraft(located.project.id, text(args.taskId), { draft: text(args.draft) }, actorOf(located))
return await service.workflowSubmitDraft(located.project.id, text(args.taskId), {
draft: text(args.draft),
scope: text(args.scope),
nonGoals: text(args.nonGoals),
acceptanceCriteria: text(args.acceptanceCriteria),
risks: text(args.risks),
dependencies: text(args.dependencies),
missingInfo: text(args.missingInfo),
}, actorOf(located))
} catch (error) { return failure(error) }
},
})
definitions.push({
name: 'sansheng_workflow_review',
description: '门下审核中书拟案。通过直接交尚书。允许一次带明确原因的退回,仍有实质分歧时会商或交丞相。',
description: '门下审核中书拟案。批准前需求必须有范围与验收标准,缺则由中书在拟案中补齐后再批准。通过直接交尚书。允许一次带明确原因的退回,仍有实质分歧时会商或交丞相。',
parameters: {
type: 'object',
properties: {
@ -294,8 +307,8 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
let located
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
const { project } = located
const tasks = (project.tasks ?? []).map(task => ({ ...task, targetLabel: labelOf(task.ownerSeatId) }))
return { ok: true, projectId: project.id, tasks }
const { tasks } = await service.tasks(project.id)
return { ok: true, projectId: project.id, tasks: tasks.map(task => ({ ...task, targetLabel: labelOf(task.ownerSeatId) })) }
},
})
@ -366,6 +379,32 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
},
})
if (typeof service?.deliberationSpeak === 'function') definitions.push({
name: 'sansheng_deliberation_speak',
description: '三省议政专用:只在当前议政轮到本席时提交本轮发言。发言会自动落进议政转录;不要在这里发布、批准或派工。',
parameters: {
type: 'object',
properties: {
deliberationId: { type: 'string', description: '议政编号,如 D-001' },
round: { type: 'number', description: '当前轮次' },
text: { type: 'string', description: '本轮发言,白话说明本省判断和理由' },
stance: { type: 'string', enum: ['agree', 'dissent', 'neutral'], description: '同意 / 有分歧 / 未表态' },
pending: { type: 'boolean', description: '是否仍有待决问题' },
openIssues: { type: 'string', description: '未决点;没有就留空' },
},
required: ['deliberationId', 'round', 'text'],
},
async execute(args, exec) {
try {
const located = await locateSeat(service, exec)
return {
ok: true,
...await service.deliberationSpeak(located.project.id, text(args.deliberationId), args, actorOf(located), exec?.callId),
}
} catch (error) { return failure(error) }
},
})
definitions.push({
name: 'sansheng_task_decision',
description: '丞相专用:无法按用户已知偏好解决实质分歧时,将问题及选项放入「待你处理」。',
@ -398,6 +437,78 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
},
})
if (leadSecretaries) definitions.push({
name: 'sansheng_lead_secretary',
description: '丞相专用。启动一位项目主簿或记室在后台工作:zhongshu、menxia、shangshu 分别对接中书/门下/尚书,requirement 是记室,负责记录用户需求。工具只等待宿主接收,不阻塞当前聊天;主簿或记室结束后回报。主簿与记室只读和记录,不发布、不批准、不派工。',
parameters: {
type: 'object',
properties: {
role: { type: 'string', enum: ['zhongshu', 'menxia', 'shangshu', 'requirement'], description: '主簿或记室角色' },
brief: { type: 'string', description: '交给主簿或记室的后台工作说明,附上用户原话更佳' },
},
required: ['role', 'brief'],
},
async execute(args, exec) {
try { return await leadSecretaries.start(exec, args) } catch (error) { return failure(error) }
},
})
if (provinceAgents) definitions.push({
name: 'sansheng_order',
description: '丞相专用。把一条指令交给中书接令子 Agent:工具先返回回执(谁下的、关联任务或需求版本),接令核对后把用户原话和要点交回中书主席。不阻塞当前对话,不直接派工。',
parameters: {
type: 'object',
properties: {
instruction: { type: 'string', description: '要下达给中书的指令,尽量保留用户原话和关键要求' },
taskId: { type: 'string', description: '关联任务 id,可选' },
requirementId: { type: 'string', description: '关联需求 id,可选' },
},
required: ['instruction'],
},
async execute(args, exec) {
let located
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以下达中书接令' }
try {
return { ok: true, ...await service.startOrder(located.project.id, args, actorOf(located)) }
} catch (error) { return failure(error) }
},
})
if (typeof service?.cardCreate === 'function') definitions.push({
name: 'sansheng_card',
description: '丞相专用。在当前丞相会话的消息流里挂一张非阻塞卡片,用户可以在聊天继续时点选,也可以回头答较早的卡;回答会回到本轮。问题卡提供 2 到 5 个选项;审批卡必须带 approvalId,选项只能是 allow/reject,模型只解释不代批,用户点选后仍回到原审批请求。',
parameters: {
type: 'object',
properties: {
kind: { type: 'string', enum: ['question', 'approval'], description: '问题卡或审批卡' },
title: { type: 'string', description: '卡片标题,零基础白话' },
body: { type: 'string', description: '卡片正文:发生了什么、影响、为什么需要决定;审批卡还要写同意/拒绝的后果' },
options: {
type: 'array',
description: '用户可选项;问题卡 2 到 5 个,审批卡可省略(默认同意/拒绝)',
items: {
type: 'object',
properties: {
label: { type: 'string' }, value: { type: 'string' }, description: { type: 'string' },
},
required: ['label', 'value'],
},
},
approvalId: { type: 'string', description: '审批卡的原始审批 id' },
},
required: ['kind', 'title', 'body'],
},
async execute(args = {}, exec) {
let located
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以挂卡片' }
try {
return await service.cardCreate(located.project.id, { ...args, callId: exec?.callId }, actorOf(located))
} catch (error) { return failure(error) }
},
})
for (const definition of definitions) definition.output = seatToolOutput
return definitions
}
@ -476,8 +587,8 @@ function buildSeatToolGuard(store, sessionId) {
}
}
export function installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground }) {
const defs = createSeatToolDefinitions({ store, service, turnCommands, leadBackground })
export function installSeatTools(ctx, { store, service, provisioner, turnCommands, leadBackground, leadSecretaries, provinceAgents }) {
const defs = createSeatToolDefinitions({ store, service, turnCommands, leadBackground, leadSecretaries, provinceAgents })
// sessionId -> { agent, disposers: Map<name, dispose>, registered: Set<name> }
const installs = new Map()
// 已绑定、但 agent 或工具系统尚未就绪的会话;等下一次席位事件/重扫再补装。
@ -518,7 +629,13 @@ export function installSeatTools(ctx, { store, service, provisioner, turnCommand
if (!sessionId) return false
const located = findSeat(sessionId)
if (!located) return false
const seatDefs = located.seatId === 'lead' ? defs : defs.filter(def => def.name !== 'sansheng_lead_background')
const sanshengSeat = SEAT_GROUPS.sansheng.includes(located.seatId)
const seatDefs = defs.filter(def => {
// 议政发言只给三省代表,丞相和六部都不挂。
if (def.name === 'sansheng_deliberation_speak') return sanshengSeat
if (located.seatId === 'lead') return true
return def.name !== 'sansheng_lead_background' && def.name !== 'sansheng_lead_secretary' && def.name !== 'sansheng_card' && def.name !== 'sansheng_order'
})
const agentTools = agent.ctx?.tools
if (!agentTools || typeof agentTools.register !== 'function') {
retry.add(sessionId)

View File

@ -0,0 +1,123 @@
const OPERATIONS = new Map([
['sansheng_workflow_submit', ['zhongshu_draft', '提交中书拟案']],
['sansheng_workflow_review', ['menxia_review', '提交门下审核']],
['sansheng_workflow_dispatch', ['shangshu_dispatch', '尚书派工']],
['sansheng_workflow_summarize', ['department_exec', '提交尚书汇总']],
['sansheng_workflow_accept', ['menxia_acceptance', '提交门下验收']],
['sansheng_workflow_deliver', ['lead_delivery', '提交交付']],
['sansheng_task_report', ['department_exec', '提交执行结果']],
])
const APPROVAL_FAILURES = new Map([
['APPROVAL_CANCELLED', '宿主审批已取消'],
['APPROVAL_REJECTED', '用户拒绝了本次宿主审批'],
['APPROVAL_UNAVAILABLE', '宿主审批通道不可用'],
['AUTO_REVIEW_DENIED', '宿主自动审查拒绝了本次操作'],
['AUTO_REVIEW_FAILED', '宿主自动审查未完成'],
])
const APPROVAL_OUTCOMES = new Map([
['cancelled', 'APPROVAL_CANCELLED'], ['rejected', 'APPROVAL_REJECTED'], ['unavailable', 'APPROVAL_UNAVAILABLE'],
])
function callArguments(value) {
if (typeof value !== 'string') return value
try { return JSON.parse(value) } catch { return null }
}
function matchesTask(project, task, observed) {
return task && !['done', 'failed', 'cancelled', 'reconfirm'].includes(task.status)
&& task.stage === observed.stage && task.ownerSeatId === observed.seatId
&& project.seats?.[observed.seatId]?.sessionId === observed.sessionId
&& task.requirementRevision === observed.revision
&& project.requirements?.some(req => req.id === task.requirementId && req.revision === observed.revision)
&& (task.lastTransitionId ?? null) === observed.transitionId
&& (task.deliveryId ?? null) === observed.deliveryId
}
export function workflowBlockageOf(project, task) {
const block = task.workflowBlockage
return block && matchesTask(project, task, block) ? block : null
}
export function installWorkflowBlockage(ctx, { store, agents }) {
if (typeof ctx.on !== 'function') return () => {}
const calls = new WeakMap()
let disposed = false
function writeBlockage(agent, call, code, at) {
const reason = APPROVAL_FAILURES.get(code)
if (!call || !reason || disposed) return
const activeTask = project => project?.tasks?.find(task => task.id === call.taskId)
const project = store.get(call.projectId)
if (!matchesTask(project, activeTask(project), call)) return
return store.mutate(state => {
if (disposed || agents?.get?.(call.sessionId) !== agent) return
const currentProject = state.projects[call.projectId]
const task = activeTask(currentProject)
if (!matchesTask(currentProject, task, call)) return
const previous = workflowBlockageOf(currentProject, task)
if (previous && previous.seq >= call.seq) return
const { projectId, taskId, ...identity } = call
task.workflowBlockage = { ...identity, code, reason, at }
currentProject.updatedAt = Date.now()
currentProject.revision = (currentProject.revision ?? 0) + 1
}).catch(error => console.warn('[sansheng] 无法记录任务审批阻塞', error?.message ?? error))
}
const onSession = ctx.on('session/event', (session, event) => {
if (disposed || !session || !event) return
const agent = agents?.get?.(session.id)
if (agent?.session !== session) return
const { type, data, seq } = event
if (type === 'turn/start') {
calls.set(agent, { tools: new Map(), approvals: new Map() })
return
}
if (type === 'turn/end') {
calls.delete(agent)
return
}
const turn = calls.get(agent)
if (!turn || !data) return
if (type === 'tool/call' || type === 'tool/ptc-dispatch-start') {
const operation = OPERATIONS.get(data.name)
if (!operation || !Number.isSafeInteger(seq)) return
const [stage, label] = operation
const args = callArguments(data.arguments)
const located = store.seatBySession(session.id)
const task = located?.project.tasks?.find(item => item.id === args?.taskId)
const callId = data.subCallId ?? data.callId
if (!task || !callId || task.stage !== stage || task.ownerSeatId !== located.seatId) return
if (data.name === 'sansheng_task_report' && (task.kind !== 'execution' || !['done', 'failed'].includes(args.status))) return
turn.tools.set(callId, {
projectId: located.project.id, taskId: task.id, stage, label, tool: data.name, seq, callId,
seatId: located.seatId, sessionId: session.id, revision: task.requirementRevision,
transitionId: task.lastTransitionId ?? null, deliveryId: task.deliveryId ?? null,
})
} else if (type === 'approval/asked') {
const call = turn.tools.get(data.callId)
if (call?.tool === data.toolName) turn.approvals.set(data.id, call)
} else if (type === 'approval/decided') {
const call = turn.approvals.get(data.id)
turn.approvals.delete(data.id)
const code = APPROVAL_OUTCOMES.get(data.outcome)
if (call && code) {
turn.tools.delete(call.callId)
return writeBlockage(agent, call, code, event.time ?? Date.now())
}
}
})
const onResult = ctx.on('tools/result', (exec, result) => {
const agent = exec?.agent
if (!agent?.session || agents?.get?.(agent.session.id) !== agent) return
const turn = calls.get(agent)
const call = turn?.tools.get(exec.callId)
if (!call || call.tool !== exec.name) return
turn.tools.delete(exec.callId)
return writeBlockage(agent, call, result?.error?.info?.code, Date.now())
})
return () => { disposed = true; onSession?.(); onResult?.() }
}

View File

@ -13,12 +13,14 @@ export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready',
export const TASK_STATUS = Object.freeze(['draft', 'dispatched', 'running', 'prepared', 'done', 'cancelled', 'failed', 'waiting_user', 'returned', 'reconfirm'])
// 需求清单:商讨中 / 待发布 / 已发布 / 已退回 / 已取消。
export const REQUIREMENT_STATUS = Object.freeze(['discussing', 'ready', 'published', 'returned', 'cancelled'])
export const DELIBERATION_STATUS = Object.freeze(['running', 'concluded', 'stopped'])
// 流程阶段:只由宿主服务推进,模型不能跳阶段。
export const WORKFLOW_STAGE = Object.freeze(['zhongshu_draft', 'menxia_review', 'awaiting_execution_approval', 'shangshu_dispatch', 'department_exec', 'shangshu_summary', 'menxia_acceptance', 'lead_delivery', 'delivered', 'reconfirm'])
const SEAT_STATUS_SET = new Set(SEAT_STATUS)
const PROJECT_STATUS_SET = new Set(PROJECT_STATUS)
const TASK_STATUS_SET = new Set(TASK_STATUS)
const DELIBERATION_STATUS_SET = new Set(DELIBERATION_STATUS)
function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v) }
function isStr(v) { return typeof v === 'string' && v.trim() !== '' }
@ -78,6 +80,17 @@ export function emptyProject({ id, name, workspaceId = null, path = null, now =
artifacts: [],
requirements: [],
approvals: [],
cards: [],
// 议政:项目级独立转录,不写进任务会商;旧数据没有时按空数组处理。
deliberations: [],
deliberationSeq: 0,
provinceRuns: [],
avatars: {},
secretaryRuns: [],
secretaryReports: [],
requirementLog: [],
secretarySessionId: null,
secretaryAgentId: null,
taskSeq: 0,
artifactSeq: 0,
requirementSeq: 0,
@ -97,7 +110,7 @@ export function emptyTask({ id, title = '', goal = '', requirement = '', ownerSe
blockedReason: '', draft: '', reviewNote: '', summary: '', deliveryNote: '',
createdAt: now, updatedAt: now, dispatchedAt: null,
contextRevision: 0, contextHash: '', decisionIds: [], sourceRefs: [],
deliveryId: null, deliveryState: 'none', deliveryOwner: null, deliveryAttemptAt: null,
deliveryId: null, deliveryState: 'none', deliveryStatus: null, deliveryOwner: null, deliveryAttemptAt: null,
deliveryAttemptId: null, sendingOwner: null, sendingAt: null, lastTransitionId: null,
contextSyncState: 'none',
result: null, resultAt: null, resultSessionId: null, reportStatus: 'none',
@ -108,7 +121,7 @@ export function emptyRequirement({ id, title = '', summary = '', originalText =
return {
id, title, summary, originalText, judgement: 'needs_discussion', judgementReason: '',
scope: '', nonGoals: '', acceptanceCriteria: '', risks: '', dependencies: '', missingInfo: '',
revision: 1, status: 'discussing', blockedReason: '等待与用户商讨并补全发布信息',
revision: 1, status: 'discussing', blockedReason: '待丞相整理;空白或 needs_discussion 可由中书拟案补齐范围与验收标准',
createdAt: now, updatedAt: now, publishedRevision: null, publishedAt: null, cancelledAt: null,
}
}
@ -175,6 +188,16 @@ function projectProblem(project, id) {
if (!isStr(approval.id)) return `项目 ${id} 的 approvals[${index}] 缺少 id`
if (!['approved', 'invalidated'].includes(approval.status)) return `项目 ${id} 的批准 ${approval.id} 状态非法`
}
if (project.cards !== undefined && !Array.isArray(project.cards)) return `项目 ${id} 的 cards 不是数组`
if (project.deliberations !== undefined && !Array.isArray(project.deliberations)) return `项目 ${id} 的 deliberations 不是数组`
for (const [index, record] of (project.deliberations ?? []).entries()) {
if (!isObject(record)) return `项目 ${id} 的 deliberations[${index}] 不是对象`
if (!isStr(record.id)) return `项目 ${id} 的 deliberations[${index}] 缺少 id`
if (!DELIBERATION_STATUS_SET.has(record.status)) return `项目 ${id} 的议政 ${record.id} 状态非法:${String(record.status)}`
if (!Number.isFinite(record.round)) return `项目 ${id} 的议政 ${record.id} 轮次非法`
if (record.speeches !== undefined && !Array.isArray(record.speeches)) return `项目 ${id} 的议政 ${record.id} 发言不是数组`
}
if (project.deliberationSeq !== undefined && !Number.isFinite(project.deliberationSeq)) return `项目 ${id} 的 deliberationSeq 非法`
if (project.tasks !== undefined && !Array.isArray(project.tasks)) return `项目 ${id} 的 tasks 不是数组`
for (const [index, task] of (project.tasks ?? []).entries()) {
if (!isObject(task)) return `项目 ${id} 的 tasks[${index}] 不是对象`
@ -183,6 +206,13 @@ function projectProblem(project, id) {
}
if (project.memory !== undefined && (project.memory === null || typeof project.memory !== 'object' || Array.isArray(project.memory))) return `项目 ${id} 的 memory 非法`
if (project.leadReports !== undefined && !Array.isArray(project.leadReports)) return `项目 ${id} 的 leadReports 不是数组`
for (const key of ['secretaryRuns', 'secretaryReports', 'requirementLog', 'provinceRuns']) {
if (project[key] !== undefined && !Array.isArray(project[key])) return `项目 ${id} 的 ${key} 不是数组`
}
if (project.avatars !== undefined && (project.avatars === null || typeof project.avatars !== 'object' || Array.isArray(project.avatars))) return `项目 ${id} 的 avatars 非法`
for (const key of ['secretarySessionId', 'secretaryAgentId']) {
if (project[key] !== undefined && project[key] !== null && typeof project[key] !== 'string') return `项目 ${id} 的 ${key} 非法`
}
if (project.commandLedgers !== undefined && (project.commandLedgers === null || typeof project.commandLedgers !== 'object' || Array.isArray(project.commandLedgers))) return `项目 ${id} 的 commandLedgers 非法`
if (project.artifacts !== undefined && !Array.isArray(project.artifacts)) return `项目 ${id} 的 artifacts 不是数组`
for (const [index, artifact] of (project.artifacts ?? []).entries()) {

View File

@ -14,8 +14,8 @@ test('approval-center:非十席调用 next,十席原生 outcome 被结清',
let nextCount = 0
assert.equal(await handler({ sessionId: 'other' }, async () => { nextCount += 1; return 'native' }), 'native')
assert.equal(nextCount, 1)
const waiting = handler({ sessionId: 's1', tool: 'bash' }, async () => ({ choice: 'allow' }))
assert.equal(await waiting, 'allow')
const waiting = handler({ agent: { session: { id: 's1' } }, toolName: 'bash' }, async () => 'allowed-once')
assert.equal(await waiting, 'allowed-once')
assert.equal(center.list('p1').length, 0)
})
@ -30,19 +30,29 @@ test('approval-center:open 同步应答不迟开 next,并发双答只一个
}
})
const waiting = handler({ sessionId: 's1', tool: 'bash' }, async () => { nextCount += 1; return 'native' })
assert.equal(await waiting, 'reject')
assert.equal(await waiting, 'rejected')
await Promise.resolve()
assert.equal(nextCount, 0, '先被工作台结清时不能迟开原生卡')
assert.throws(() => center.answer(entryId, { projectId: 'p1', seatId: 'gongbu', sessionId: 's1' }, 'allow'), error => error.code === 'sansheng/approval-stale')
})
test('工作台明确允许时返回宿主唯一认可的授权值', async () => {
const { center, handler } = makeCenter()
const waiting = handler({ agent: { session: { id: 's1' } }, toolName: 'sansheng_workflow_review' }, () => new Promise(() => {}))
await new Promise(resolve => setImmediate(resolve))
const [approval] = center.list('p1')
assert.equal(approval.tool, 'sansheng_workflow_review')
center.answer(approval.id, approval, 'allow')
assert.equal(await waiting, 'allowed-once')
})
test('approval-center:dispose 取消所有 pending', async () => {
const { center, handler } = makeCenter()
let nextCount = 0
const waiting = handler({ sessionId: 's1', tool: 'bash' }, async () => { nextCount += 1; return new Promise(() => {}) })
await new Promise(resolve => setImmediate(resolve))
center.dispose()
assert.deepEqual(await waiting, { cancelled: true })
assert.equal(await waiting, 'cancelled')
assert.equal(center.status().degraded, true)
assert.equal(nextCount, 1)
})

View File

@ -1,6 +1,7 @@
// 只测纯视图模型:绝不 import 会拉起 React 的 index.js。
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import {
buildWorkbenchView,
collectModelOptions,
@ -8,7 +9,16 @@ import {
UNCHOSEN_MODEL_LABEL,
} from '../src/client/workbench.js'
// 与 CONTRACT.md 一致:十席固定编制、两字显示名。
// 丞相会话卡片:只注册宿主公开的 tool.call.toolview,不碰底部输入框。
test('丞相会话卡片按工具名注册,并从项目 store 读取/回答', async () => {
const index = await readFile(new URL('../src/client/index.js', import.meta.url), 'utf8')
assert.match(index, /tool\.call\.toolview/)
assert.match(index, /key: 'sansheng_card'/)
const cards = await readFile(new URL('../src/client/cards.js', import.meta.url), 'utf8')
assert.match(cards, /cardGet/)
assert.match(cards, /cardAnswer/)
assert.doesNotMatch(cards, /<textarea|<input|textarea\(|input\(/)
})
const SEAT_ROWS = [
['lead', '丞相'],
['zhongshu', '中书'],

View File

@ -34,6 +34,18 @@ test('发布:唯一 ready 允许裸「发布」,同 seq 不可重放', async
assert.equal(replay.taskId, published.taskId)
})
test('发布009吧在多个待发布需求中只选中 R-009', async () => {
const { service } = await setupService()
const { project } = await service.open({ path: '/short-id', name: '短编号' })
for (let i = 1; i <= 9; i++) await readyRequirement(service, project.id, '需求 ' + i)
const input = { command: '没事的,我已经让别人修完了,发布009吧', commandRef: { seq: 1, messageId: 'm1' } }
const actor = { seatId: 'lead', sessionId: 'lead-session' }
await assert.rejects(() => service.requirementPublish(project.id, 'R-008', input, actor), { code: 'sansheng/requirement-conflict' })
const published = await service.requirementPublish(project.id, '', input, actor)
assert.equal(published.requirement.id, 'R-009')
assert.equal((await service.tasks(project.id)).tasks.length, 1)
})
test('发布:多个 ready 时裸「发布」拒绝并列出候选,不创建任务', async () => {
const { service } = await setupService()
const opened = await service.open({ path: '/ledger2', name: '台账项目二' })

View File

@ -11,7 +11,7 @@ export async function tempStateFile() {
export function createFakeHost(opts = {}) {
const sessions = new Map() // sessionId -> agent
const workspaces = new Map() // id -> { id, name, path }
const calls = { create: [], resolve: [], selectModel: 0, agentSelect: [], createAt: [], prompt: [], rename: [] }
const calls = { create: [], resolve: [], selectModel: 0, agentSelect: [], createAt: [], prompt: [], followup: [], createUserMessage: [], flush: [], rename: [], cancel: [] }
const control = {
failCreateOrder: null, // 第 N 次 create 抛错(1 起)
mismatchCreateOrder: null, // 第 N 次 create 返回另一个 ID
@ -21,6 +21,7 @@ export function createFakeHost(opts = {}) {
failures: [],
},
validRoutes: opts.validRoutes ?? new Set(['deepseek/deepseek-chat', 'deepseek/deepseek-reasoner']),
followupHook: null, // async (sessionId, message) => {},测试用来暂停/观察发送
}
let createCount = 0
@ -44,6 +45,13 @@ export function createFakeHost(opts = {}) {
current() { return agent._selection },
select(selection) { agent._selection = selection; calls.agentSelect.push({ sessionId, selection }) },
},
async followup(message) {
calls.followup.push({ sessionId, message })
if (typeof control.followupHook === 'function') await control.followupHook(sessionId, message)
},
cancel(reason) {
calls.cancel.push({ sessionId, reason })
},
}
sessions.set(sessionId, agent)
}
@ -103,7 +111,16 @@ export function createFakeHost(opts = {}) {
let route = null
const connection = { fetch: { register(def) { route = def; return () => {} } } }
const host = { workspaceRegistry, sessionController, agents, llm, systemPrompt }
const createUserMessage = async ({ content, source } = {}) => {
const message = { role: 'user', content, source }
calls.createUserMessage.push(message)
return message
}
const sessionsService = {
async flush(sessionId) { calls.flush.push(sessionId) },
}
const host = { workspaceRegistry, sessionController, agents, llm, systemPrompt, createUserMessage, sessions: sessionsService }
const ctx = {
workspaceRegistry, sessionController, agents, llm, systemPrompt, connection,
effect(fn) { const dispose = fn(); return dispose },

View File

@ -50,7 +50,7 @@ test('Grill 结果回写同一个需求:revision 递增且不产生任务副
assert.equal(created.ok, true, created.error)
assert.equal(created.created, true)
assert.equal(created.requirement.revision, 1)
assert.equal(created.requirement.status, 'discussing')
assert.equal(created.requirement.status, 'ready', '缺少范围与验收不再阻止下派,由中书拟案补齐')
const id = created.requirement.id
const updated = await run(env, 'sansheng_requirement_upsert', {

View File

@ -1,6 +1,7 @@
import { SanshengStore } from '../src/host/store.js'
import { createProvisioner } from '../src/host/provision.js'
import { SanshengService } from '../src/host/service.js'
import { createSeatDelivery } from '../src/host/seat-delivery.js'
import { createFakeHost, tempStateFile } from './fake-ctx.js'
export async function setupService(opts = {}) {
@ -9,8 +10,9 @@ export async function setupService(opts = {}) {
await store.load()
const fake = opts.fake ?? createFakeHost(opts)
const provisioner = createProvisioner({ store, host: fake.host })
const service = new SanshengService({ store, host: fake.host, provisioner })
return { file, store, fake, provisioner, service }
const seatDelivery = createSeatDelivery({ host: fake.host })
const service = new SanshengService({ store, host: fake.host, provisioner, seatDelivery })
return { file, store, fake, provisioner, service, seatDelivery }
}
export function seatById(view, id) {

View File

@ -48,7 +48,7 @@ test('项目共识:注入到部门 system prompt,不依赖任务文字', asy
assert.match(text, /自动化测试通过/)
})
test('派工:把共识拼进 prompt,记录上下文版本与投递回执', async () => {
test('派工:把共识拼进 followup,记录上下文版本与投递回执', async () => {
const { service, fake } = await setupService({ prompt: true })
const opened = await service.open({ path: '/memory-dispatch', name: '派工项目' })
const projectId = opened.project.id
@ -63,8 +63,8 @@ test('派工:把共识拼进 prompt,记录上下文版本与投递回执', a
assert.equal(dispatched.delivered, true)
assert.equal(dispatched.task.contextRevision, saved.memory.revision)
assert.equal(dispatched.task.deliveryState, 'accepted')
assert.equal(fake.calls.prompt.length, 1)
const text = fake.calls.prompt[0].content[0].text
assert.equal(fake.calls.followup.length, 1)
const text = fake.calls.followup[0].message.content[0].text
assert.match(text, /项目共识 v1/)
assert.match(text, /不能动线上数据库/)
assert.match(text, /任务文字故意不写硬约束/)

View File

@ -39,7 +39,7 @@ test('approval-center:非十席直接 next;十席可 list/answer 且只接
assert.equal(list[0].detail.secret, undefined)
assert.throws(() => center.answer(list[0].id, { projectId: 'p1', seatId: 'hubu', sessionId: 's1' }, 'allow'), error => error.code === 'sansheng/approval-forbidden')
center.answer(list[0].id, { projectId: 'p1', seatId: 'gongbu', sessionId: 's1' }, 'allow')
assert.equal(await waiting, 'allow')
assert.equal(await waiting, 'allowed-once')
assert.equal(center.list('p1').length, 0)
})
@ -86,3 +86,31 @@ test('当前轮授权只接受首步认领并落盘的 Web 用户消息', async
tracker.dispose()
assert.equal(listeners.size, 0)
})
test('当前轮授权只认宿主落盘正文:两份正文不一致仍可下派,空正文不算命令', async () => {
const listeners = new Map()
const session = { id: 'lead-landed' }
const agent = { session }
let openTurnStartSeq = 4
const ctx = {
agents: { get: () => agent, turnBoundaryOf: () => ({ openTurnStartSeq }) },
on(name, fn) { listeners.set(name, fn); return () => listeners.delete(name) },
}
const tracker = createTurnCommands(ctx, { seatBySession: () => ({ seatId: 'lead' }) })
const preStep = listeners.get('agent/pre-step')
const event = listeners.get('session/event')
const queued = { id: 'm-9', role: 'user', source: { kind: 'user', rpcId: 'rpc-9', clientTimeZone: 'Asia/Shanghai' }, content: [{ type: 'text', text: '就按这个做' }] }
const landed = { ...queued, content: [{ type: 'text', text: '就按这个做,发布 R-002' }] }
const exec = { agent }
const next = () => ({ kind: 'enter' })
await preStep({ agent, messages: [queued] }, next)
event(session, { type: 'user/message', seq: 6, data: landed })
assert.deepEqual(tracker.read(exec), { text: '就按这个做,发布 R-002', messageId: 'm-9', seq: 6 })
event(session, { type: 'turn/end', seq: 7 })
openTurnStartSeq = 8
await preStep({ agent, messages: [queued] }, next)
event(session, { type: 'user/message', seq: 10, data: { ...landed, content: [{ type: 'text', text: ' ' }] } })
assert.equal(tracker.read(exec), null)
tracker.dispose()
})

View File

@ -51,6 +51,9 @@ test('丞相提示包含 Grill Me 规则,其他九席不注入', async () => {
assert.match(leadText, /expectedRevision/)
assert.match(leadText, /dispatchAfterClarification=true/)
assert.match(leadText, /authorization=clarified/)
assert.match(leadText, /sansheng_lead_secretary/)
assert.match(leadText, /零基础白话/)
assert.match(leadText, /sansheng-report/)
assert.doesNotMatch(leadText, /发布 R-xxx 给中书/)
for (const seatId of ['zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) {

View File

@ -2,10 +2,13 @@ import test from 'node:test'
import assert from 'node:assert/strict'
import { setupService, seatById } from './helpers.js'
import { createSeatToolDefinitions } from '../src/host/tools.js'
import { createTurnCommands } from '../src/host/message-source.js'
import { readFile } from 'node:fs/promises'
import { SanshengStore } from '../src/host/store.js'
import { SanshengService } from '../src/host/service.js'
import { createApiHandler } from '../src/host/api.js'
import { createApprovalCenter } from '../src/host/approval-center.js'
import { installWorkflowBlockage } from '../src/host/workflow-blockage.js'
async function setupGate() {
const env = await setupService({ prompt: true })
@ -86,38 +89,84 @@ test('1. 用户第一次提出想法:只整理需求清单,不创建执行
const req = await readyRequirement(env)
const tasks = await env.service.tasks(env.projectId)
assert.equal(tasks.tasks.length, 0, '需求清单不是任务')
assert.equal(env.fake.calls.prompt.length, 0, '不能自动投递任何部门会话')
assert.equal(env.fake.calls.followup.length, 0, '不能自动投递任何部门会话')
assert.equal(req.status, 'ready')
assert.equal(req.id, 'R-001')
})
test('丞相工具根据本轮用户原话发布短编号,内部回报不能借用授权', async () => {
const env = await setupGate()
for (let i = 1; i <= 9; i++) await readyRequirement(env, { title: '需求 ' + i })
const exec = execOf(env, 'lead')
const { agent } = exec
const listeners = new Map()
let boundary = 1
const commands = createTurnCommands({
agents: { get: id => env.fake.sessions.get(id), turnBoundaryOf: () => ({ openTurnStartSeq: boundary }) },
on(name, handler) { listeners.set(name, handler); return () => listeners.delete(name) },
}, env.store)
const publish = createSeatToolDefinitions({ service: env.service, turnCommands: commands })
.find(tool => tool.name === 'sansheng_requirement_publish')
const enter = () => ({ kind: 'enter' })
const human = {
id: 'human-009', role: 'user',
source: { kind: 'user', rpcId: 'rpc-009', clientTimeZone: 'Asia/Shanghai' },
content: [{ type: 'text', text: '没事的,我已经让别人修完了,发布009吧' }],
}
const internal = { ...human, id: 'report-009', source: { kind: 'sansheng-report' } }
await listeners.get('agent/pre-step')({ agent, messages: [internal] }, enter)
listeners.get('session/event')(agent.session, { type: 'user/message', seq: 2, data: internal })
const rejected = await publish.execute({ requirementId: 'R-009' }, exec)
assert.equal(rejected.reason, 'sansheng/current-user-message-unavailable')
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
listeners.get('session/event')(agent.session, { type: 'turn/end', seq: 3 })
boundary = 4
await listeners.get('agent/pre-step')({ agent, messages: [human] }, enter)
listeners.get('session/event')(agent.session, { type: 'user/message', seq: 5, data: human })
const result = await publish.execute({}, exec)
assert.equal(result.queued, true, result.error)
assert.equal(result.requirement.id, 'R-009')
assert.equal((await publish.execute({}, exec)).duplicate, true)
const { tasks } = await env.service.tasks(env.projectId)
assert.deepEqual(tasks.map(task => [task.requirementId, task.ownerSeatId]), [['R-009', 'zhongshu']])
commands.dispose()
})
test('2. 丞相尝试直接派给工部:系统拒绝且无任务/共识/投递副作用', async () => {
const env = await setupGate()
const req = await readyRequirement(env)
const memoryBefore = (await env.service.memory(env.projectId)).memory.revision
const promptBefore = env.fake.calls.prompt.length
const followupBefore = env.fake.calls.followup.length
const out = await run(env, 'sansheng_requirement_publish', { targetSeatId: 'gongbu', requirementId: req.id }, 'lead')
assert.equal(out.ok, false)
assert.equal(out.reason, 'workflow-route-forbidden')
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
assert.equal((await env.service.memory(env.projectId)).memory.revision, memoryBefore)
assert.equal(env.fake.calls.prompt.length, promptBefore)
assert.equal(env.fake.calls.followup.length, followupBefore)
const reqs = await env.service.requirements(env.projectId)
assert.equal(reqs.requirements[0].status, req.status, '需求状态也不能被直接派工改变')
})
test('3. 未发布需求不能进入中书', async () => {
test('3. 只有标题和用户原话的 ready 需求,明确授权即可进入中书', async () => {
const env = await setupGate()
const req = await readyRequirement(env, { scope: '', acceptanceCriteria: '' })
const req = await readyRequirement(env, {
summary: '', judgement: 'needs_discussion', scope: '', nonGoals: '', acceptanceCriteria: '',
risks: '', dependencies: '', missingInfo: '',
})
assert.equal(req.status, 'ready', '缺少范围与验收不再阻塞下派')
env.fake.say(env.seatSessions.lead, `发布 ${req.id} 给中书`)
const out = await run(env, 'sansheng_requirement_publish', {
requirementId: req.id,
expectedRevision: req.revision,
targetSeatId: 'zhongshu',
}, 'lead')
assert.equal(out.ok, false)
assert.match(String(out.error), /待发布|不可发布|范围/)
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
assert.equal(out.ok, true, out.error)
const tasks = (await env.service.tasks(env.projectId)).tasks
assert.equal(tasks.length, 1)
assert.equal(tasks[0].ownerSeatId, 'zhongshu')
assert.equal(tasks[0].requirementSnapshot.scope, '')
assert.equal(tasks[0].goal, req.title, '没有摘要和范围时任务说明回落到标题')
})
test('4. 明确发布后只进入中书,不能直接进尚书/六部', async () => {
@ -168,7 +217,65 @@ test('6. 门下审核后直接交尚书,保留当前需求范围', async () =>
assert.equal(task.ownerSeatId, 'shangshu')
assert.equal(task.stage, 'shangshu_dispatch')
assert.equal(task.approvalScope, req.scope)
assert.equal(env.fake.calls.prompt.at(-1).sessionId, env.seatSessions.shangshu)
assert.equal(env.fake.calls.followup.at(-1).sessionId, env.seatSessions.shangshu)
})
test('门下审批取消时保留任务并显示阻塞,工作台应答后直接交尚书', async t => {
const env = await setupGate()
const { taskId } = await publishRequirement(env, await readyRequirement(env))
const draft = await run(env, 'sansheng_workflow_submit', { taskId, draft: '工部实现本地页面,门下验收。' }, 'zhongshu')
assert.equal(draft.ok, true, draft.error)
const listeners = new Map()
const ctx = { on(name, listener) { listeners.set(name, listener); return () => listeners.delete(name) } }
t.after(installWorkflowBlockage(ctx, { store: env.store, agents: env.fake.host.agents }))
const approvalCenter = createApprovalCenter({ ctx, resolveSeatBySessionId: sessionId => {
const found = env.store.seatBySession(sessionId)
return found ? { projectId: found.project.id, seatId: found.seatId } : null
} })
t.after(approvalCenter.install())
env.service.approvalCenter = approvalCenter
const { agent } = execOf(env, 'menxia')
const name = 'sansheng_workflow_review'
const args = { taskId, action: 'approve', note: '符合验收标准' }
let seq = 0
const append = (type, data) => listeners.get('session/event')(agent.session, { type, data, seq: ++seq, time: Date.now() })
const starts = env.fake.calls.followup.length
append('turn/start')
append('tool/ptc-dispatch-start', { subCallId: 'review-1', name, arguments: args })
append('approval/asked', { id: 'approval-1', toolName: name, callId: 'review-1' })
await append('approval/decided', { id: 'approval-1', outcome: 'cancelled' })
append('turn/end')
const api = createApiHandler(env.service)
const blocked = (await api('tasks', { projectId: env.projectId })).value.tasks.find(task => task.id === taskId)
assert.equal(blocked.stage, 'menxia_review')
assert.equal(blocked.workflowBlockage.code, 'APPROVAL_CANCELLED')
assert.equal(env.fake.calls.followup.length, starts)
const persisted = new SanshengStore(env.file)
await persisted.load()
assert.equal(persisted.get(env.projectId).tasks.find(task => task.id === taskId).workflowBlockage.code, 'APPROVAL_CANCELLED')
append('turn/start')
append('tool/ptc-dispatch-start', { subCallId: 'review-2', name, arguments: args })
append('approval/asked', { id: 'approval-2', toolName: name, callId: 'review-2' })
const waiting = listeners.get('approval/request')({ agent, toolName: name, callId: 'review-2' }, () => new Promise(() => {}))
await new Promise(resolve => setImmediate(resolve))
const [entry] = (await api('approvals', { projectId: env.projectId })).value.approvals
assert.equal(entry.callId, 'review-2')
const answer = await api('approvalAnswer', { ...entry, choice: 'allow' })
assert.equal(answer.ok, true)
const outcome = await waiting
assert.equal(outcome, 'allowed-once')
await append('approval/decided', { id: 'approval-2', outcome })
const reviewed = await run(env, name, args, 'menxia')
assert.equal(reviewed.ok, true, reviewed.error)
append('turn/end')
const current = (await env.service.taskGet(env.projectId, taskId)).task
assert.equal(current.stage, 'shangshu_dispatch')
assert.equal(current.workflowBlockage, undefined)
assert.equal(env.fake.calls.followup.length, starts + 1)
assert.equal(env.fake.calls.followup.at(-1).sessionId, env.seatSessions.shangshu)
})
test('7. 门下通过后,尚书可以向六部派工', async () => {
@ -187,7 +294,7 @@ test('7. 门下通过后,尚书可以向六部派工', async () => {
assert.ok(child)
assert.equal(child.ownerSeatId, 'gongbu')
assert.equal(child.approvalId, approvals[0].id)
assert.equal(env.fake.calls.prompt.at(-1).sessionId, env.seatSessions.gongbu)
assert.equal(env.fake.calls.followup.at(-1).sessionId, env.seatSessions.gongbu)
})
test('8. 用户直接对六部聊天也不能绕过批准执行', async () => {
@ -199,7 +306,7 @@ test('8. 用户直接对六部聊天也不能绕过批准执行', async () => {
}, 'gongbu')
assert.equal(workflow.ok, false)
assert.equal((await env.service.tasks(env.projectId)).tasks.length, before)
assert.equal(env.fake.calls.prompt.length, 0)
assert.equal(env.fake.calls.followup.length, 0)
})
test('9. 需求 revision 变化后旧批准立即失效,旧任务不能再报告完成', async () => {
@ -241,7 +348,7 @@ test('10. 旧版待批任务恢复后在待你处理等待确认', async () => {
})
const store2 = new SanshengStore(env.file)
await store2.load()
const service2 = new SanshengService({ store: store2, host: env.fake.host, provisioner: env.provisioner })
const service2 = new SanshengService({ store: store2, host: env.fake.host, provisioner: env.provisioner, seatDelivery: env.seatDelivery })
await service2.surfaceLegacyApprovals()
const { task } = await service2.taskGet(env.projectId, taskId)
assert.equal(task.stage, 'awaiting_execution_approval')
@ -303,7 +410,7 @@ test('澄清后继续使用同一需求和用户原话', async () => {
const env = await setupGate()
env.fake.say(env.seatSessions.lead, '做个本地页面,问清楚就开工')
const draft = await readyRequirement(env, { judgement: 'needs_discussion', scope: '', dispatchAfterClarification: true })
assert.equal(draft.status, 'discussing')
assert.equal(draft.status, 'ready', '范围与验收不再作为下派门槛,澄清授权仍按原逻辑校验')
env.fake.say(env.seatSessions.lead, '在本地打开即可,用静态页面')
const clarified = await run(env, 'sansheng_requirement_upsert', {
id: draft.id, expectedRevision: draft.revision, judgement: 'can_do', scope: '本地静态页面', missingInfo: '无',
@ -334,19 +441,292 @@ test('会商先交丞相,待答复时阻塞派工,通过项目决定接口
const { task } = await env.service.taskGet(env.projectId, taskId)
assert.equal(task.decisions[0].answer, '1')
assert.equal(task.consultations[0].fromSeatId, 'shangshu')
const prompts = []
const delivered = []
let release
const hold = new Promise(resolve => { release = resolve })
const prompt = env.fake.host.sessionController.prompt
env.fake.host.sessionController.prompt = async request => {
if ([env.seatSessions.gongbu, env.seatSessions.libu].includes(request.sessionId)) {
prompts.push(request.sessionId)
if (prompts.length === 2) release()
env.fake.control.followupHook = async sessionId => {
if ([env.seatSessions.gongbu, env.seatSessions.libu].includes(sessionId)) {
delivered.push(sessionId)
if (delivered.length === 2) release()
await hold
}
return prompt(request)
}
const dispatched = await run(env, 'sansheng_workflow_dispatch', assignments, 'shangshu')
assert.equal(dispatched.ok, true, dispatched.error)
assert.equal(new Set(prompts).size, 2)
assert.equal(new Set(delivered).size, 2)
})
test('自然语言下派:两份正文不一致时使用宿主落盘正文,且同一条消息只下派一次', async () => {
const env = await setupGate()
await readyRequirement(env, { title: '落盘正文一号' })
await readyRequirement(env, { title: '落盘正文二号' })
const exec = execOf(env, 'lead')
const { agent } = exec
const listeners = new Map()
let boundary = 3
const commands = createTurnCommands({
agents: { get: id => env.fake.sessions.get(id), turnBoundaryOf: () => ({ openTurnStartSeq: boundary }) },
on(name, handler) { listeners.set(name, handler); return () => listeners.delete(name) },
}, env.store)
try {
const publish = createSeatToolDefinitions({ service: env.service, turnCommands: commands })
.find(tool => tool.name === 'sansheng_requirement_publish')
const enter = () => ({ kind: 'enter' })
const queued = { id: 'm-diff', role: 'user', source: { kind: 'user', rpcId: 'rpc-diff', clientTimeZone: 'Asia/Shanghai' }, content: [{ type: 'text', text: '就按这个做' }] }
const landed = { ...queued, content: [{ type: 'text', text: '就按这个做,发布 R-002' }] }
await listeners.get('agent/pre-step')({ agent, messages: [queued] }, enter)
listeners.get('session/event')(agent.session, { type: 'user/message', seq: boundary + 2, data: landed })
const first = await publish.execute({}, exec)
assert.equal(first.ok, true, first.error)
assert.equal(first.queued, true)
assert.equal(first.requirement.id, 'R-002')
const tasks = (await env.service.tasks(env.projectId)).tasks
assert.equal(tasks.length, 1)
assert.equal(tasks[0].requirementId, 'R-002')
const second = await publish.execute({}, exec)
assert.equal(second.duplicate, true)
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 1)
listeners.get('session/event')(agent.session, { type: 'turn/end', seq: 7 })
boundary = 8
const emptyQueued = { ...queued, id: 'm-empty' }
await listeners.get('agent/pre-step')({ agent, messages: [emptyQueued] }, enter)
listeners.get('session/event')(agent.session, {
type: 'user/message', seq: 10,
data: { ...emptyQueued, content: [{ type: 'text', text: ' ' }] },
})
const empty = await publish.execute({ requirementId: 'R-001' }, exec)
assert.equal(empty.ok, false)
assert.equal(empty.reason, 'sansheng/current-user-message-unavailable')
} finally {
commands.dispose()
}
})
test('中书拟案补齐范围与验收后,自然语言下派的主链一路传到六部回报', async () => {
const env = await setupGate()
const req = await readyRequirement(env, {
summary: '', judgement: 'needs_discussion', scope: '', nonGoals: '', acceptanceCriteria: '',
risks: '', dependencies: '', missingInfo: '',
})
env.fake.say(env.seatSessions.lead, '就按这个做')
const published = await run(env, 'sansheng_requirement_publish', {}, 'lead')
assert.equal(published.ok, true, published.error)
assert.equal(published.requirement.id, req.id)
const taskId = published.taskId
assert.equal((await env.service.taskGet(env.projectId, taskId)).task.requirementSnapshot.scope, '')
const draft = await run(env, 'sansheng_workflow_submit', {
taskId,
draft: '拟案:工部实现三种语言页面,门下验收。',
scope: '本地静态页面 + 三种可运行语言示例',
nonGoals: '不部署公网,不引入构建依赖',
acceptanceCriteria: '三种语言均可真实运行;窄屏可用;可重跑',
risks: '浏览器兼容性',
}, 'zhongshu')
assert.equal(draft.ok, true, draft.error)
assert.deepEqual(draft.filledFields.sort(), ['acceptanceCriteria', 'nonGoals', 'risks', 'scope'])
assert.equal(env.fake.calls.followup.at(-1).sessionId, env.seatSessions.menxia)
const menxiaText = env.fake.calls.followup.at(-1).message.content[0].text
assert.ok(menxiaText.includes('范围:本地静态页面 + 三种可运行语言示例'), menxiaText)
assert.ok(menxiaText.includes('验收标准:三种语言均可真实运行'), menxiaText)
const saved = (await env.service.requirements(env.projectId)).requirements.find(item => item.id === req.id)
assert.equal(saved.revision, req.revision, '中书补缺不升需求版本')
assert.equal(saved.status, 'published')
assert.equal(saved.scope, '', '中书补缺不回写需求正文')
const afterSubmit = (await env.service.taskGet(env.projectId, taskId)).task
assert.equal(afterSubmit.requirementFill.scope, '本地静态页面 + 三种可运行语言示例')
assert.equal(afterSubmit.requirementSnapshot.scope, '本地静态页面 + 三种可运行语言示例')
const review = await run(env, 'sansheng_workflow_review', { taskId, action: 'approve', note: '范围与验收标准齐全' }, 'menxia')
assert.equal(review.ok, true, review.error)
const approval = (await env.service.requirements(env.projectId)).approvals.at(-1)
assert.equal(approval.scope, '本地静态页面 + 三种可运行语言示例')
const dispatched = await run(env, 'sansheng_workflow_dispatch', {
taskId, assignments: [{ seatId: 'gongbu', title: '实现页面' }],
}, 'shangshu')
assert.equal(dispatched.ok, true, dispatched.error)
const child = (await env.service.tasks(env.projectId)).tasks.find(item => item.parentTaskId === taskId && item.kind === 'execution')
assert.equal(child.requirementSnapshot.scope, '本地静态页面 + 三种可运行语言示例')
assert.equal(env.fake.calls.followup.at(-1).sessionId, env.seatSessions.gongbu)
const gongbuText = env.fake.calls.followup.at(-1).message.content[0].text
assert.ok(gongbuText.includes('范围:本地静态页面 + 三种可运行语言示例'), gongbuText)
assert.ok(gongbuText.includes('验收标准:三种语言均可真实运行'), gongbuText)
const report = await run(env, 'sansheng_task_report', {
taskId: child.id, status: 'done', result: '真实结果:三种语言均执行成功,输出 PASS。',
}, 'gongbu')
assert.equal(report.ok, true, report.error)
assert.equal(report.task.status, 'done')
})
test('中书补缺只写空缺字段,用户已确认的范围保持原样', async () => {
const env = await setupGate()
const req = await readyRequirement(env, {
scope: '用户确认的范围',
nonGoals: '用户确认的非目标',
acceptanceCriteria: '',
risks: '',
})
const published = await publishRequirement(env, req)
const draft = await run(env, 'sansheng_workflow_submit', {
taskId: published.taskId,
draft: '拟案',
scope: '中书想换的范围',
nonGoals: '中书想换的非目标',
acceptanceCriteria: '中书补的验收标准',
risks: '中书补的风险',
}, 'zhongshu')
assert.equal(draft.ok, true, draft.error)
assert.deepEqual(draft.filledFields.sort(), ['acceptanceCriteria', 'risks'])
assert.deepEqual(draft.keptFields.sort(), ['nonGoals', 'scope'])
const saved = (await env.service.requirements(env.projectId)).requirements.find(item => item.id === req.id)
assert.equal(saved.scope, '用户确认的范围')
assert.equal(saved.nonGoals, '用户确认的非目标')
assert.equal(saved.acceptanceCriteria, '', '中书补缺不回写需求正文')
assert.equal(saved.risks, '')
assert.equal(saved.revision, req.revision)
const task = (await env.service.taskGet(env.projectId, published.taskId)).task
assert.equal(task.requirementSnapshot.scope, '用户确认的范围')
assert.equal(task.requirementSnapshot.nonGoals, '用户确认的非目标')
assert.equal(task.requirementSnapshot.acceptanceCriteria, '中书补的验收标准')
assert.equal(task.requirementSnapshot.risks, '中书补的风险')
assert.deepEqual(Object.keys(task.requirementFill).sort(), ['acceptanceCriteria', 'risks'])
})
test('中书没有补齐范围与验收时,门下批准被拒;退回补齐后可批准', async () => {
const env = await setupGate()
const req = await readyRequirement(env, { summary: '', scope: '', acceptanceCriteria: '' })
const published = await publishRequirement(env, req)
const draft = await run(env, 'sansheng_workflow_submit', { taskId: published.taskId, draft: '只写拟案,不补需求字段' }, 'zhongshu')
assert.equal(draft.ok, true, draft.error)
const rejected = await run(env, 'sansheng_workflow_review', { taskId: published.taskId, action: 'approve', note: '缺范围' }, 'menxia')
assert.equal(rejected.ok, false)
assert.equal(rejected.reason, 'sansheng/requirement-incomplete')
const returned = await run(env, 'sansheng_workflow_review', { taskId: published.taskId, action: 'return', note: '请补齐范围与验收标准' }, 'menxia')
assert.equal(returned.ok, true, returned.error)
const resubmit = await run(env, 'sansheng_workflow_submit', {
taskId: published.taskId, draft: '已补齐', scope: '补齐的范围', acceptanceCriteria: '补齐的验收标准',
}, 'zhongshu')
assert.equal(resubmit.ok, true, resubmit.error)
const approved = await run(env, 'sansheng_workflow_review', { taskId: published.taskId, action: 'approve', note: '已补齐' }, 'menxia')
assert.equal(approved.ok, true, approved.error)
const task = (await env.service.taskGet(env.projectId, published.taskId)).task
assert.equal(task.stage, 'shangshu_dispatch')
assert.equal(task.approvalScope, '补齐的范围')
assert.equal(task.requirementSnapshot.scope, '补齐的范围')
const reqAfter = (await env.service.requirements(env.projectId)).requirements.find(item => item.id === req.id)
assert.equal(reqAfter.scope, '', '中书补齐不回写需求正文')
assert.equal(reqAfter.revision, req.revision)
})
test('门下退回后,中书可修订自己补的范围,批准和派工按修订后的快照执行', async () => {
const env = await setupGate()
const req = await readyRequirement(env, { summary: '', scope: '', acceptanceCriteria: '' })
const published = await publishRequirement(env, req)
const taskId = published.taskId
const first = await run(env, 'sansheng_workflow_submit', {
taskId, draft: '第一版拟案', scope: '第一版范围', acceptanceCriteria: '第一版验收标准',
}, 'zhongshu')
assert.equal(first.ok, true, first.error)
const firstTask = (await env.service.taskGet(env.projectId, taskId)).task
assert.equal(firstTask.requirementSnapshot.scope, '第一版范围')
assert.equal(firstTask.requirementFill.scope, '第一版范围')
const returned = await run(env, 'sansheng_workflow_review', { taskId, action: 'return', note: '范围太宽,收窄到本地' }, 'menxia')
assert.equal(returned.ok, true, returned.error)
// 省略未改的字段时保留已有快照值;改中书自己补的 scope 时允许覆盖。
const revised = await run(env, 'sansheng_workflow_submit', {
taskId, draft: '第二版拟案', scope: '修订后的范围',
}, 'zhongshu')
assert.equal(revised.ok, true, revised.error)
assert.ok(revised.filledFields.includes('scope'))
const revisedTask = (await env.service.taskGet(env.projectId, taskId)).task
assert.equal(revisedTask.requirementSnapshot.scope, '修订后的范围')
assert.equal(revisedTask.requirementSnapshot.acceptanceCriteria, '第一版验收标准', '省略字段保留快照值')
assert.equal(revisedTask.requirementFill.scope, '修订后的范围')
const reqAfter = (await env.service.requirements(env.projectId)).requirements.find(item => item.id === req.id)
assert.equal(reqAfter.scope, '', '中书修订只改任务快照,不回写需求正文')
assert.equal(reqAfter.revision, req.revision, '需求版本保持不变')
const approved = await run(env, 'sansheng_workflow_review', { taskId, action: 'approve', note: '按修订范围通过' }, 'menxia')
assert.equal(approved.ok, true, approved.error)
const approval = (await env.service.requirements(env.projectId)).approvals.at(-1)
assert.equal(approval.scope, '修订后的范围')
const dispatched = await run(env, 'sansheng_workflow_dispatch', {
taskId, assignments: [{ seatId: 'gongbu', title: '按修订范围实现' }],
}, 'shangshu')
assert.equal(dispatched.ok, true, dispatched.error)
const child = (await env.service.tasks(env.projectId)).tasks.find(item => item.parentTaskId === taskId && item.kind === 'execution')
assert.equal(child.requirementSnapshot.scope, '修订后的范围')
assert.equal(child.approvalScope, '修订后的范围')
const gongbuText = env.fake.calls.followup.at(-1).message.content[0].text
assert.ok(gongbuText.includes('范围:修订后的范围'), gongbuText)
assert.ok(!gongbuText.includes('第一版范围'), gongbuText)
const report = await run(env, 'sansheng_task_report', {
taskId: child.id, status: 'done', result: '按修订后的范围完成,验证 PASS。',
}, 'gongbu')
assert.equal(report.ok, true, report.error)
assert.equal(report.task.status, 'done')
})
test('not_now 需求即使明确授权也不能下派', async () => {
const env = await setupGate()
const req = await readyRequirement(env, { judgement: 'not_now', judgementReason: '依赖未就绪', scope: '', acceptanceCriteria: '' })
assert.equal(req.status, 'discussing')
env.fake.say(env.seatSessions.lead, '就按这个做')
const out = await run(env, 'sansheng_requirement_publish', { requirementId: req.id, expectedRevision: req.revision }, 'lead')
assert.equal(out.ok, false)
assert.equal(out.reason, 'sansheng/requirement-not-ready')
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
})
test('两条只有标题和用户原话的 ready 需求同时存在时,未指定编号仍报多候选', async () => {
const env = await setupGate()
await readyRequirement(env, { title: '候选一', summary: '', scope: '', acceptanceCriteria: '' })
await readyRequirement(env, { title: '候选二', summary: '', scope: '', acceptanceCriteria: '' })
env.fake.say(env.seatSessions.lead, '就按这个做')
const out = await run(env, 'sansheng_requirement_publish', {}, 'lead')
assert.equal(out.ok, false)
assert.equal(out.reason, 'sansheng/requirement-ambiguous')
assert.match(String(out.error), /R-001、R-002/)
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
})
test('两条 ready 需求并存时,用户消息里的编号仍选中指定需求', async () => {
const env = await setupGate()
await readyRequirement(env, { title: '编号一', summary: '', scope: '', acceptanceCriteria: '' })
const second = await readyRequirement(env, { title: '编号二', summary: '', scope: '', acceptanceCriteria: '' })
env.fake.say(env.seatSessions.lead, `就按这个做,发布 ${second.id}`)
const out = await run(env, 'sansheng_requirement_publish', {}, 'lead')
assert.equal(out.ok, true, out.error)
assert.equal(out.requirement.id, second.id)
const tasks = (await env.service.tasks(env.projectId)).tasks
assert.equal(tasks.length, 1)
assert.equal(tasks[0].requirementId, second.id)
})
test('旧数据里存成 discussing 但已满足新门槛的需求,列表和候选都按 ready 处理', async () => {
const env = await setupGate()
const req = await readyRequirement(env, { title: '旧数据需求', summary: '', scope: '', acceptanceCriteria: '' })
await env.store.mutate(state => {
const target = state.projects[env.projectId].requirements.find(item => item.id === req.id)
target.status = 'discussing'
target.blockedReason = '等待与用户商讨并补全发布信息'
})
const listed = (await env.service.requirements(env.projectId)).requirements.find(item => item.id === req.id)
assert.equal(listed.status, 'ready')
env.fake.say(env.seatSessions.lead, '就按这个做')
const out = await run(env, 'sansheng_requirement_publish', {}, 'lead')
assert.equal(out.ok, true, out.error)
const stored = env.store.get(env.projectId).requirements.find(item => item.id === req.id)
assert.equal(stored.status, 'published')
})

View File

@ -45,5 +45,4 @@ test('seat-delivery:resolveAgent 后 followup,source 永远不是 user', asy
assert.equal(result.status, 'sent')
assert.equal(followed.source.kind, 'sansheng-task')
assert.equal(followed.source.kind === 'user', false)
assert.equal(delivery.attempt('a1').state, 'sent')
})

View File

@ -19,7 +19,7 @@ async function makeService() {
const service = new SanshengService({ store, host: fake.host, provisioner, globalStore, modelSync })
const opened = await service.open({ path: '/model-service', name: '模型服务项目' })
await service.enableSeat(opened.project.id, 'gongbu')
return { service, projectId: opened.project.id, globalStore, fake }
return { service, projectId: opened.project.id, globalStore, fake, modelSync }
}
test('service:全局默认继承、项目覆盖优先、清除覆盖回全局', async () => {
@ -45,3 +45,16 @@ test('service:全局默认继承、项目覆盖优先、清除覆盖回全局'
assert.equal(seat.modelSource, 'global')
assert.equal(seat.configuredModel.model, 'deepseek-reasoner')
})
test('model sync:活 agentRef 不参与状态深拷贝', async () => {
const { service, projectId, fake, modelSync } = await makeService()
const view = await service.project(projectId)
const seat = view.project.seats.find(item => item.id === 'gongbu')
const agent = fake.sessions.get(seat.sessionId)
Object.defineProperty(agent, 'toJSON', {
enumerable: false,
value() { throw new Error('cannot get property "toJSON" without inject') },
})
const status = await modelSync.syncSeat(projectId, 'gongbu', 'test')
assert.equal(status.status, 'synced')
})

View File

@ -17,7 +17,7 @@ test('尚书汇总:只读真实任务,不重派任务,汇总请求发送
requirement: '保留标题',
ownerSeatId: 'gongbu',
})
await env.service.taskDispatch(id, created.task.id, { force: true })
await env.service.taskDispatch(id, created.task.id)
const before = await env.service.tasks(id)
const result = await env.service.shangshuSummary(id)
@ -31,9 +31,9 @@ test('尚书汇总:只读真实任务,不重派任务,汇总请求发送
const shang = seatById(await env.service.project(id), 'shangshu')
assert.equal(shang.status, 'bound', '汇总会按需开启尚书会话')
assert.equal(result.sessionId, shang.sessionId)
const promptCall = env.fake.calls.prompt.at(-1)
assert.equal(promptCall.sessionId, shang.sessionId, '汇总请求必须发到尚书会话')
const text = promptCall.content[0].text
const lastDelivery = env.fake.calls.followup.at(-1)
assert.equal(lastDelivery.sessionId, shang.sessionId, '汇总请求必须发到尚书会话')
const text = lastDelivery.message.content[0].text
assert.match(text, /【尚书汇总】/)
assert.match(text, /写页面/)
assert.match(text, /已派工/)

View File

@ -12,7 +12,7 @@ test('taskDispatch:并发同任务只允许一个领取者发送', async () =>
env.service.taskDispatch(projectId, created.task.id),
env.service.taskDispatch(projectId, created.task.id),
])
assert.equal(env.fake.calls.prompt.length, 1)
assert.equal(env.fake.calls.followup.length, 1)
assert.equal([a, b].filter(item => item.delivered).length, 1)
assert.equal((await env.service.taskGet(projectId, created.task.id)).task.deliveryState, 'accepted')
})

View File

@ -0,0 +1,331 @@
// 任务投递修复的隔离回归:取消/改版/重启恢复/重试上下文/同标识去重。
// 宿主全部是 fake,不触发任何真实 DSH 任务投递。
import test from 'node:test'
import assert from 'node:assert/strict'
import { setupService } from './helpers.js'
import { SanshengService } from '../src/host/service.js'
import { SanshengStore } from '../src/host/store.js'
import { createProvisioner } from '../src/host/provision.js'
import { createSeatDelivery } from '../src/host/seat-delivery.js'
function defer() {
let resolve
const promise = new Promise(done => { resolve = done })
return { promise, resolve }
}
async function fixture(path) {
const env = await setupService({ prompt: true })
const opened = await env.service.open({ path, name: '投递修复项目' })
env.projectId = opened.project.id
env.sessions = {}
for (const seatId of ['lead', 'zhongshu', 'menxia', 'shangshu', 'gongbu']) {
const view = await env.service.enableSeat(env.projectId, seatId)
env.sessions[seatId] = view.project.seats.find(seat => seat.id === seatId).sessionId
}
return env
}
async function createTask(env, title = '执行任务') {
const created = await env.service.taskCreate(env.projectId, { title, ownerSeatId: 'gongbu', goal: title })
return created.task
}
function holdFollowup(env, sessionId) {
const reached = defer()
const gate = defer()
env.fake.control.followupHook = async id => {
if (id === sessionId) {
reached.resolve()
await gate.promise
}
}
return { reached: reached.promise, release: () => gate.resolve() }
}
async function waitTaskDelivery(service, projectId, taskId, state = 'accepted') {
for (let i = 0; i < 400; i += 1) {
const task = (await service.taskGet(projectId, taskId)).task
if (task.deliveryState === state) return task
await new Promise(resolve => setTimeout(resolve, 5))
}
throw new Error(`任务 ${taskId} 未在预期时间内变为 ${state}`)
}
async function createRequirement(env) {
const out = await env.service.requirementUpsert(env.projectId, {
title: '流程需求',
summary: '摘要',
originalText: '用户原话:流程需求',
judgement: 'can_do',
judgementReason: '可做',
scope: '范围',
nonGoals: '非目标',
acceptanceCriteria: '验收标准',
}, {})
return out.requirement
}
async function publishRequirement(env, req) {
return env.service.requirementPublish(env.projectId, req.id, {
expectedRevision: req.revision,
command: '发布 ' + req.id,
commandRef: { messageId: 'msg-' + req.id, seq: 9 },
}, { seatId: 'lead', sessionId: env.sessions.lead })
}
async function drive(env, target) {
const req = await createRequirement(env)
const published = await publishRequirement(env, req)
await waitTaskDelivery(env.service, env.projectId, published.taskId)
const taskId = published.taskId
if (target === 'zhongshu_draft') return { taskId }
await env.service.workflowSubmitDraft(env.projectId, taskId, { draft: '拟案:按范围执行,门下验收。' }, { seatId: 'zhongshu', sessionId: env.sessions.zhongshu })
if (target === 'menxia_review') return { taskId }
await env.service.workflowReview(env.projectId, taskId, { action: 'approve', note: '方案可执行' }, { seatId: 'menxia', sessionId: env.sessions.menxia })
if (target === 'shangshu_dispatch') return { taskId }
const dispatched = await env.service.workflowDispatch(env.projectId, taskId, {
assignments: [{ seatId: 'gongbu', title: '执行任务', goal: '按范围执行' }],
}, { seatId: 'shangshu', sessionId: env.sessions.shangshu })
const child = dispatched.children[0]
await env.service.taskReport(env.projectId, child.id, {
status: 'done', result: '真实结果:完成', seatId: 'gongbu', sessionId: env.sessions.gongbu,
})
if (target === 'department_exec') return { taskId, childId: child.id }
await env.service.workflowSummarize(env.projectId, taskId, { summary: '六部已完成' }, { seatId: 'shangshu', sessionId: env.sessions.shangshu })
if (target === 'menxia_acceptance') return { taskId, childId: child.id }
await env.service.workflowAccept(env.projectId, taskId, { action: 'accept', note: '验收通过' }, { seatId: 'menxia', sessionId: env.sessions.menxia })
return { taskId, childId: child.id }
}
test('场景1:领取后 followup 前取消(领取失效),followup 0 次,状态保持 cancelled', async () => {
const env = await fixture('/fix-scenario1')
const task = await createTask(env)
const controller = env.fake.host.sessionController
const originalResolve = controller.resolveAgent.bind(controller)
const reached = defer()
const gate = defer()
controller.resolveAgent = async id => {
if (id === env.sessions.gongbu) {
reached.resolve()
await gate.promise
}
return originalResolve(id)
}
const dispatch = env.service.taskDispatch(env.projectId, task.id)
await reached.promise
await env.service.taskCancel(env.projectId, task.id)
gate.resolve()
const result = await dispatch
controller.resolveAgent = originalResolve
assert.equal(result.delivered, false)
assert.equal(env.fake.calls.followup.length, 0)
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.status, 'cancelled')
assert.equal(after.deliveryState, 'none')
})
test('场景2:followup 后、回写前取消,迟到回写不覆盖取消', async () => {
const env = await fixture('/fix-scenario2')
const task = await createTask(env)
const held = holdFollowup(env, env.sessions.gongbu)
const dispatch = env.service.taskDispatch(env.projectId, task.id)
await held.reached
await env.service.taskCancel(env.projectId, task.id)
held.release()
await dispatch
assert.equal(env.fake.calls.followup.length, 1)
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.status, 'cancelled')
assert.equal(after.deliveryState, 'none')
})
test('场景3:发送中修改要求,迟到回写不覆盖 draft', async () => {
const env = await fixture('/fix-scenario3')
const task = await createTask(env)
const held = holdFollowup(env, env.sessions.gongbu)
const dispatch = env.service.taskDispatch(env.projectId, task.id)
await held.reached
await env.service.taskRevise(env.projectId, task.id, { goal: '修改后的目标' })
held.release()
await dispatch
assert.equal(env.fake.calls.followup.length, 1)
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.status, 'draft')
assert.equal(after.deliveryState, 'none')
assert.equal(after.goal, '修改后的目标')
})
test('场景4:需求改版时执行任务在发,仍为 returned', async () => {
const env = await fixture('/fix-scenario4')
const req = await createRequirement(env)
const created = await env.service.taskCreate(env.projectId, {
title: '执行任务',
ownerSeatId: 'gongbu',
kind: 'execution',
requirementId: req.id,
requirementRevision: req.revision,
})
const held = holdFollowup(env, env.sessions.gongbu)
const dispatch = env.service.taskDispatch(env.projectId, created.task.id)
await held.reached
const updated = await env.service.requirementUpsert(env.projectId, {
id: req.id,
expectedRevision: req.revision,
acceptanceCriteria: '新增要求:必须支持第四种语言',
}, {})
assert.equal(updated.requirement.revision, req.revision + 1)
held.release()
await dispatch
const after = (await env.service.taskGet(env.projectId, created.task.id)).task
assert.equal(after.status, 'returned')
assert.equal(after.deliveryState, 'none')
})
const transitionCases = [
{
key: 'publish',
title: '需求发布',
prepare: async env => {
const req = await createRequirement(env)
return { run: async () => ({ taskId: (await publishRequirement(env, req)).taskId }) }
},
},
{
key: 'submit',
title: '中书提交拟案',
prepare: async env => {
const { taskId } = await drive(env, 'zhongshu_draft')
return {
run: async () => {
await env.service.workflowSubmitDraft(env.projectId, taskId, { draft: '拟案:按范围执行,门下验收。' }, { seatId: 'zhongshu', sessionId: env.sessions.zhongshu })
return { taskId }
},
}
},
},
{
key: 'summarize',
title: '尚书汇总转门下验收',
prepare: async env => {
const { taskId } = await drive(env, 'department_exec')
return {
run: async () => {
await env.service.workflowSummarize(env.projectId, taskId, { summary: '六部已完成' }, { seatId: 'shangshu', sessionId: env.sessions.shangshu })
return { taskId }
},
}
},
},
{
key: 'accept',
title: '门下验收通过',
prepare: async env => {
const { taskId } = await drive(env, 'menxia_acceptance')
return {
run: async () => {
await env.service.workflowAccept(env.projectId, taskId, { action: 'accept', note: '验收通过' }, { seatId: 'menxia', sessionId: env.sessions.menxia })
return { taskId }
},
}
},
},
]
for (const item of transitionCases) {
test(`场景5:${item.title}后立刻重启,恢复只补发一次且状态与不重启一致`, async () => {
const normal = await fixture('/fix-normal-' + item.key)
const normalPrepared = await item.prepare(normal)
const normalOut = await normalPrepared.run()
await waitTaskDelivery(normal.service, normal.projectId, normalOut.taskId)
const expected = (await normal.service.taskGet(normal.projectId, normalOut.taskId)).task
const restarted = await fixture('/fix-restart-' + item.key)
const prepared = await item.prepare(restarted)
const originalDispatch = restarted.service.taskDispatch
let stubbed = 0
restarted.service.taskDispatch = async () => { stubbed += 1; return { delivered: false, duplicate: false } }
const out = await prepared.run()
restarted.service.taskDispatch = originalDispatch
assert.equal(stubbed, 1, '阶段切换应只登记一次待发投递')
const queued = (await restarted.service.taskGet(restarted.projectId, out.taskId)).task
assert.equal(queued.deliveryState, 'pending')
const before = restarted.fake.calls.followup.length
const store = new SanshengStore(restarted.file)
const provisioner = createProvisioner({ store, host: restarted.fake.host })
const service = new SanshengService({
store, host: restarted.fake.host, provisioner,
seatDelivery: createSeatDelivery({ host: restarted.fake.host }),
})
const recovery = await service.recoverPendingDeliveries()
assert.equal(recovery.recovered.length, 1)
assert.equal(restarted.fake.calls.followup.length, before + 1, '重启恢复只补发一次')
const actual = (await service.taskGet(restarted.projectId, out.taskId)).task
assert.equal(actual.deliveryId, queued.deliveryId, '恢复沿用同一 deliveryId')
assert.equal(actual.deliveryState, 'accepted')
assert.equal(actual.status, expected.status)
assert.equal(actual.stage, expected.stage)
})
}
test('场景6:重启遗留 sending 变 unknown,followup 0 次', async () => {
const env = await fixture('/fix-scenario6')
const task = await createTask(env)
await env.store.mutate(s => {
const target = s.projects[env.projectId].tasks.find(item => item.id === task.id)
target.deliveryId = 'delivery-sending-6'
target.deliveryState = 'sending'
target.sendingOwner = 'attempt-6'
target.deliveryOwner = 'attempt-6'
s.projects[env.projectId].revision = (s.projects[env.projectId].revision ?? 0) + 1
})
const store = new SanshengStore(env.file)
const provisioner = createProvisioner({ store, host: env.fake.host })
const service = new SanshengService({
store, host: env.fake.host, provisioner,
seatDelivery: createSeatDelivery({ host: env.fake.host }),
})
const result = await service.recoverPendingDeliveries()
assert.equal(result.staleSending, 1)
assert.equal(env.fake.calls.followup.length, 0)
const after = (await service.taskGet(env.projectId, task.id)).task
assert.equal(after.deliveryState, 'unknown')
assert.equal(after.sendingOwner, null)
})
test('场景9:同一 deliveryId 重复调用不重发(含退回后保留状态的投递)', async () => {
const env = await fixture('/fix-scenario9')
const { taskId } = await drive(env, 'menxia_review')
await env.service.workflowReview(env.projectId, taskId, { action: 'return', note: '补范围说明' }, { seatId: 'menxia', sessionId: env.sessions.menxia })
const returned = (await env.service.taskGet(env.projectId, taskId)).task
assert.equal(returned.status, 'returned')
assert.equal(returned.deliveryState, 'accepted')
const count = env.fake.calls.followup.length
const duplicate = await env.service.taskDispatch(env.projectId, taskId, { deliveryId: returned.deliveryId })
assert.equal(duplicate.duplicate, true)
assert.equal(env.fake.calls.followup.length, count)
})
test('返工回归:退回后首发结果未知,重投成功仍保持 returned', async () => {
const env = await fixture('/fix-redispatch-returned')
const { taskId } = await drive(env, 'menxia_review')
env.fake.control.followupHook = async sessionId => {
if (sessionId === env.sessions.zhongshu) throw new Error('模拟首次投递结果未知')
}
const reviewed = await env.service.workflowReview(env.projectId, taskId, { action: 'return', note: '补范围说明' }, { seatId: 'menxia', sessionId: env.sessions.menxia })
assert.equal(reviewed.delivered, false)
const first = (await env.service.taskGet(env.projectId, taskId)).task
assert.equal(first.status, 'returned')
assert.equal(first.deliveryState, 'unknown')
assert.equal(first.deliveryStatus, 'returned')
env.fake.control.followupHook = null
const count = env.fake.calls.followup.length
const redelivered = await env.service.redispatchTask(env.projectId, taskId, { expectedDeliveryId: first.deliveryId })
assert.equal(redelivered.delivery.status, 'sent')
assert.equal(env.fake.calls.followup.length, count + 1)
const after = (await env.service.taskGet(env.projectId, taskId)).task
assert.equal(after.status, 'returned', '重投不能把已退回改成已派工')
assert.equal(after.deliveryStatus, 'returned')
assert.equal(after.deliveryState, 'accepted')
})

View File

@ -6,7 +6,8 @@ async function fixture() {
const env = await setupService({ prompt: true })
const opened = await env.service.open({ path: '/delivery', name: '投递项目' })
env.projectId = opened.project.id
await env.service.enableSeat(env.projectId, 'gongbu')
const view = await env.service.enableSeat(env.projectId, 'gongbu')
env.gongbuSessionId = view.project.seats.find(seat => seat.id === 'gongbu').sessionId
return env
}
@ -22,29 +23,82 @@ test('taskDispatch:pending 领取后同 deliveryId 回写 accepted,重复调
assert.equal(first.delivered, true)
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.deliveryState, 'accepted')
assert.equal(after.status, 'dispatched')
assert.equal(after.deliveryId, first.task.deliveryId)
const promptCount = env.fake.calls.prompt.length
const duplicate = await env.service.taskDispatch(env.projectId, task.id)
assert.equal(env.fake.calls.followup.length, 1)
const duplicate = await env.service.taskDispatch(env.projectId, task.id, { deliveryId: after.deliveryId })
assert.equal(duplicate.duplicate, true)
assert.equal(env.fake.calls.prompt.length, promptCount)
assert.equal(env.fake.calls.followup.length, 1)
})
test('taskDispatch:发送失败写 unknown,未知结果不会自动重发', async () => {
test('taskDispatch:resolve 失败只回 pending,不写 unknown,可按同 deliveryId 重试', async () => {
const env = await fixture()
const task = await createTask(env)
const originalPrompt = env.fake.host.sessionController.prompt
env.fake.host.sessionController.prompt = async () => { throw new Error('模拟发送中断') }
const controller = env.fake.host.sessionController
const originalResolve = controller.resolveAgent.bind(controller)
controller.resolveAgent = async () => ({ error: { code: 'session/not-found' } })
const first = await env.service.taskDispatch(env.projectId, task.id)
controller.resolveAgent = originalResolve
assert.equal(first.delivered, false)
assert.equal((await env.service.taskGet(env.projectId, task.id)).task.deliveryState, 'unknown')
env.fake.host.sessionController.prompt = originalPrompt
const before = env.fake.calls.prompt.length
const retry = await env.service.taskDispatch(env.projectId, task.id)
assert.equal(retry.unknown, true)
assert.equal(env.fake.calls.prompt.length, before)
assert.equal(first.deliveryState, 'pending')
assert.equal(env.fake.calls.followup.length, 0)
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.deliveryState, 'pending')
assert.equal(after.status, 'draft')
const retry = await env.service.taskDispatch(env.projectId, task.id, { deliveryId: after.deliveryId })
assert.equal(retry.delivered, true)
assert.equal(env.fake.calls.followup.length, 1)
assert.equal((await env.service.taskGet(env.projectId, task.id)).task.deliveryState, 'accepted')
})
test('recoverPendingDeliveries:pending 条件领取一次,sending 遗留只标 unknown', async () => {
test('taskDispatch:followup 抛错写 unknown,自动路径不重发', async () => {
const env = await fixture()
const task = await createTask(env)
env.fake.control.followupHook = async () => { throw new Error('模拟发送中断') }
const first = await env.service.taskDispatch(env.projectId, task.id)
assert.equal(first.delivered, false)
assert.equal(first.deliveryState, 'unknown')
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.deliveryState, 'unknown')
assert.equal(after.status, 'draft')
const before = env.fake.calls.followup.length
const retry = await env.service.taskDispatch(env.projectId, task.id)
assert.equal(retry.unknown, true)
assert.equal(env.fake.calls.followup.length, before)
})
test('taskDispatch:建消息失败也算未发出,回 pending 且不调用 followup', async () => {
const env = await fixture()
const task = await createTask(env)
const originalFactory = env.fake.host.createUserMessage
env.fake.host.createUserMessage = async () => { throw new Error('模拟建消息失败') }
const first = await env.service.taskDispatch(env.projectId, task.id)
env.fake.host.createUserMessage = originalFactory
assert.equal(first.delivered, false)
assert.equal(first.deliveryState, 'pending')
assert.equal(env.fake.calls.followup.length, 0)
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.deliveryState, 'pending')
assert.equal(after.status, 'draft')
})
test('taskDispatch:flush 抛错同样记 unknown,不自动重发', async () => {
const env = await fixture()
const task = await createTask(env)
const sessions = env.fake.host.sessions
const originalFlush = sessions.flush.bind(sessions)
sessions.flush = async () => { throw new Error('模拟落盘失败') }
const first = await env.service.taskDispatch(env.projectId, task.id)
sessions.flush = originalFlush
assert.equal(first.delivered, false)
assert.equal(first.deliveryState, 'unknown')
const before = env.fake.calls.followup.length
const retry = await env.service.taskDispatch(env.projectId, task.id)
assert.equal(retry.unknown, true)
assert.equal(env.fake.calls.followup.length, before)
})
test('recoverPendingDeliveries:pending 按存储的 deliveryStatus 补发一次,sending 遗留只标 unknown', async () => {
const env = await fixture()
const pending = await createTask(env, '待恢复投递')
const stale = await createTask(env, '发送中断')
@ -53,10 +107,12 @@ test('recoverPendingDeliveries:pending 条件领取一次,sending 遗留只
const a = project.tasks.find(task => task.id === pending.id)
a.deliveryId = 'delivery-pending-1'
a.deliveryState = 'pending'
a.deliveryStatus = 'dispatched'
a.deliveryAttemptAt = Date.now()
const b = project.tasks.find(task => task.id === stale.id)
b.deliveryId = 'delivery-sending-1'
b.deliveryState = 'sending'
b.sendingOwner = 'attempt-stale'
project.revision = (project.revision ?? 0) + 1
})
const result = await env.service.recoverPendingDeliveries()
@ -65,27 +121,57 @@ test('recoverPendingDeliveries:pending 条件领取一次,sending 遗留只
assert.equal(result.recovered[0].delivered, true)
const tasks = (await env.service.tasks(env.projectId)).tasks
assert.equal(tasks.find(task => task.id === pending.id).deliveryState, 'accepted')
assert.equal(tasks.find(task => task.id === pending.id).status, 'dispatched')
assert.equal(tasks.find(task => task.id === stale.id).deliveryState, 'unknown')
assert.equal(env.fake.calls.prompt.length, 1)
assert.equal(env.fake.calls.followup.length, 1)
})
test('redispatchTask:只允许 expectedDeliveryId 的 blocked/unknown 任务,且只发送一次', async () => {
test('redispatchTask:只认 unknown,正文含范围/非目标/验收标准/阶段提示/记忆', async () => {
const env = await fixture()
const task = await createTask(env, '阻塞任务')
const task = await createTask(env, '重投任务')
await env.service.memoryUpdate(env.projectId, { goal: '项目目标', constraints: ['项目约束'] })
await env.store.mutate(s => {
const target = s.projects[env.projectId].tasks.find(item => item.id === task.id)
target.deliveryId = 'delivery-blocked-1'
target.deliveryState = 'unknown'
target.status = 'blocked'
Object.assign(target, {
deliveryId: 'delivery-unknown-1',
deliveryState: 'unknown',
status: 'draft',
stage: 'shangshu_dispatch',
requirementSnapshot: { scope: '范围X', nonGoals: '非目标Y', acceptanceCriteria: '验收Z' },
})
s.projects[env.projectId].revision = (s.projects[env.projectId].revision ?? 0) + 1
})
const first = await env.service.redispatchTask(env.projectId, task.id, { expectedDeliveryId: 'delivery-blocked-1' })
const first = await env.service.redispatchTask(env.projectId, task.id, { expectedDeliveryId: 'delivery-unknown-1' })
assert.equal(first.delivery.status, 'sent')
const text = env.fake.calls.followup.at(-1).message.content[0].text
assert.match(text, /范围:范围X/)
assert.match(text, /非目标:非目标Y/)
assert.match(text, /验收标准:验收Z/)
assert.match(text, /门下已通过方案/)
assert.match(text, /项目约束/)
const after = (await env.service.taskGet(env.projectId, task.id)).task
assert.equal(after.deliveryState, 'accepted')
assert.equal(after.status, 'dispatched')
assert.equal(after.deliveryStatus, 'dispatched', '旧数据缺字段时补默认值')
await assert.rejects(
() => env.service.redispatchTask(env.projectId, task.id, { expectedDeliveryId: 'delivery-blocked-1' }),
() => env.service.redispatchTask(env.projectId, task.id, { expectedDeliveryId: 'delivery-unknown-1' }),
error => error.code === 'sansheng/invalid',
)
})
test('redispatchTask:已取消任务即使投递结果未知也拒绝重投', async () => {
const env = await fixture()
const task = await createTask(env)
await env.store.mutate(s => {
const target = s.projects[env.projectId].tasks.find(item => item.id === task.id)
target.deliveryId = 'delivery-cancelled-1'
target.deliveryState = 'unknown'
target.status = 'cancelled'
s.projects[env.projectId].revision = (s.projects[env.projectId].revision ?? 0) + 1
})
await assert.rejects(
() => env.service.redispatchTask(env.projectId, task.id, { expectedDeliveryId: 'delivery-cancelled-1' }),
error => error.code === 'sansheng/invalid',
)
assert.equal(env.fake.calls.followup.length, 0)
})

View File

@ -19,10 +19,11 @@ test('任务:新建草稿、派工记录、取消,按项目保存', async ()
assert.equal(listed.tasks.length, 1)
const dispatched = await service.taskDispatch(projectId, created.task.id)
// 测试宿主没有发送接口,因此只记录为待执行,而不是假装已送达
assert.equal(dispatched.delivered, false)
assert.equal(dispatched.task.status, 'prepared')
assert.ok(dispatched.task.note.length > 0)
// 测试宿主补了 followup/createUserMessage/flush,派工走生产投递路径。
assert.equal(dispatched.delivered, true)
assert.equal(dispatched.task.status, 'dispatched')
assert.equal(dispatched.task.deliveryState, 'accepted')
assert.equal(dispatched.task.note, '')
assert.ok(dispatched.task.sessionId)
const cancelled = await service.taskCancel(projectId, created.task.id)
@ -38,7 +39,8 @@ test('任务:缺标题、未知主责席被拒绝;派工按需开启该部
const created = await ctx.service.taskCreate(opened.project.id, { title: '待派工', ownerSeatId: 'lead' })
const dispatched = await ctx.service.taskDispatch(opened.project.id, created.task.id)
// 派工时按需开启主责部门,不要求先手动启用十席
assert.equal(dispatched.task.status, 'prepared')
assert.equal(dispatched.task.status, 'dispatched')
assert.equal(dispatched.task.deliveryState, 'accepted')
assert.ok(dispatched.task.sessionId)
const view = await ctx.service.project(opened.project.id)
assert.equal(view.project.seats.find(s => s.id === 'lead').status, 'bound')

View File

@ -43,7 +43,7 @@ function makeEventedCtx(env) {
return { ctx, registered, disposed, guards, emit }
}
const TOOL_COUNT = createSeatToolDefinitions({}).length
const TOOL_COUNT = createSeatToolDefinitions({ service: { cardCreate() {} } }).length
test('回归:创建事件先到、绑定后保存时,绑定成功即补装部门工具(无需重扫)', async () => {
const env = await setupService({ prompt: true })

View File

@ -40,7 +40,7 @@ async function createLegacyTask(env, title = '内部兼容任务') {
requirement: '由内部流程创建的历史任务',
ownerSeatId: 'gongbu',
})
await env.service.taskDispatch(env.projectId, created.task.id, { force: true })
await env.service.taskDispatch(env.projectId, created.task.id)
return created.task
}