release: dsh-sansheng-liubu v1.1.3
This commit is contained in:
parent
67046beb0a
commit
a4334bfba0
|
|
@ -1,4 +1,4 @@
|
|||
# 三省六部(dsh-sansheng)· v1.1.2
|
||||
# 三省六部(dsh-sansheng)· v1.1.3
|
||||
|
||||
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
|
||||
每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
|
||||
|
|
|
|||
|
|
@ -483,7 +483,7 @@ function refreshList(value, previous, projectChanged = false) {
|
|||
if (Array.isArray(value)) return value;
|
||||
return projectChanged ? [] : previous;
|
||||
}
|
||||
var DELIVERY_LABELS = { pending: "待发送", sending: "发送中", unknown: "结果未知", accepted: "已接收", failed: "投递失败" };
|
||||
var DELIVERY_LABELS = { pending: "待发送", sending: "发送中", unknown: "结果未知", accepted: "已接收" };
|
||||
function deliveryLabel(state) {
|
||||
return DELIVERY_LABELS[state] || "";
|
||||
}
|
||||
|
|
@ -1103,7 +1103,7 @@ 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) {
|
||||
return tasks.filter((task) => task.ownerSeatId === seatId).sort((a, b) => Number(b.updatedAt || b.createdAt || 0) - Number(a.updatedAt || a.createdAt || 0))[0] || null;
|
||||
|
|
@ -1198,7 +1198,7 @@ function WorkbenchV2(props) {
|
|||
task.approvalId ? (0, import_react.createElement)("span", null, task.approvalId) : null
|
||||
),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: task.goal || task.requirement || "", label: "任务说明", empty: "(无任务说明)", max: 110 }),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: task.result || task.note || task.blockedReason || "", label: "当前结果 / 阻塞", empty: "(尚未回报)", max: 110 }),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: task.workflowBlockage ? task.workflowBlockage.label + " · " + task.workflowBlockage.reason : task.result || task.note || task.blockedReason || "", label: "当前结果 / 阻塞", empty: "(尚未回报)", max: 110 }),
|
||||
(0, import_react.createElement)("div", { className: "rc-actions" }, (0, import_react.createElement)("span", { className: "spacer" }), (0, import_react.createElement)("button", { type: "button", className: "r-open", onClick: () => setSelectedTask(task) }, "查看详情 →"))
|
||||
))) : (0, import_react.createElement)("p", { className: "empty-note" }, "还没有流转任务。丞相下派需求后会出现在这里。");
|
||||
} else if (reqView === "delivery") {
|
||||
|
|
@ -1608,7 +1608,7 @@ function WorkbenchV2(props) {
|
|||
} },
|
||||
(0, import_react.createElement)("td", null, (0, import_react.createElement)("span", { className: "task-name" }, task.title), (0, import_react.createElement)("br"), (0, import_react.createElement)("span", { className: "task-id" }, task.id)),
|
||||
(0, import_react.createElement)("td", null, SEATS[task.ownerSeatId]?.label || task.ownerSeatId || "—"),
|
||||
(0, import_react.createElement)("td", null, (0, import_react.createElement)("span", { className: "pill " + taskTone(task.status) }, (0, import_react.createElement)("i"), taskLabel(task.status)), task.deliveryState && task.deliveryState !== "none" ? (0, import_react.createElement)("span", { className: "pill " + (["failed", "unknown"].includes(task.deliveryState) ? "fail" : "idle"), style: { marginLeft: "4px" } }, (0, import_react.createElement)("i"), deliveryLabel(task.deliveryState)) : null),
|
||||
(0, import_react.createElement)("td", null, (0, import_react.createElement)("span", { className: "pill " + taskTone(task.status) }, (0, import_react.createElement)("i"), taskLabel(task.status)), task.deliveryState && task.deliveryState !== "none" ? (0, import_react.createElement)("span", { className: "pill " + (task.deliveryState === "unknown" ? "fail" : "idle"), style: { marginLeft: "4px" } }, (0, import_react.createElement)("i"), deliveryLabel(task.deliveryState)) : null),
|
||||
(0, import_react.createElement)("td", { className: "result-cell" }, task.result ? shortText(task.result, 42) : "—"),
|
||||
(0, import_react.createElement)("td", { className: "dur" }, taskDurationMs(task) > 0 ? durationText(taskDurationMs(task)) : "—"),
|
||||
(0, import_react.createElement)("td", { className: "time" }, task.dispatchedAt ? dateText(task.dispatchedAt) : "—")
|
||||
|
|
@ -1883,6 +1883,13 @@ function WorkbenchV2(props) {
|
|||
)))
|
||||
) : null,
|
||||
(0, import_react.createElement)("div", { className: "m-sec" }, (0, import_react.createElement)("span", { className: "t-label" }, "承办与状态"), (0, import_react.createElement)("p", null, "承办席位:" + (seat ? seat.label : task.ownerSeatId) + " · 模型:" + modelLabelOf(task.ownerSeatId) + " · 状态:" + taskLabel(task.status) + (task.deliveryState && task.deliveryState !== "none" ? " · " + deliveryLabel(task.deliveryState) : ""))),
|
||||
task.workflowBlockage ? (0, import_react.createElement)(
|
||||
"div",
|
||||
{ className: "m-sec" },
|
||||
(0, import_react.createElement)("span", { className: "t-label" }, "当前阻塞"),
|
||||
(0, import_react.createElement)("p", null, task.workflowBlockage.label + " · " + task.workflowBlockage.reason),
|
||||
(0, import_react.createElement)("button", { type: "button", className: "btn", disabled: busy, onClick: () => openSeat(task.ownerSeatId) }, "打开" + (seat?.label || "承办席位") + "会话")
|
||||
) : null,
|
||||
(0, import_react.createElement)("div", { className: "m-sec" }, (0, import_react.createElement)("span", { className: "t-label" }, "任务完成情况"), (0, import_react.createElement)("div", { className: "m-rich" }, task.result ? renderRichText(task.result) : (0, import_react.createElement)("p", { className: "empty-note" }, "(暂无结果)"))),
|
||||
(0, import_react.createElement)("div", { className: "modal-actions" }, (0, import_react.createElement)("button", { type: "button", className: "btn", onClick: () => setSelectedTask(null) }, "关闭"))
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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'
|
||||
|
|
@ -60,6 +61,7 @@ export function apply(ctx, config = {}) {
|
|||
|
||||
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))
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-sansheng-liubu",
|
||||
"version": "1.1.2",
|
||||
"version": "1.1.3",
|
||||
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
|
||||
"keywords": [
|
||||
"dsh-plugin",
|
||||
|
|
|
|||
|
|
@ -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') }
|
||||
|
|
@ -636,7 +636,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) {
|
||||
|
|
@ -723,7 +723,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 +1031,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,6 +1222,11 @@ 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) }, '关闭')),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -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 } = {}) {
|
||||
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,30 @@ 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) })
|
||||
|
||||
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 +110,13 @@ 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) {
|
||||
throw new ApprovalCenterError('sansheng/approval-forbidden', '审批归属不匹配')
|
||||
}
|
||||
const ok = finalize(entry, 'answered', choice)
|
||||
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 +129,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 +159,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()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -76,7 +76,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 +90,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) {
|
||||
|
|
|
|||
|
|
@ -15,25 +15,26 @@ 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 都可在用户明确授权后进入中书,由中书拟案判断可行性。',
|
||||
'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('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import { applyModel, normalizeSelection } from './model.js'
|
|||
import { internalSource } from './message-source.js'
|
||||
import { getCommand, putCommand } from './command-ledger.js'
|
||||
import { recordLeadReportInState } from './lead-reporter.js'
|
||||
import { workflowBlockageOf } from './workflow-blockage.js'
|
||||
|
||||
export class ServiceError extends Error {
|
||||
constructor(code, message) { super(message); this.name = 'ServiceError'; this.code = code }
|
||||
|
|
@ -56,6 +57,8 @@ const REQUIREMENT_TEXT_FIELDS = [
|
|||
'title', 'summary', 'originalText', 'judgement', 'judgementReason', 'scope',
|
||||
'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo',
|
||||
]
|
||||
// 中书拟案时只能补这些空缺字段;标题、用户原话和判断仍由丞相维护。
|
||||
const REQUIREMENT_FILL_FIELDS = ['scope', 'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo']
|
||||
const OPEN_TASK_STATUS = new Set(['draft', 'dispatched', 'running', 'prepared', 'waiting_user', 'returned', 'reconfirm'])
|
||||
|
||||
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
|
||||
|
|
@ -81,12 +84,12 @@ function appendLeadReport(state, projectId, task, event, summary, extra = {}) {
|
|||
return recordLeadReportInState(state, projectId, leadReportEventOf(task, event, summary, extra), Date.now())
|
||||
}
|
||||
|
||||
// 下派只需用户明确授权、标题和用户原话;范围与验收标准由中书拟案补齐。
|
||||
// 只有丞相明确判断 not_now 时才继续阻止下派,空白或默认 needs_discussion 都放行。
|
||||
function requirementReadyProblem(req) {
|
||||
if (!req || !cleanText(req.title)) return '缺少需求标题'
|
||||
if (!cleanText(req.originalText)) return '缺少用户原始要求'
|
||||
if (req.judgement !== 'can_do') return '丞相判断尚不可立项'
|
||||
if (!cleanText(req.scope)) return '缺少范围'
|
||||
if (!cleanText(req.acceptanceCriteria)) return '缺少验收标准'
|
||||
if (req.judgement === 'not_now') return '丞相判断暂不可做'
|
||||
return ''
|
||||
}
|
||||
|
||||
|
|
@ -101,9 +104,8 @@ function requirementBlockedReason(req) {
|
|||
if (req.status === 'cancelled') return '已取消'
|
||||
if (req.status === 'published') return req.blockedReason || '已发布,等待流程推进'
|
||||
if (req.status === 'returned') return req.blockedReason || '已退回,等待重新商讨或拟案'
|
||||
const problem = requirementReadyProblem(req)
|
||||
if (problem) return problem
|
||||
return '可以交中书拟案'
|
||||
if (req.judgement === 'not_now') return req.judgementReason || '丞相判断暂不可做'
|
||||
return '可以交中书拟案,范围与验收标准由中书补齐'
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -115,6 +117,64 @@ function requirementSnapshot(req) {
|
|||
}
|
||||
}
|
||||
|
||||
// 列表按当前门槛重算非终态需求:旧数据存成 discussing、但已可下派的条目也显示为 ready。
|
||||
function requirementView(req) {
|
||||
const view = structuredClone(req)
|
||||
if (!['published', 'cancelled', 'returned'].includes(view.status)) {
|
||||
view.status = requirementStatusOf(view)
|
||||
view.blockedReason = requirementBlockedReason(view)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
// 中书补缺只存在任务上:只认需求里仍为空的字段,用户已确认的内容永远优先。
|
||||
function requirementFillOf(task, req) {
|
||||
const fill = {}
|
||||
for (const field of REQUIREMENT_FILL_FIELDS) {
|
||||
const value = cleanText(task?.requirementFill?.[field])
|
||||
if (value && !cleanText(req?.[field])) fill[field] = value
|
||||
}
|
||||
return fill
|
||||
}
|
||||
|
||||
// 批准、派发和六部回报共用这一份有效快照:需求原字段 + 中书补缺。
|
||||
function effectiveRequirementSnapshot(task, req) {
|
||||
return { ...requirementSnapshot(req), ...requirementFillOf(task, req) }
|
||||
}
|
||||
|
||||
// 作废当前投递:回写只认投递标识与领取者,清掉领取者即可让迟到回写失效。
|
||||
function voidDelivery(task) {
|
||||
if (!task) return
|
||||
task.deliveryState = 'none'
|
||||
task.sendingOwner = null
|
||||
task.deliveryOwner = null
|
||||
}
|
||||
|
||||
// 阶段切换统一登记一次待发投递,并记下发送成功后要写入的状态(恢复时直接沿用)。
|
||||
function queueDelivery(task, status, now = Date.now()) {
|
||||
task.deliveryId = randomUUID()
|
||||
task.deliveryState = 'pending'
|
||||
task.deliveryStatus = status
|
||||
task.deliveryOwner = null
|
||||
task.sendingOwner = null
|
||||
task.deliveryAttemptAt = now
|
||||
return task.deliveryId
|
||||
}
|
||||
|
||||
// 首发与重投共用同一份正文:任务说明、需求快照、阶段提示和项目记忆。
|
||||
function taskDeliveryText(task, memoryText) {
|
||||
const detail = [
|
||||
`【任务 ${task.id}】${task.title}`,
|
||||
task.goal ? `任务说明:${task.goal}` : '',
|
||||
task.requirement ? `用户原话:${task.requirement}` : '',
|
||||
task.requirementSnapshot?.scope ? `范围:${task.requirementSnapshot.scope}` : '',
|
||||
task.requirementSnapshot?.nonGoals ? `非目标:${task.requirementSnapshot.nonGoals}` : '',
|
||||
task.requirementSnapshot?.acceptanceCriteria ? `验收标准:${task.requirementSnapshot.acceptanceCriteria}` : '',
|
||||
workflowStageHint(task),
|
||||
].filter(Boolean).join('\n')
|
||||
return [memoryText, detail].filter(Boolean).join('\n\n')
|
||||
}
|
||||
|
||||
function invalidateRequirementWork(project, requirementId, nextRevision, now) {
|
||||
for (const approval of project.approvals ?? []) {
|
||||
if (approval.requirementId === requirementId && approval.status === 'approved') {
|
||||
|
|
@ -134,15 +194,18 @@ function invalidateRequirementWork(project, requirementId, nextRevision, now) {
|
|||
task.status = 'returned'
|
||||
task.blockedReason = `需求已更新到 v${nextRevision},停止新增工作并报告是否需要重新确认`
|
||||
}
|
||||
voidDelivery(task)
|
||||
task.updatedAt = now
|
||||
}
|
||||
}
|
||||
|
||||
function handOffReviewedTask(project, task, requirement, now, approvedBy) {
|
||||
project.approvalSeq = (project.approvalSeq ?? 0) + 1
|
||||
// 批准范围取任务上的有效快照:中书补缺或退回后的修订都以这一份为准。
|
||||
const approvedScope = cleanText(task.requirementSnapshot?.scope) || cleanText(requirement.scope)
|
||||
const approval = {
|
||||
id: 'AP-' + String(project.approvalSeq).padStart(3, '0'),
|
||||
requirementId: requirement.id, requirementRevision: requirement.revision, scope: requirement.scope,
|
||||
requirementId: requirement.id, requirementRevision: requirement.revision, scope: approvedScope,
|
||||
status: 'approved', approvedAt: now, approvedBy,
|
||||
}
|
||||
project.approvals ??= []
|
||||
|
|
@ -172,13 +235,20 @@ function taskDecisionBlock(task) {
|
|||
}
|
||||
}
|
||||
|
||||
function projectTask(project, task) {
|
||||
if (!task.workflowBlockage) return { ...task }
|
||||
const { workflowBlockage, ...rest } = task
|
||||
const current = workflowBlockageOf(project, task)
|
||||
return current ? { ...rest, workflowBlockage: current } : rest
|
||||
}
|
||||
|
||||
function workflowStageHint(task) {
|
||||
const hints = {
|
||||
zhongshu_draft: '请使用 sansheng_workflow_submit 提交拟案;拟案阶段只读调查,不得修改工程、不得向六部派工。',
|
||||
menxia_review: '请使用 sansheng_workflow_review 审核:通过或退回中书;不得直接向六部派工。',
|
||||
zhongshu_draft: '根据用户原话和已确认内容给出简短拟案;需求缺少范围、非目标或验收标准时,用 sansheng_workflow_submit 的结构化字段补入任务快照后再交门下,退回后可修订自己补的字段。拟案阶段只读。',
|
||||
menxia_review: '用 sansheng_workflow_review 提交审核,批准前确认范围与验收标准齐全。通过后系统交尚书,发现实质问题时说明原因退回中书补齐。',
|
||||
awaiting_execution_approval: '此方案等待用户在「待你处理」中确认。',
|
||||
shangshu_dispatch: '门下已通过方案。请使用 sansheng_workflow_dispatch 向六部分派获批任务;不得超出批准范围。',
|
||||
department_exec: '请执行获批任务,并使用 sansheng_task_report 回报真实状态与结果。',
|
||||
department_exec: '按获批范围执行。用 sansheng_task_report 提交完成结果或具体失败原因。',
|
||||
menxia_acceptance: '请使用 sansheng_workflow_accept 验收;未通过则退回尚书省。',
|
||||
lead_delivery: '请向用户交付真实结果;不得代替部门伪造或改写执行结果。',
|
||||
reconfirm: '需求已变更,旧授权失效;请与用户重新商讨。',
|
||||
|
|
@ -452,7 +522,7 @@ export class SanshengService {
|
|||
await this.store.ensureLoaded()
|
||||
const project = this.store.get(projectId)
|
||||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
return { tasks: [...(project.tasks ?? [])] }
|
||||
return { tasks: (project.tasks ?? []).map(task => projectTask(project, task)) }
|
||||
}
|
||||
|
||||
// 只读任务汇总:按状态/主责席位统计,并返回可追溯的任务明细。
|
||||
|
|
@ -496,6 +566,7 @@ export class SanshengService {
|
|||
note: task.note ?? '',
|
||||
resultSessionId: task.resultSessionId ?? null,
|
||||
deliveryState: task.deliveryState ?? 'none',
|
||||
workflowBlockage: workflowBlockageOf(project, task),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
|
@ -582,7 +653,7 @@ export class SanshengService {
|
|||
const project = this.store.get(projectId)
|
||||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
return {
|
||||
requirements: structuredClone(project.requirements ?? []),
|
||||
requirements: (project.requirements ?? []).map(requirementView),
|
||||
approvals: structuredClone(project.approvals ?? []),
|
||||
}
|
||||
}
|
||||
|
|
@ -687,14 +758,17 @@ export class SanshengService {
|
|||
}
|
||||
// 丞相根据当前对话选定需求,只有存在唯一候选时才允许省略编号。
|
||||
let effectiveId = cleanText(requirementId).toUpperCase()
|
||||
const mentioned = [...new Set((command.match(/R-\d{3,}/gi) ?? []).map(id => id.toUpperCase()))]
|
||||
if (/^\d{3,}$/.test(effectiveId)) effectiveId = 'R-' + effectiveId
|
||||
const fullIds = Array.from(command.matchAll(/\bR-(\d{3,})\b/gi), match => 'R-' + match[1])
|
||||
const shortIds = Array.from(command.matchAll(/(?:发布|下派)\s*(\d{3,})\b/g), match => 'R-' + match[1])
|
||||
const mentioned = [...new Set([...fullIds, ...shortIds])]
|
||||
if (mentioned.length === 1) {
|
||||
if (effectiveId && mentioned[0] !== effectiveId) throw new ServiceError('sansheng/requirement-conflict', '消息中的需求编号与待下派需求不一致')
|
||||
effectiveId = mentioned[0]
|
||||
}
|
||||
const projectBefore = this.store.get(projectId)
|
||||
if (!effectiveId && command) {
|
||||
const ready = (projectBefore.requirements ?? []).filter(item => item.status === 'ready' && !requirementReadyProblem(item))
|
||||
const ready = (projectBefore.requirements ?? []).filter(item => requirementStatusOf(item) === 'ready')
|
||||
if (ready.length === 1) effectiveId = ready[0].id
|
||||
else if (ready.length > 1) {
|
||||
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-ambiguous', { candidates: ready.map(item => item.id), error: '多个待发布需求' })
|
||||
|
|
@ -710,7 +784,7 @@ export class SanshengService {
|
|||
}
|
||||
if (!command || !sessionId || !Number.isSafeInteger(commandSeq) || !commandRef?.messageId) {
|
||||
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-invalid', { error: '未检测到明确发布命令' })
|
||||
throw new ServiceError('sansheng/publish-not-explicit', `请先与用户确认是否下派 ${effectiveId}`)
|
||||
throw new ServiceError('sansheng/current-user-message-unavailable', '宿主未能验证本轮用户消息,本次下派没有执行')
|
||||
}
|
||||
const expectedRevision = Number(input.expectedRevision)
|
||||
let published
|
||||
|
|
@ -722,7 +796,8 @@ export class SanshengService {
|
|||
const req = (project.requirements ?? []).find(item => item.id === effectiveId)
|
||||
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${effectiveId} 不存在`)
|
||||
if (Number.isFinite(expectedRevision) && req.revision !== expectedRevision) throw new ServiceError('sansheng/requirement-conflict', `需求已更新到 v${req.revision},发布命令基于 v${expectedRevision},已失效`)
|
||||
if (req.status !== 'ready') throw new ServiceError('sansheng/requirement-not-ready', `需求 ${req.id} 当前状态为 ${req.status},只有「待发布」的需求可以发布`)
|
||||
const currentStatus = requirementStatusOf(req)
|
||||
if (currentStatus !== 'ready') throw new ServiceError('sansheng/requirement-not-ready', `需求 ${req.id} 当前状态为 ${currentStatus},只有「待发布」的需求可以发布`)
|
||||
if (input.authorization === 'clarified' && (req.dispatchAuthorization?.sessionId !== sessionId || req.dispatchAuthorization.seq >= commandSeq)) {
|
||||
throw new ServiceError('sansheng/publish-not-explicit', '这项需求缺少同一会话中有效的澄清后下派授权')
|
||||
}
|
||||
|
|
@ -731,12 +806,11 @@ export class SanshengService {
|
|||
const duplicate = (project.tasks ?? []).find(task => task.requirementId === req.id && task.requirementRevision === req.revision && task.kind === 'workflow' && OPEN_TASK_STATUS.has(task.status))
|
||||
if (duplicate) throw new ServiceError('sansheng/requirement-duplicate', `需求 ${req.id} v${req.revision} 已发布,不能重复发布`)
|
||||
const now = Date.now()
|
||||
const deliveryId = randomUUID()
|
||||
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||||
const task = emptyTask({
|
||||
id: `task-${project.taskSeq}`,
|
||||
title: `${req.id} · ${req.title}`,
|
||||
goal: req.summary || req.scope,
|
||||
goal: req.summary || req.scope || req.title,
|
||||
requirement: req.originalText,
|
||||
ownerSeatId: 'zhongshu',
|
||||
kind: 'workflow',
|
||||
|
|
@ -749,10 +823,7 @@ export class SanshengService {
|
|||
task.blockedReason = '中书省拟案中'
|
||||
task.executionAuthorizedAtDispatch = true
|
||||
task.publishCommandRef = commandRef.messageId
|
||||
task.deliveryId = deliveryId
|
||||
task.deliveryState = 'pending'
|
||||
task.deliveryAttemptAt = now
|
||||
task.deliveryOwner = null
|
||||
const deliveryId = queueDelivery(task, 'dispatched', now)
|
||||
if (!Array.isArray(project.tasks)) project.tasks = []
|
||||
project.tasks.push(task)
|
||||
delete req.dispatchAuthorization
|
||||
|
|
@ -807,6 +878,8 @@ export class SanshengService {
|
|||
if (actor.seatId !== 'zhongshu') throw new ServiceError('sansheng/forbidden', '只有中书省可以提交拟案')
|
||||
const draft = cleanText(input.draft)
|
||||
if (!draft) throw new ServiceError('sansheng/invalid', '拟案内容不能为空')
|
||||
const fill = {}
|
||||
for (const field of REQUIREMENT_FILL_FIELDS) fill[field] = cleanText(input[field])
|
||||
const next = await this.store.mutate(s => {
|
||||
const project = s.projects[projectId]
|
||||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
|
|
@ -816,6 +889,17 @@ export class SanshengService {
|
|||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||
if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,旧任务不能再推进')
|
||||
const now = Date.now()
|
||||
// 中书补缺只写任务快照:需求正文、标题、原话和版本都不动;退回重提时可改自己补的字段。
|
||||
const filledFields = []
|
||||
const keptFields = []
|
||||
const nextFill = { ...(task.requirementFill ?? {}) }
|
||||
for (const field of REQUIREMENT_FILL_FIELDS) {
|
||||
if (!fill[field]) continue
|
||||
if (cleanText(req[field])) { keptFields.push(field); continue }
|
||||
nextFill[field] = fill[field]
|
||||
filledFields.push(field)
|
||||
}
|
||||
task.requirementFill = nextFill
|
||||
task.draft = draft
|
||||
task.stage = 'menxia_review'
|
||||
task.ownerSeatId = 'menxia'
|
||||
|
|
@ -823,19 +907,21 @@ export class SanshengService {
|
|||
task.blockedReason = '待门下省审核'
|
||||
task.lastTransitionId = randomUUID()
|
||||
appendLeadReport(s, projectId, task, 'zhongshu_submit', draft)
|
||||
task.deliveryState = 'none'
|
||||
queueDelivery(task, 'dispatched', now)
|
||||
task.result = null
|
||||
task.resultAt = null
|
||||
task.updatedAt = now
|
||||
// 有效快照 = 同版本需求字段 + 中书补缺;门下、会商、批准和派发都读这一份。
|
||||
task.requirementSnapshot = effectiveRequirementSnapshot(task, req)
|
||||
req.status = 'published'
|
||||
req.blockedReason = '门下省审核中'
|
||||
req.updatedAt = now
|
||||
project.updatedAt = now
|
||||
project.revision = (project.revision ?? 0) + 1
|
||||
return { task: { ...task } }
|
||||
return { task: { ...task }, filledFields, keptFields }
|
||||
})
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { force: true })
|
||||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task, filledFields: next.filledFields, keptFields: next.keptFields }
|
||||
}
|
||||
|
||||
async workflowReview(projectId, taskId, input = {}, actor = {}) {
|
||||
|
|
@ -866,6 +952,12 @@ export class SanshengService {
|
|||
req.blockedReason = `门下退回:${note}`
|
||||
} else {
|
||||
if (!cleanText(task.draft)) throw new ServiceError('sansheng/invalid', '中书尚未提交拟案,不能审核通过')
|
||||
// 执行批准使用任务上的有效快照:需求字段优先,中书补缺或退回后的修订随任务走。
|
||||
const effective = effectiveRequirementSnapshot(task, req)
|
||||
if (!cleanText(effective.scope) || !cleanText(effective.acceptanceCriteria)) {
|
||||
throw new ServiceError('sansheng/requirement-incomplete', '需求缺少范围或验收标准,请退回中书省在拟案中补齐后再批准')
|
||||
}
|
||||
task.requirementSnapshot = effective
|
||||
if (task.executionAuthorizedAtDispatch) {
|
||||
handOffReviewedTask(project, task, req, now, 'menxia')
|
||||
} else {
|
||||
|
|
@ -882,15 +974,14 @@ export class SanshengService {
|
|||
}
|
||||
task.lastTransitionId = randomUUID()
|
||||
appendLeadReport(s, projectId, task, action === 'return' ? 'menxia_return' : 'menxia_approve', note || '审核通过')
|
||||
task.deliveryId = randomUUID()
|
||||
task.deliveryState = 'pending'
|
||||
queueDelivery(task, task.status, now)
|
||||
task.updatedAt = now
|
||||
req.updatedAt = now
|
||||
project.updatedAt = now
|
||||
project.revision = (project.revision ?? 0) + 1
|
||||
return { task: { ...task } }
|
||||
})
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId, keepStatus: true })
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
|
||||
}
|
||||
|
||||
|
|
@ -1003,15 +1094,15 @@ export class SanshengService {
|
|||
if (value === 'cancel') {
|
||||
task.status = 'cancelled'
|
||||
task.blockedReason = '用户结束旧任务'
|
||||
voidDelivery(task)
|
||||
requirement.status = 'ready'
|
||||
requirement.blockedReason = requirementBlockedReason(requirement)
|
||||
requirement.updatedAt = decision.answeredAt
|
||||
return { decision }
|
||||
}
|
||||
handOffReviewedTask(project, task, requirement, decision.answeredAt, 'user')
|
||||
task.deliveryId = randomUUID()
|
||||
task.deliveryState = 'pending'
|
||||
return { decision, deliveryId: task.deliveryId }
|
||||
const deliveryId = queueDelivery(task, 'dispatched', decision.answeredAt)
|
||||
return { decision, deliveryId }
|
||||
}
|
||||
const request = task.consultations?.findLast(entry => entry.toSeatIds.includes('lead'))
|
||||
const toSeatIds = [...new Set([task.ownerSeatId, request?.fromSeatId].filter(seat => seat && seat !== 'lead'))]
|
||||
|
|
@ -1053,6 +1144,9 @@ export class SanshengService {
|
|||
throw new ServiceError('sansheng/approval-invalid', '执行批准无效或已过期,不能向六部派工')
|
||||
}
|
||||
const now = Date.now()
|
||||
// 派发沿用批准时的有效快照:用户需求字段优先,中书补缺或修订随任务走。
|
||||
const effective = effectiveRequirementSnapshot(task, req)
|
||||
task.requirementSnapshot = effective
|
||||
const children = []
|
||||
for (const assignment of assignments) {
|
||||
const seatId = cleanText(assignment.seatId)
|
||||
|
|
@ -1060,7 +1154,7 @@ export class SanshengService {
|
|||
const child = emptyTask({
|
||||
id: `task-${project.taskSeq}`,
|
||||
title: cleanText(assignment.title),
|
||||
goal: cleanText(assignment.goal) || req.scope,
|
||||
goal: cleanText(assignment.goal) || effective.scope || effective.title,
|
||||
requirement: req.originalText,
|
||||
ownerSeatId: seatId,
|
||||
kind: 'execution',
|
||||
|
|
@ -1072,10 +1166,9 @@ export class SanshengService {
|
|||
now,
|
||||
})
|
||||
child.approvalScope = approval.scope
|
||||
child.requirementSnapshot = requirementSnapshot(req)
|
||||
child.requirementSnapshot = { ...effective }
|
||||
child.blockedReason = '六部执行中'
|
||||
child.deliveryId = randomUUID()
|
||||
child.deliveryState = 'pending'
|
||||
queueDelivery(child, 'dispatched', now)
|
||||
project.tasks.push(child)
|
||||
children.push({ ...child })
|
||||
}
|
||||
|
|
@ -1084,7 +1177,7 @@ export class SanshengService {
|
|||
task.blockedReason = '六部执行中'
|
||||
task.lastTransitionId = randomUUID()
|
||||
appendLeadReport(s, projectId, task, 'shangshu_dispatch', assignmentSummary)
|
||||
task.deliveryState = 'none'
|
||||
voidDelivery(task)
|
||||
task.updatedAt = now
|
||||
req.blockedReason = '六部执行中'
|
||||
req.updatedAt = now
|
||||
|
|
@ -1125,7 +1218,7 @@ export class SanshengService {
|
|||
task.blockedReason = '待门下省验收'
|
||||
task.lastTransitionId = randomUUID()
|
||||
appendLeadReport(s, projectId, task, 'shangshu_summarize', summary)
|
||||
task.deliveryState = 'none'
|
||||
queueDelivery(task, 'dispatched', now)
|
||||
task.updatedAt = now
|
||||
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||
if (req) { req.blockedReason = '门下验收中'; req.updatedAt = now }
|
||||
|
|
@ -1133,7 +1226,7 @@ export class SanshengService {
|
|||
project.revision = (project.revision ?? 0) + 1
|
||||
return { task: { ...task } }
|
||||
})
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { force: true })
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
|
||||
}
|
||||
|
||||
|
|
@ -1167,13 +1260,13 @@ export class SanshengService {
|
|||
}
|
||||
task.lastTransitionId = randomUUID()
|
||||
appendLeadReport(s, projectId, task, action === 'reject' ? 'menxia_accept_return' : 'menxia_accept', note || '验收通过')
|
||||
task.deliveryState = 'none'
|
||||
queueDelivery(task, task.status, now)
|
||||
task.updatedAt = now
|
||||
project.updatedAt = now
|
||||
project.revision = (project.revision ?? 0) + 1
|
||||
return { task: { ...task } }
|
||||
})
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { force: true, keepStatus: true })
|
||||
const dispatched = await this.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||||
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
|
||||
}
|
||||
|
||||
|
|
@ -1192,6 +1285,7 @@ export class SanshengService {
|
|||
task.status = 'done'
|
||||
task.deliveryNote = deliveryNote
|
||||
task.deliveredAt = now
|
||||
voidDelivery(task)
|
||||
task.deliveredBySessionId = actor.sessionId ?? null
|
||||
task.lastTransitionId = randomUUID()
|
||||
task.blockedReason = ''
|
||||
|
|
@ -1239,17 +1333,26 @@ export class SanshengService {
|
|||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
let task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||
if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工;请新建任务保留历史结果')
|
||||
// 同一任务已成功投递时不重复刷屏;修改要求后由 taskRevise 显式 force 重发。
|
||||
if (task.deliveryState === 'accepted' && task.status === 'dispatched' && !options.force) {
|
||||
return { task: { ...task }, delivered: true, duplicate: true }
|
||||
}
|
||||
// R-002:sending 表示已经调用过 followup、结果未知,禁止自动盲发;unknown 只能走显式 redispatchTask。
|
||||
if (task.deliveryState === 'sending') {
|
||||
return { task: { ...task }, delivered: false, duplicate: false, pending: true, reason: 'sending' }
|
||||
}
|
||||
if (task.deliveryState === 'unknown') {
|
||||
return { task: { ...task }, delivered: false, duplicate: false, unknown: true, reason: 'delivery-unknown' }
|
||||
const redispatch = options.redispatch === true
|
||||
const requestedId = typeof options.deliveryId === 'string' && options.deliveryId.trim() ? options.deliveryId.trim() : null
|
||||
if (redispatch) {
|
||||
// 重投只认投递结果未知、且任务没有结束的记录;同一 deliveryId 人工核对后只发一次。
|
||||
if (!requestedId || task.deliveryId !== requestedId) throw new ServiceError('sansheng/conflict', '任务投递标识已变化,拒绝重投')
|
||||
if (task.deliveryState !== 'unknown') throw new ServiceError('sansheng/invalid', '只有投递结果未知的任务可以重投')
|
||||
if (['cancelled', 'done', 'reconfirm'].includes(task.status)) throw new ServiceError('sansheng/invalid', '已取消、已完成或待重新确认的任务不能重投')
|
||||
} else {
|
||||
if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工;请新建任务保留历史结果')
|
||||
// 同一投递标识(或未指定标识)的已接收任务不重复刷屏;改要求与阶段切换会先作废旧投递。
|
||||
if (task.deliveryState === 'accepted' && (!requestedId || task.deliveryId === requestedId)) {
|
||||
return { task: { ...task }, delivered: true, duplicate: true, deliveryState: 'accepted' }
|
||||
}
|
||||
if (requestedId && task.deliveryId !== requestedId) throw new ServiceError('sansheng/conflict', '任务投递标识已变化,拒绝重复投递')
|
||||
if (task.deliveryState === 'sending') {
|
||||
return { task: { ...task }, delivered: false, duplicate: false, pending: true, reason: 'sending', deliveryState: 'sending' }
|
||||
}
|
||||
if (task.deliveryState === 'unknown') {
|
||||
return { task: { ...task }, delivered: false, duplicate: false, unknown: true, reason: 'delivery-unknown', deliveryState: 'unknown' }
|
||||
}
|
||||
}
|
||||
let seat = project.seats[task.ownerSeatId]
|
||||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||
|
|
@ -1260,6 +1363,9 @@ export class SanshengService {
|
|||
throw new ServiceError('sansheng/seat-unbound', `「${SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId}」的会话还没开启成功,请稍后重试`)
|
||||
}
|
||||
}
|
||||
if (typeof this.seatDelivery?.deliverToSeat !== 'function') {
|
||||
throw new ServiceError('sansheng/delivery-unavailable', '宿主未提供任务投递接口')
|
||||
}
|
||||
project = this.store.get(projectId)
|
||||
task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||
|
|
@ -1268,34 +1374,29 @@ export class SanshengService {
|
|||
stage: task.stage ?? null,
|
||||
requirementRevision: task.requirementRevision ?? null,
|
||||
}
|
||||
const deliveryId = typeof options.deliveryId === 'string' && options.deliveryId.trim()
|
||||
? options.deliveryId.trim()
|
||||
: (task.deliveryState === 'pending' && task.deliveryId ? task.deliveryId : randomUUID())
|
||||
const deliveryId = requestedId
|
||||
?? (task.deliveryState === 'pending' && task.deliveryId ? task.deliveryId : randomUUID())
|
||||
const attemptId = randomUUID()
|
||||
const memory = normalizeProjectMemory(project.memory, projectId)
|
||||
const memoryText = renderProjectMemory(memory)
|
||||
const detail = [
|
||||
`【任务 ${task.id}】${task.title}`,
|
||||
task.goal ? `任务说明:${task.goal}` : '',
|
||||
task.requirement ? `用户原话:${task.requirement}` : '',
|
||||
task.requirementSnapshot?.scope ? `范围:${task.requirementSnapshot.scope}` : '',
|
||||
task.requirementSnapshot?.nonGoals ? `非目标:${task.requirementSnapshot.nonGoals}` : '',
|
||||
task.requirementSnapshot?.acceptanceCriteria ? `验收标准:${task.requirementSnapshot.acceptanceCriteria}` : '',
|
||||
workflowStageHint(task),
|
||||
].filter(Boolean).join('\n')
|
||||
const text = [memoryText, detail].filter(Boolean).join('\n\n')
|
||||
const text = taskDeliveryText(task, renderProjectMemory(memory))
|
||||
const claim = await this.store.mutate(s => {
|
||||
const targetProject = s.projects[projectId]
|
||||
const target = (targetProject.tasks ?? []).find(item => item.id === taskId)
|
||||
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||
if (target.status === 'done' || target.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工')
|
||||
if (target.deliveryState === 'accepted' && target.status === 'dispatched' && !options.force) {
|
||||
return { claimed: false, duplicate: true, task: { ...target } }
|
||||
}
|
||||
if (target.deliveryState === 'sending') return { claimed: false, reason: 'sending', task: { ...target } }
|
||||
if (target.deliveryState === 'unknown') return { claimed: false, reason: 'delivery-unknown', task: { ...target } }
|
||||
if (options.deliveryId && target.deliveryId !== options.deliveryId) {
|
||||
return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
||||
if (target.status === 'done' || target.status === 'cancelled') return { claimed: false, reason: 'task-closed', task: { ...target } }
|
||||
if (redispatch) {
|
||||
if (target.deliveryId !== deliveryId) return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
||||
if (target.deliveryState !== 'unknown') return { claimed: false, reason: 'not-redispatchable', task: { ...target } }
|
||||
if (['cancelled', 'done', 'reconfirm'].includes(target.status)) return { claimed: false, reason: 'task-closed', task: { ...target } }
|
||||
} else {
|
||||
if (target.deliveryState === 'accepted' && (!requestedId || target.deliveryId === deliveryId)) {
|
||||
return { claimed: false, duplicate: true, task: { ...target } }
|
||||
}
|
||||
if (target.deliveryState === 'sending') return { claimed: false, reason: 'sending', task: { ...target } }
|
||||
if (target.deliveryState === 'unknown') return { claimed: false, reason: 'delivery-unknown', task: { ...target } }
|
||||
if (requestedId && target.deliveryId !== requestedId) return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
||||
// 阶段切换登记的是 pending;若中途被取消或改要求作废,就不能再发。
|
||||
if (requestedId && target.deliveryState !== 'pending') return { claimed: false, reason: 'stage-changed', task: { ...target } }
|
||||
}
|
||||
if (target.ownerSeatId !== expected.ownerSeatId
|
||||
|| (target.stage ?? null) !== expected.stage
|
||||
|
|
@ -1310,71 +1411,82 @@ export class SanshengService {
|
|||
target.deliveryOwner = attemptId
|
||||
target.deliveryAttemptId = attemptId
|
||||
target.deliveryAttemptAt = now
|
||||
// 重投保留阶段切换时存下的目标状态;只有旧数据缺字段时才补 dispatched。
|
||||
if (redispatch) target.deliveryStatus ??= 'dispatched'
|
||||
target.updatedAt = now
|
||||
targetProject.updatedAt = now
|
||||
targetProject.revision = (targetProject.revision ?? 0) + 1
|
||||
return { claimed: true, deliveryId, attemptId, task: { ...target } }
|
||||
})
|
||||
if (!claim.claimed) {
|
||||
if (claim.duplicate) return { task: claim.task, delivered: true, duplicate: true }
|
||||
if (claim.reason === 'sending') return { task: claim.task, delivered: false, duplicate: false, pending: true, reason: 'sending' }
|
||||
if (claim.reason === 'delivery-unknown') return { task: claim.task, delivered: false, duplicate: false, unknown: true, reason: 'delivery-unknown' }
|
||||
if (claim.duplicate) return { task: claim.task, delivered: true, duplicate: true, deliveryState: 'accepted' }
|
||||
if (claim.reason === 'sending') return { task: claim.task, delivered: false, duplicate: false, pending: true, reason: 'sending', deliveryState: 'sending' }
|
||||
if (claim.reason === 'delivery-unknown') return { task: claim.task, delivered: false, duplicate: false, unknown: true, reason: 'delivery-unknown', deliveryState: 'unknown' }
|
||||
if (claim.reason === 'task-closed') throw new ServiceError('sansheng/invalid', '任务已结束,不能投递')
|
||||
if (claim.reason === 'not-redispatchable') throw new ServiceError('sansheng/invalid', '任务已不在可重投状态')
|
||||
throw new ServiceError('sansheng/conflict', '投递领取失败:' + (claim.reason === 'stage-changed' ? '任务阶段已变化' : '投递标识已变化'))
|
||||
}
|
||||
let delivered = false
|
||||
let note = ''
|
||||
let delivery
|
||||
try {
|
||||
if (this.seatDelivery?.deliverToSeat) {
|
||||
const result = await this.seatDelivery.deliverToSeat({
|
||||
sessionId: seat.sessionId, text, taskId: task.id, deliveryId, attemptId,
|
||||
sourceKind: 'sansheng-task', seatId: task.ownerSeatId,
|
||||
verifyClaim: () => {
|
||||
const latest = this.store.get(projectId)
|
||||
const current = latest?.tasks?.find(item => item.id === taskId)
|
||||
const currentSeat = latest?.seats?.[task.ownerSeatId]
|
||||
return !!current && current.deliveryId === deliveryId
|
||||
&& current.deliveryState === 'sending' && current.sendingOwner === attemptId
|
||||
&& currentSeat?.sessionId === seat.sessionId
|
||||
},
|
||||
})
|
||||
delivered = result?.status === 'sent'
|
||||
if (!delivered) note = `发送失败:${result?.reason ?? result?.status ?? 'unknown'}`
|
||||
} else {
|
||||
await this._deliverInternal(seat.sessionId, text, internalSource('sansheng-task', { seatId: task.ownerSeatId, taskId: task.id }))
|
||||
delivered = true
|
||||
}
|
||||
delivery = await this.seatDelivery.deliverToSeat({
|
||||
sessionId: seat.sessionId, text, taskId: task.id, deliveryId, attemptId,
|
||||
sourceKind: 'sansheng-task', seatId: task.ownerSeatId,
|
||||
// 同步复核:领取仍属于本次尝试、席位仍是同一会话;返回后立即 followup。
|
||||
verifyClaim: () => {
|
||||
const latest = this.store.get(projectId)
|
||||
const current = latest?.tasks?.find(item => item.id === taskId)
|
||||
const currentSeat = latest?.seats?.[task.ownerSeatId]
|
||||
return !!current && current.deliveryId === deliveryId
|
||||
&& current.deliveryState === 'sending' && current.sendingOwner === attemptId
|
||||
&& currentSeat?.sessionId === seat.sessionId
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
note = `发送失败:${error?.message ?? error}`
|
||||
delivery = { status: 'unknown', reason: 'delivery-error', error: error?.message ?? String(error) }
|
||||
}
|
||||
const outcome = delivery.status === 'sent' ? 'sent' : (delivery.status === 'not-sent' ? 'not-sent' : 'unknown')
|
||||
const activeDecisions = memory.decisions.filter(item => item.status === 'active').map(item => item.id)
|
||||
const written = await this.store.mutate(s => {
|
||||
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||||
if (!target) return { applied: false, task: null }
|
||||
// 回写必须同 deliveryId + 同领取者 + 同阶段,绝不覆盖更晚阶段。
|
||||
if (target.deliveryId !== deliveryId || target.sendingOwner !== attemptId
|
||||
|| (target.stage ?? null) !== expected.stage
|
||||
|| target.ownerSeatId !== expected.ownerSeatId) {
|
||||
// 回写只认同一次投递的 deliveryId 与领取者;取消、改要求、阶段切换会清掉领取者。
|
||||
if (target.deliveryId !== deliveryId || target.sendingOwner !== attemptId) {
|
||||
return { applied: false, task: { ...target } }
|
||||
}
|
||||
const now = Date.now()
|
||||
target.status = options.status ? options.status : (options.keepStatus ? target.status : (delivered ? 'dispatched' : 'prepared'))
|
||||
target.note = delivered ? '' : note
|
||||
target.sessionId = seat.sessionId
|
||||
target.dispatchedAt = now
|
||||
target.updatedAt = now
|
||||
target.contextRevision = memory.revision
|
||||
target.contextHash = memory.contentHash
|
||||
target.decisionIds = activeDecisions
|
||||
target.sourceRefs = memory.sources.slice(0, 20)
|
||||
target.deliveryState = delivered ? 'accepted' : 'unknown'
|
||||
target.deliveryOwner = null
|
||||
target.sendingOwner = null
|
||||
target.contextSyncState = delivered ? 'provided' : 'observed'
|
||||
target.deliveryOwner = null
|
||||
if (outcome === 'sent') {
|
||||
target.status = target.deliveryStatus ?? (target.status === 'draft' ? 'dispatched' : target.status)
|
||||
target.note = ''
|
||||
target.sessionId = seat.sessionId
|
||||
target.dispatchedAt = now
|
||||
target.contextRevision = memory.revision
|
||||
target.contextHash = memory.contentHash
|
||||
target.decisionIds = activeDecisions
|
||||
target.sourceRefs = memory.sources.slice(0, 20)
|
||||
target.deliveryState = 'accepted'
|
||||
target.contextSyncState = 'provided'
|
||||
} else {
|
||||
target.deliveryState = outcome === 'not-sent' ? 'pending' : 'unknown'
|
||||
target.contextSyncState = 'observed'
|
||||
target.note = (outcome === 'not-sent' ? '未发出:' : '发送结果未知:')
|
||||
+ (delivery.reason ?? delivery.status ?? 'unknown')
|
||||
+ (delivery.error ? '(' + delivery.error + ')' : '')
|
||||
}
|
||||
target.updatedAt = now
|
||||
s.projects[projectId].updatedAt = now
|
||||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||
return { applied: true, task: { ...target } }
|
||||
})
|
||||
return { task: written.task ?? { ...task }, delivered, duplicate: false, applied: written.applied !== false }
|
||||
return {
|
||||
task: written.task ?? { ...task },
|
||||
delivered: outcome === 'sent',
|
||||
duplicate: false,
|
||||
applied: written.applied !== false,
|
||||
deliveryState: outcome === 'sent' ? 'accepted' : (outcome === 'not-sent' ? 'pending' : 'unknown'),
|
||||
reason: delivery.reason ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
// R-002:启动/重连恢复。pending 表示尚未开始发送,可条件领取一次;sending 遗留只标 unknown,绝不自动重发。
|
||||
|
|
@ -1385,8 +1497,7 @@ export class SanshengService {
|
|||
for (const project of this.store.list()) {
|
||||
for (const task of project.tasks ?? []) {
|
||||
if (task.deliveryState === 'pending' && !['done', 'cancelled', 'reconfirm'].includes(task.status)) {
|
||||
const keepStatus = ['awaiting_execution_approval', 'menxia_review'].includes(task.stage) || task.status === 'returned'
|
||||
pending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId, keepStatus })
|
||||
pending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
||||
} else if (task.deliveryState === 'sending') {
|
||||
sending.push({ projectId: project.id, taskId: task.id, deliveryId: task.deliveryId })
|
||||
}
|
||||
|
|
@ -1409,7 +1520,8 @@ export class SanshengService {
|
|||
const recovered = []
|
||||
for (const item of pending) {
|
||||
try {
|
||||
const result = await this.taskDispatch(item.projectId, item.taskId, { deliveryId: item.deliveryId, recovery: true, keepStatus: item.keepStatus })
|
||||
const options = item.deliveryId ? { deliveryId: item.deliveryId } : {}
|
||||
const result = await this.taskDispatch(item.projectId, item.taskId, options)
|
||||
recovered.push({ projectId: item.projectId, taskId: item.taskId, delivered: result.delivered, reason: result.reason ?? null })
|
||||
} catch (error) {
|
||||
recovered.push({ projectId: item.projectId, taskId: item.taskId, delivered: false, error: error?.message ?? String(error) })
|
||||
|
|
@ -1419,7 +1531,7 @@ export class SanshengService {
|
|||
}
|
||||
|
||||
|
||||
// R-007:只对明确 blocked 且 deliveryId 匹配的旧任务安全重投一次;不参与 R-002/R-003 首次领取。
|
||||
// R-007:只对投递结果未知且未结束的任务,按 expectedDeliveryId 人工核对后重投一次。
|
||||
async redispatchTask(projectId, taskId, input = {}) {
|
||||
await this.store.ensureLoaded()
|
||||
const project = this.store.get(projectId)
|
||||
|
|
@ -1430,86 +1542,15 @@ export class SanshengService {
|
|||
if (!expectedDeliveryId || task.deliveryId !== expectedDeliveryId) {
|
||||
throw new ServiceError('sansheng/conflict', '任务投递标识已变化,拒绝重投')
|
||||
}
|
||||
if (task.status !== 'blocked' && task.deliveryState !== 'unknown') {
|
||||
throw new ServiceError('sansheng/invalid', '只有明确 blocked 或投递状态 unknown 的任务可以安全重投')
|
||||
}
|
||||
const seat = project.seats?.[task.ownerSeatId]
|
||||
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||
throw new ServiceError('sansheng/seat-unbound', '主责部门会话未就绪,不能重投')
|
||||
}
|
||||
const attemptId = randomUUID()
|
||||
const expected = { ownerSeatId: task.ownerSeatId, stage: task.stage ?? null }
|
||||
const claim = await this.store.mutate(s => {
|
||||
const targetProject = s.projects[projectId]
|
||||
const target = targetProject.tasks.find(item => item.id === taskId)
|
||||
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||
if (target.deliveryId !== expectedDeliveryId) return { claimed: false, reason: 'delivery-mismatch', task: { ...target } }
|
||||
if (target.deliveryState === 'sending') return { claimed: false, reason: 'sending', task: { ...target } }
|
||||
if (target.status !== 'blocked' && target.deliveryState !== 'unknown') {
|
||||
return { claimed: false, reason: 'not-redispatchable', task: { ...target } }
|
||||
}
|
||||
if (target.ownerSeatId !== expected.ownerSeatId || (target.stage ?? null) !== expected.stage) {
|
||||
return { claimed: false, reason: 'stage-changed', task: { ...target } }
|
||||
}
|
||||
const now = Date.now()
|
||||
target.deliveryState = 'sending'
|
||||
target.sendingOwner = attemptId
|
||||
target.sendingAt = now
|
||||
target.deliveryOwner = attemptId
|
||||
target.deliveryAttemptId = attemptId
|
||||
target.deliveryAttemptAt = now
|
||||
target.lastRedispatchAt = now
|
||||
target.updatedAt = now
|
||||
targetProject.updatedAt = now
|
||||
targetProject.revision = (targetProject.revision ?? 0) + 1
|
||||
return { claimed: true, task: { ...target } }
|
||||
})
|
||||
if (!claim.claimed) {
|
||||
if (claim.reason === 'sending') return { task: claim.task, delivery: { status: 'unknown', reason: 'sending', attemptId } }
|
||||
throw new ServiceError('sansheng/conflict', claim.reason === 'stage-changed'
|
||||
? '任务阶段已变化,拒绝重投'
|
||||
: claim.reason === 'not-redispatchable' ? '任务已不在可重投状态' : '任务投递标识已变化,拒绝重投')
|
||||
}
|
||||
const text = [`【重投任务】${task.title}`, task.goal ? `任务说明:${task.goal}` : '', task.requirement ? `用户原话:${task.requirement}` : ''].filter(Boolean).join('\n')
|
||||
let delivery
|
||||
if (this.seatDelivery?.deliverToSeat) {
|
||||
delivery = await this.seatDelivery.deliverToSeat({
|
||||
sessionId: seat.sessionId, text, taskId: task.id, deliveryId: expectedDeliveryId,
|
||||
attemptId, sourceKind: 'sansheng-task', seatId: task.ownerSeatId,
|
||||
verifyClaim: () => {
|
||||
const latest = this.store.get(projectId)
|
||||
const current = latest?.tasks?.find(item => item.id === taskId)
|
||||
const currentSeat = latest?.seats?.[task.ownerSeatId]
|
||||
return !!current && current.deliveryId === expectedDeliveryId
|
||||
&& current.deliveryState === 'sending' && current.sendingOwner === attemptId
|
||||
&& currentSeat?.sessionId === seat.sessionId
|
||||
},
|
||||
})
|
||||
} else {
|
||||
try {
|
||||
await this._deliverInternal(seat.sessionId, text, internalSource('sansheng-task', { seatId: task.ownerSeatId, taskId: task.id }))
|
||||
delivery = { status: 'sent', attemptId }
|
||||
} catch (error) {
|
||||
delivery = { status: 'unknown', attemptId, error: error?.message ?? String(error) }
|
||||
}
|
||||
}
|
||||
const next = await this.store.mutate(s => {
|
||||
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||||
if (!target || target.deliveryId !== expectedDeliveryId || target.sendingOwner !== attemptId) {
|
||||
return { applied: false, task: target ? { ...target } : null }
|
||||
}
|
||||
target.deliveryState = delivery.status === 'sent' ? 'accepted' : 'unknown'
|
||||
if (delivery.status === 'sent') target.status = 'dispatched'
|
||||
target.deliveryOwner = null
|
||||
target.sendingOwner = null
|
||||
target.lastRedispatchAt = Date.now()
|
||||
target.deliveryAttemptId = attemptId
|
||||
target.updatedAt = Date.now()
|
||||
s.projects[projectId].updatedAt = Date.now()
|
||||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||
return { applied: true, task: { ...target } }
|
||||
})
|
||||
return { task: next.task, delivery, applied: next.applied !== false }
|
||||
const result = await this.taskDispatch(projectId, taskId, { deliveryId: expectedDeliveryId, redispatch: true })
|
||||
const status = result.deliveryState === 'accepted'
|
||||
? 'sent'
|
||||
: (result.deliveryState === 'unknown' || result.reason === 'sending' ? 'unknown' : 'not-sent')
|
||||
return { task: result.task, delivery: { status, reason: result.reason ?? null }, applied: result.applied !== false }
|
||||
}
|
||||
|
||||
async taskGet(projectId, taskId) {
|
||||
|
|
@ -1518,7 +1559,7 @@ export class SanshengService {
|
|||
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||
return { task: { ...task } }
|
||||
return { task: projectTask(project, task) }
|
||||
}
|
||||
|
||||
async taskReport(projectId, taskId, input = {}) {
|
||||
|
|
@ -1587,7 +1628,7 @@ export class SanshengService {
|
|||
task.resultAt = null
|
||||
task.resultSessionId = null
|
||||
task.reportStatus = 'none'
|
||||
task.deliveryState = 'none'
|
||||
voidDelivery(task)
|
||||
task.updatedAt = Date.now()
|
||||
s.projects[projectId].updatedAt = Date.now()
|
||||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||
|
|
@ -1604,6 +1645,7 @@ export class SanshengService {
|
|||
if (!target) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||
if (target.status === 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能取消')
|
||||
target.status = 'cancelled'
|
||||
voidDelivery(target)
|
||||
target.updatedAt = Date.now()
|
||||
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||
return { ...target }
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ function seatToolDefinitions({ store, service, turnCommands, leadBackground }) {
|
|||
|
||||
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) })) }
|
||||
},
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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?.() }
|
||||
}
|
||||
|
|
@ -97,7 +97,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 +108,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,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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: '台账项目二' })
|
||||
|
|
|
|||
|
|
@ -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: [] }
|
||||
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,10 @@ 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)
|
||||
},
|
||||
}
|
||||
sessions.set(sessionId, agent)
|
||||
}
|
||||
|
|
@ -103,7 +108,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 },
|
||||
|
|
|
|||
|
|
@ -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', {
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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, /任务文字故意不写硬约束/)
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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, /已派工/)
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
})
|
||||
|
|
@ -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)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue