refactor(sansheng): split host service into focused domain modules
This commit is contained in:
parent
00014453b9
commit
a69fe5940e
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,180 @@
|
||||||
|
// 丞相非阻塞卡片、集中审批应答与丞相回报查询服务方法。
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { SEATS } from '../../shared/roles.js'
|
||||||
|
import { cleanText } from '../../shared/utils.js'
|
||||||
|
import { ServiceError } from './shared.js'
|
||||||
|
|
||||||
|
const CARD_LIMIT = 200
|
||||||
|
const CARD_KINDS = new Set(['question', 'approval'])
|
||||||
|
|
||||||
|
function normalizeCardOptions(raw, kind) {
|
||||||
|
const options = (Array.isArray(raw) ? raw : []).map(item => ({
|
||||||
|
label: cleanText(item?.label),
|
||||||
|
value: cleanText(item?.value),
|
||||||
|
description: cleanText(item?.description),
|
||||||
|
})).filter(item => item.label && item.value)
|
||||||
|
if (kind === 'approval') {
|
||||||
|
if (options.length === 0) {
|
||||||
|
return [
|
||||||
|
{ label: '同意', value: 'allow', description: '允许这次操作' },
|
||||||
|
{ label: '拒绝', value: 'reject', description: '拒绝这次操作' },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
if (options.length !== 2 || options.some(item => !['allow', 'reject'].includes(item.value))
|
||||||
|
|| new Set(options.map(item => item.value)).size !== 2) {
|
||||||
|
throw new ServiceError('sansheng/card-invalid', '审批卡必须提供 allow 和 reject 两个选项')
|
||||||
|
}
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
if (options.length < 2 || options.length > 5 || new Set(options.map(item => item.value)).size !== options.length) {
|
||||||
|
throw new ServiceError('sansheng/card-invalid', '问题卡需要 2 到 5 个不重复选项')
|
||||||
|
}
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
function capCards(list) {
|
||||||
|
if (list.length > CARD_LIMIT) list.splice(0, list.length - CARD_LIMIT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的卡片、审批与回报查询方法集。 */
|
||||||
|
export const cardApprovalServiceMethods = {
|
||||||
|
async cards(projectId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
return { cards: structuredClone(project.cards ?? []) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async cardGet(cardId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const id = cleanText(cardId)
|
||||||
|
if (!id) throw new ServiceError('sansheng/card-invalid', '缺少 cardId')
|
||||||
|
for (const project of this.store.list()) {
|
||||||
|
const card = (project.cards ?? []).find(item => item.id === id)
|
||||||
|
if (card) return { ok: true, card: structuredClone(card) }
|
||||||
|
}
|
||||||
|
throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||||||
|
},
|
||||||
|
|
||||||
|
// 丞相只能为当前项目挂卡;审批卡的结论仍回到 approval-center 的同一个原生请求。
|
||||||
|
async cardCreate(projectId, input = {}, actor = {}) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以挂卡片')
|
||||||
|
const lead = project.seats?.lead
|
||||||
|
if (lead?.status !== 'bound' || !lead.sessionId) throw new ServiceError('sansheng/seat-unbound', '丞相会话未就绪,不能挂卡片')
|
||||||
|
if (actor.sessionId && actor.sessionId !== lead.sessionId) throw new ServiceError('sansheng/forbidden', '丞相会话已变化')
|
||||||
|
const kind = cleanText(input.kind)
|
||||||
|
if (!CARD_KINDS.has(kind)) throw new ServiceError('sansheng/card-invalid', '卡片类型必须是 question 或 approval')
|
||||||
|
const title = cleanText(input.title)
|
||||||
|
const body = cleanText(input.body)
|
||||||
|
if (!title || title.length > 200) throw new ServiceError('sansheng/card-invalid', '卡片标题必须为 1 至 200 字符')
|
||||||
|
if (!body || body.length > 4000) throw new ServiceError('sansheng/card-invalid', '卡片正文必须为 1 至 4000 字符')
|
||||||
|
const options = normalizeCardOptions(input.options, kind)
|
||||||
|
const now = Date.now()
|
||||||
|
let approval = null
|
||||||
|
if (kind === 'approval') {
|
||||||
|
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用,不能挂审批卡')
|
||||||
|
const approvalId = cleanText(input.approvalId)
|
||||||
|
if (!approvalId) throw new ServiceError('sansheng/card-invalid', '审批卡需要 approvalId')
|
||||||
|
approval = this.approvalCenter.list(projectId).find(item => item.id === approvalId) ?? null
|
||||||
|
if (!approval) throw new ServiceError('sansheng/approval-stale', '审批已处理或不存在,不能挂卡')
|
||||||
|
}
|
||||||
|
const card = {
|
||||||
|
id: cleanText(input.callId) || randomUUID(),
|
||||||
|
kind, title, body,
|
||||||
|
options,
|
||||||
|
approvalId: approval?.id ?? null,
|
||||||
|
seatId: approval?.seatId ?? null,
|
||||||
|
seatLabel: approval?.seatId ? (SEATS[approval.seatId]?.label ?? approval.seatId) : null,
|
||||||
|
tool: approval?.tool ?? null,
|
||||||
|
reason: approval?.reason ?? null,
|
||||||
|
detail: approval?.detail ?? null,
|
||||||
|
projectId,
|
||||||
|
sessionId: lead.sessionId,
|
||||||
|
status: 'pending',
|
||||||
|
answer: null,
|
||||||
|
answerLabel: null,
|
||||||
|
createdAt: now,
|
||||||
|
answeredAt: null,
|
||||||
|
}
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const current = state.projects[projectId]
|
||||||
|
if (!current) return
|
||||||
|
current.cards ??= []
|
||||||
|
current.cards.push(card)
|
||||||
|
capCards(current.cards)
|
||||||
|
current.updatedAt = now
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
})
|
||||||
|
return { ok: true, card: structuredClone(card) }
|
||||||
|
},
|
||||||
|
|
||||||
|
// 答题是普通用户消息(会唤醒丞相);审题结论只走 approval-center,不另造第二套决定。
|
||||||
|
async cardAnswer(cardId, choice, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const id = cleanText(cardId)
|
||||||
|
const value = cleanText(choice)
|
||||||
|
if (!id || !value) throw new ServiceError('sansheng/card-invalid', '缺少 cardId 或选择')
|
||||||
|
let project = null
|
||||||
|
let card = null
|
||||||
|
for (const candidate of this.store.list()) {
|
||||||
|
const found = (candidate.cards ?? []).find(item => item.id === id)
|
||||||
|
if (found) { project = candidate; card = found; break }
|
||||||
|
}
|
||||||
|
if (!project || !card) throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||||||
|
if (card.status === 'answered') return { ok: true, duplicate: true, card: structuredClone(card) }
|
||||||
|
const option = card.options.find(item => item.value === value)
|
||||||
|
if (!option) throw new ServiceError('sansheng/card-invalid', '卡片没有这个选项')
|
||||||
|
const lead = project.seats?.lead
|
||||||
|
if (lead?.status !== 'bound' || !lead.sessionId) throw new ServiceError('sansheng/seat-unbound', '丞相会话未就绪,不能回答卡片')
|
||||||
|
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以回答卡片')
|
||||||
|
if (actor.sessionId && actor.sessionId !== lead.sessionId) throw new ServiceError('sansheng/forbidden', '丞相会话已变化')
|
||||||
|
if (card.kind === 'approval') {
|
||||||
|
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用')
|
||||||
|
await this.approvalCenter.answer(card.approvalId, { projectId: project.id, seatId: 'lead', sessionId: lead.sessionId }, value)
|
||||||
|
} else {
|
||||||
|
const agent = this.host?.agents?.get?.(lead.sessionId)
|
||||||
|
if (!agent || typeof agent.followup !== 'function') throw new ServiceError('sansheng/card-session-unavailable', '丞相会话不可用,回答未送达')
|
||||||
|
const message = this.host?.createUserMessage
|
||||||
|
? await Promise.resolve(this.host.createUserMessage({
|
||||||
|
content: [{ type: 'text', text: `[卡片回答] ${card.title}\n用户选择:${option.label}` }],
|
||||||
|
source: { kind: 'sansheng-card-answer', cardId: card.id, choice: value },
|
||||||
|
}))
|
||||||
|
: { role: 'user', content: [{ type: 'text', text: `[卡片回答] ${card.title}\n用户选择:${option.label}` }], source: { kind: 'sansheng-card-answer', cardId: card.id, choice: value } }
|
||||||
|
await agent.followup(message)
|
||||||
|
}
|
||||||
|
const answered = await this.store.mutate(state => {
|
||||||
|
const current = state.projects[project.id]
|
||||||
|
const target = (current.cards ?? []).find(item => item.id === id)
|
||||||
|
if (!target) throw new ServiceError('sansheng/card-not-found', `卡片 ${id} 不存在`)
|
||||||
|
target.status = 'answered'
|
||||||
|
target.answer = value
|
||||||
|
target.answerLabel = option.label
|
||||||
|
target.answeredAt = Date.now()
|
||||||
|
current.updatedAt = target.answeredAt
|
||||||
|
current.revision = (current.revision ?? 0) + 1
|
||||||
|
return structuredClone(target)
|
||||||
|
})
|
||||||
|
return { ok: true, card: answered }
|
||||||
|
},
|
||||||
|
|
||||||
|
async leadReports(projectId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
if (this.leadReporter) return { reports: await this.leadReporter.list(projectId) }
|
||||||
|
return { reports: structuredClone(project.leadReports ?? []) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async approvals(projectId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
const status = this.approvalCenter?.status?.() ?? { available: false, degraded: true, pendingCount: 0, reason: 'approval-center-unavailable' }
|
||||||
|
return { approvals: status.available ? this.approvalCenter.list(projectId) : [], status }
|
||||||
|
},
|
||||||
|
|
||||||
|
async approvalAnswer(projectId, seatId, input = {}) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
if (!this.approvalCenter) throw new ServiceError('sansheng/approval-degraded', '审批中心不可用,请使用原生审批卡')
|
||||||
|
const seat = project.seats?.[seatId]
|
||||||
|
const sessionId = cleanText(input.sessionId)
|
||||||
|
if (!sessionId || seat?.sessionId !== sessionId) throw new ServiceError('sansheng/approval-stale', '审批会话已变化,请刷新')
|
||||||
|
return this.approvalCenter.answer(input.id, { projectId, seatId, sessionId }, input.choice)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,153 @@
|
||||||
|
// 任务会商与用户裁决服务方法(含历史等待批准决策补丁)。
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { SEATS } from '../../shared/roles.js'
|
||||||
|
import { cleanText } from '../../shared/utils.js'
|
||||||
|
import { internalSource } from '../message-source.js'
|
||||||
|
import { ServiceError, queueDelivery, voidDelivery } from './shared.js'
|
||||||
|
import { handOffReviewedTask, legacyApprovalDecision, requirementBlockedReason } from './requirement-helpers.js'
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的任务会商与决策方法集。 */
|
||||||
|
export const consultationServiceMethods = {
|
||||||
|
async consultTask(projectId, taskId, input, actor) {
|
||||||
|
const text = cleanText(input.text)
|
||||||
|
const toSeatIds = [...new Set(input.toSeatIds ?? [])]
|
||||||
|
if (!text || !toSeatIds.length || toSeatIds.includes(actor.seatId)) {
|
||||||
|
throw new ServiceError('sansheng/invalid', '请指定商议对象及问题或结论')
|
||||||
|
}
|
||||||
|
const requiresDecision = toSeatIds.includes('lead') && input.requiresDecision !== false
|
||||||
|
const { task, entry } = await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
const task = project?.tasks?.find(item => item.id === taskId && item.kind === 'workflow')
|
||||||
|
const requirement = project?.requirements?.find(item => item.id === task?.requirementId)
|
||||||
|
if (!task || ['done', 'cancelled', 'reconfirm'].includes(task.status) || requirement?.revision !== task.requirementRevision) {
|
||||||
|
throw new ServiceError('sansheng/stage-forbidden', '任务已结束或需求已更新')
|
||||||
|
}
|
||||||
|
const seats = new Set(['lead', 'zhongshu', 'menxia', 'shangshu'])
|
||||||
|
for (const child of project.tasks) if (child.parentTaskId === taskId) seats.add(child.ownerSeatId)
|
||||||
|
if (![actor.seatId, ...toSeatIds].every(seat => seats.has(seat))) {
|
||||||
|
throw new ServiceError('sansheng/forbidden', '只有本任务相关席位可以会商')
|
||||||
|
}
|
||||||
|
const entry = { id: randomUUID(), fromSeatId: actor.seatId, toSeatIds, text, requiresDecision, createdAt: Date.now() }
|
||||||
|
task.consultations ??= []
|
||||||
|
task.consultations.push(entry)
|
||||||
|
if (requiresDecision) task.awaitingLeadDecision = true
|
||||||
|
if (actor.seatId === 'lead') task.awaitingLeadDecision = false
|
||||||
|
task.updatedAt = entry.createdAt
|
||||||
|
project.revision += 1
|
||||||
|
return structuredClone({ task, entry })
|
||||||
|
})
|
||||||
|
const snapshot = task.requirementSnapshot ?? {}
|
||||||
|
const context = [snapshot.originalText || task.requirement, snapshot.scope, snapshot.acceptanceCriteria].filter(Boolean).join('\n')
|
||||||
|
const message = [
|
||||||
|
`【任务会商】${task.id} · ${task.title}`,
|
||||||
|
`用户原话与要求:${context}`,
|
||||||
|
`${SEATS[actor.seatId]?.label ?? actor.seatId}:${text}`,
|
||||||
|
'回复用 sansheng_task_consult,填写同一个 taskId。向丞相请示时说明分歧和可选做法。',
|
||||||
|
].join('\n')
|
||||||
|
const currentProject = () => {
|
||||||
|
const project = this.store.get(projectId)
|
||||||
|
const latest = project?.tasks?.find(item => item.id === taskId)
|
||||||
|
const requirement = project?.requirements?.find(item => item.id === task.requirementId)
|
||||||
|
if (!latest || latest.requirementRevision !== task.requirementRevision || requirement?.revision !== task.requirementRevision
|
||||||
|
|| ['done', 'cancelled', 'reconfirm'].includes(latest.status)) {
|
||||||
|
throw new ServiceError('sansheng/stage-forbidden', '任务已变化')
|
||||||
|
}
|
||||||
|
return project
|
||||||
|
}
|
||||||
|
const delivery = await Promise.allSettled(toSeatIds.map(async seatId => {
|
||||||
|
await this.provisioner.enableSeat(projectId, seatId)
|
||||||
|
const project = currentProject()
|
||||||
|
return this._deliverInternal(project.seats[seatId].sessionId, message, internalSource('sansheng-task', { seatId, taskId }))
|
||||||
|
}))
|
||||||
|
return { entry, failedSeatIds: toSeatIds.filter((_id, i) => delivery[i].status === 'rejected') }
|
||||||
|
},
|
||||||
|
|
||||||
|
async requestTaskDecision(projectId, taskId, input, actor) {
|
||||||
|
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '请先把分歧交给丞相')
|
||||||
|
const question = cleanText(input.question)
|
||||||
|
const options = (input.options ?? []).map((label, index) => ({ label: cleanText(label), value: String(index + 1) }))
|
||||||
|
if (!question || options.length < 2 || options.length > 5 || options.some(option => !option.label)) {
|
||||||
|
throw new ServiceError('sansheng/invalid', '请说明需要用户选择的问题并给出 2 到 5 个选项')
|
||||||
|
}
|
||||||
|
return this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
const task = project?.tasks?.find(item => item.id === taskId && item.kind === 'workflow')
|
||||||
|
if (!task || ['done', 'cancelled', 'reconfirm'].includes(task.status)) throw new ServiceError('sansheng/stage-forbidden', '任务已结束或需求已更新')
|
||||||
|
task.decisions ??= []
|
||||||
|
const existing = task.decisions.find(item => item.status === 'pending' && item.question === question)
|
||||||
|
if (existing) return { decision: existing }
|
||||||
|
const decision = { id: randomUUID(), question, options, status: 'pending', createdAt: Date.now() }
|
||||||
|
task.decisions.push(decision)
|
||||||
|
task.awaitingLeadDecision = false
|
||||||
|
task.updatedAt = decision.createdAt
|
||||||
|
project.revision += 1
|
||||||
|
return { decision }
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
async surfaceLegacyApprovals() {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const waiting = task => task.stage === 'awaiting_execution_approval' && task.status === 'waiting_user' && !task.decisions?.some(item => item.kind === 'legacy-approval')
|
||||||
|
if (!this.store.list().some(project => project.tasks?.some(waiting))) return
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
for (const project of Object.values(state.projects)) {
|
||||||
|
for (const task of (project.tasks ?? []).filter(waiting)) {
|
||||||
|
task.decisions ??= []
|
||||||
|
task.decisions.push(legacyApprovalDecision(Date.now()))
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
async answerTaskDecision(projectId, taskId, decisionId, value) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireId(taskId, 'taskId')
|
||||||
|
const result = await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
const task = project?.tasks?.find(item => item.id === taskId)
|
||||||
|
const decision = task?.decisions?.find(item => item.id === decisionId)
|
||||||
|
const option = decision?.options.find(item => item.value === value)
|
||||||
|
if (!task || !option || ['done', 'cancelled', 'reconfirm'].includes(task.status)) throw new ServiceError('sansheng/invalid', '决定已失效或选项无效')
|
||||||
|
if (decision.status === 'answered') {
|
||||||
|
if (decision.answer !== value) throw new ServiceError('sansheng/conflict', '这项决定已有答复')
|
||||||
|
return { decision, duplicate: true }
|
||||||
|
}
|
||||||
|
decision.status = 'answered'
|
||||||
|
decision.answer = value
|
||||||
|
decision.answeredAt = Date.now()
|
||||||
|
task.updatedAt = decision.answeredAt
|
||||||
|
project.revision += 1
|
||||||
|
if (decision.kind === 'legacy-approval') {
|
||||||
|
const requirement = project.requirements.find(item => item.id === task.requirementId)
|
||||||
|
if (task.stage !== 'awaiting_execution_approval' || requirement?.revision !== task.requirementRevision) {
|
||||||
|
throw new ServiceError('sansheng/conflict', '方案已变化,请刷新任务')
|
||||||
|
}
|
||||||
|
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')
|
||||||
|
const deliveryId = queueDelivery(task, 'dispatched')
|
||||||
|
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'))]
|
||||||
|
return { decision, toSeatIds, text: `${decision.question}:${option.label}` }
|
||||||
|
})
|
||||||
|
if (result.deliveryId) {
|
||||||
|
void this.taskDispatch(projectId, taskId, { deliveryId: result.deliveryId }).catch(error => console.warn('[sansheng] 尚书投递失败:', error))
|
||||||
|
}
|
||||||
|
if (result.text && result.toSeatIds.length) {
|
||||||
|
void this.consultTask(projectId, taskId, { text: `用户决定:${result.text}`, toSeatIds: result.toSeatIds }, { seatId: 'lead' })
|
||||||
|
.then(outcome => { if (outcome.failedSeatIds.length) console.warn('[sansheng] 决定通知未送达:', outcome.failedSeatIds) })
|
||||||
|
.catch(error => console.warn('[sansheng] 决定通知失败:', error))
|
||||||
|
}
|
||||||
|
return { decision: result.decision }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,261 @@
|
||||||
|
// 单次领取任务投递、重启未决恢复与人工显式重投服务方法。
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { SEATS } from '../../shared/roles.js'
|
||||||
|
import { normalizeProjectMemory, renderProjectMemory } from '../../shared/project-memory.js'
|
||||||
|
import { ServiceError, queueDelivery, readyForDepartmentSummary } from './shared.js'
|
||||||
|
|
||||||
|
function workflowStageHint(task) {
|
||||||
|
const hints = {
|
||||||
|
zhongshu_draft: '根据用户原话和已确认内容给出简短拟案;需求缺少范围、非目标或验收标准时,用 sansheng_workflow_submit 的结构化字段补入任务快照后再交门下,退回后可修订自己补的字段。拟案阶段只读。',
|
||||||
|
menxia_review: '用 sansheng_workflow_review 提交审核,批准前确认范围与验收标准齐全。通过后系统交尚书,发现实质问题时说明原因退回中书补齐。',
|
||||||
|
awaiting_execution_approval: '此方案等待用户在「待你处理」中确认。',
|
||||||
|
shangshu_dispatch: '门下已通过方案。请使用 sansheng_workflow_dispatch 向六部分派获批任务;不得超出批准范围。',
|
||||||
|
department_exec: task.kind === 'workflow'
|
||||||
|
? '六部子任务均已结束。请用 sansheng_task_list 查看本任务的各子任务真实结果和失败原因,再用 sansheng_workflow_summarize 汇总并提交门下验收。'
|
||||||
|
: '按获批范围执行。用 sansheng_task_report 提交完成结果或具体失败原因。',
|
||||||
|
menxia_acceptance: '请使用 sansheng_workflow_accept 验收;未通过则退回尚书省。',
|
||||||
|
lead_delivery: '请向用户交付真实结果;不得代替部门伪造或改写执行结果。',
|
||||||
|
reconfirm: '需求已变更,旧授权失效;请与用户重新商讨。',
|
||||||
|
}
|
||||||
|
const extra = []
|
||||||
|
if (hints[task.stage]) extra.push(hints[task.stage])
|
||||||
|
if (task.draft && (task.stage === 'menxia_review' || task.stage === 'shangshu_dispatch')) extra.push(`中书拟案:\n${task.draft}`)
|
||||||
|
if (task.reviewNote && task.stage === 'zhongshu_draft') extra.push(`门下退回意见:${task.reviewNote}`)
|
||||||
|
if (task.summary && (task.stage === 'menxia_acceptance' || task.stage === 'lead_delivery')) extra.push(`尚书汇总:\n${task.summary}`)
|
||||||
|
if (task.approvalId) extra.push(`批准编号:${task.approvalId};需求版本:v${task.requirementRevision ?? '?'}`)
|
||||||
|
return extra.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 首发与重投共用同一份正文:任务说明、需求快照、阶段提示和项目记忆。
|
||||||
|
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')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的任务派发、重启恢复与重投方法集。 */
|
||||||
|
export const deliveryServiceMethods = {
|
||||||
|
async taskDispatch(projectId, taskId, options = {}) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
const initialTask = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!initialTask) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
|
const redispatch = options.redispatch === true
|
||||||
|
const requestedId = typeof options.deliveryId === 'string' && options.deliveryId.trim() ? options.deliveryId.trim() : null
|
||||||
|
const needsSeat = redispatch
|
||||||
|
? Boolean(requestedId && initialTask.deliveryId === requestedId && initialTask.deliveryState === 'unknown'
|
||||||
|
&& !['cancelled', 'done', 'reconfirm'].includes(initialTask.status))
|
||||||
|
: (!['done', 'cancelled'].includes(initialTask.status)
|
||||||
|
&& !['accepted', 'sending', 'unknown'].includes(initialTask.deliveryState)
|
||||||
|
&& (!requestedId || initialTask.deliveryId === requestedId))
|
||||||
|
if (needsSeat) {
|
||||||
|
const seat = project.seats?.[initialTask.ownerSeatId]
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
|
// 按需开启:丞相派工时只给出主责部门,由系统用该部门预配置的模型开启会话;丞相不选模型。
|
||||||
|
await this.provisioner.enableSeat(projectId, initialTask.ownerSeatId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (typeof this.seatDelivery?.deliverToSeat !== 'function') {
|
||||||
|
throw new ServiceError('sansheng/delivery-unavailable', '宿主未提供任务投递接口')
|
||||||
|
}
|
||||||
|
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 (redispatch) {
|
||||||
|
if (!requestedId || target.deliveryId !== requestedId) 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.status === 'done' || target.status === 'cancelled') return { claimed: false, reason: 'task-closed', task: { ...target } }
|
||||||
|
// 同一投递标识(或未指定标识)的已接收任务不重复刷屏;改要求与阶段切换会先作废旧投递。
|
||||||
|
if (target.deliveryState === 'accepted' && (!requestedId || target.deliveryId === requestedId)) {
|
||||||
|
return { claimed: false, duplicate: true, task: { ...target } }
|
||||||
|
}
|
||||||
|
if (requestedId && target.deliveryId !== requestedId) return { claimed: false, reason: 'delivery-mismatch', 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 } }
|
||||||
|
// 阶段切换登记的是 pending;若中途被取消或改要求作废,就不能再发。
|
||||||
|
if (requestedId && target.deliveryState !== 'pending') return { claimed: false, reason: 'stage-changed', task: { ...target } }
|
||||||
|
}
|
||||||
|
const seat = targetProject.seats?.[target.ownerSeatId]
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
|
throw new ServiceError('sansheng/seat-unbound', `「${SEATS[target.ownerSeatId]?.label ?? target.ownerSeatId}」的会话还没开启成功,请稍后重试`)
|
||||||
|
}
|
||||||
|
const deliveryId = requestedId ?? (target.deliveryState === 'pending' && target.deliveryId ? target.deliveryId : randomUUID())
|
||||||
|
const attemptId = randomUUID()
|
||||||
|
const now = Date.now()
|
||||||
|
target.deliveryId = deliveryId
|
||||||
|
target.deliveryState = 'sending'
|
||||||
|
target.sendingOwner = attemptId
|
||||||
|
target.sendingAt = now
|
||||||
|
// 重投保留阶段切换时存下的目标状态;只有旧数据缺字段时才补 dispatched。
|
||||||
|
if (redispatch) target.deliveryStatus ??= 'dispatched'
|
||||||
|
target.updatedAt = now
|
||||||
|
targetProject.updatedAt = now
|
||||||
|
targetProject.revision = (targetProject.revision ?? 0) + 1
|
||||||
|
const memory = normalizeProjectMemory(targetProject.memory, projectId)
|
||||||
|
return {
|
||||||
|
claimed: true,
|
||||||
|
deliveryId,
|
||||||
|
attemptId,
|
||||||
|
ownerSeatId: target.ownerSeatId,
|
||||||
|
sessionId: seat.sessionId,
|
||||||
|
memory,
|
||||||
|
text: taskDeliveryText(target, renderProjectMemory(memory)),
|
||||||
|
task: { ...target },
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if (!claim.claimed) {
|
||||||
|
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 delivery
|
||||||
|
try {
|
||||||
|
delivery = await this.seatDelivery.deliverToSeat({
|
||||||
|
sessionId: claim.sessionId, text: claim.text, taskId: claim.task.id,
|
||||||
|
deliveryId: claim.deliveryId, attemptId: claim.attemptId,
|
||||||
|
sourceKind: 'sansheng-task', seatId: claim.ownerSeatId,
|
||||||
|
// 同步复核:领取仍属于本次尝试、席位仍是同一会话;返回后立即 followup。
|
||||||
|
verifyClaim: () => {
|
||||||
|
const latest = this.store.get(projectId)
|
||||||
|
const current = latest?.tasks?.find(item => item.id === taskId)
|
||||||
|
const currentSeat = latest?.seats?.[claim.ownerSeatId]
|
||||||
|
return !!current && current.deliveryId === claim.deliveryId
|
||||||
|
&& current.deliveryState === 'sending' && current.sendingOwner === claim.attemptId
|
||||||
|
&& currentSeat?.sessionId === claim.sessionId
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} catch (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 = claim.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 !== claim.deliveryId || target.sendingOwner !== claim.attemptId) {
|
||||||
|
return { applied: false, task: { ...target } }
|
||||||
|
}
|
||||||
|
const now = Date.now()
|
||||||
|
target.sendingOwner = null
|
||||||
|
if (outcome === 'sent') {
|
||||||
|
// 部门可能在发送回写之前就开始执行或提交结果。
|
||||||
|
if (!['running', 'done', 'failed'].includes(target.reportStatus)) {
|
||||||
|
target.status = target.deliveryStatus ?? (target.status === 'draft' ? 'dispatched' : target.status)
|
||||||
|
target.note = ''
|
||||||
|
}
|
||||||
|
target.sessionId = claim.sessionId
|
||||||
|
target.dispatchedAt = now
|
||||||
|
target.contextRevision = claim.memory.revision
|
||||||
|
target.contextHash = claim.memory.contentHash
|
||||||
|
target.decisionIds = activeDecisions
|
||||||
|
target.sourceRefs = claim.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 ?? claim.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,绝不自动重发。
|
||||||
|
async recoverPendingDeliveries() {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
// 旧版可能已收齐六部结果,但从未登记尚书通知。
|
||||||
|
if (this.store.list().some(project => project.tasks?.some(task => readyForDepartmentSummary(project, task)))) {
|
||||||
|
await this.store.mutate(s => {
|
||||||
|
for (const project of Object.values(s.projects)) {
|
||||||
|
for (const task of project.tasks ?? []) {
|
||||||
|
if (!readyForDepartmentSummary(project, task)) continue
|
||||||
|
const now = Date.now()
|
||||||
|
queueDelivery(task, task.status)
|
||||||
|
task.updatedAt = project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const pending = []
|
||||||
|
const sending = []
|
||||||
|
for (const project of this.store.list()) {
|
||||||
|
for (const task of project.tasks ?? []) {
|
||||||
|
if (task.deliveryState === 'pending' && !['done', 'cancelled', 'reconfirm'].includes(task.status)) {
|
||||||
|
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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sending.length > 0) {
|
||||||
|
await this.store.mutate(s => {
|
||||||
|
for (const item of sending) {
|
||||||
|
const target = s.projects[item.projectId]?.tasks?.find(task => task.id === item.taskId)
|
||||||
|
if (!target || target.deliveryState !== 'sending') continue
|
||||||
|
target.deliveryState = 'unknown'
|
||||||
|
target.sendingOwner = null
|
||||||
|
target.note = '发送中断,结果未知'
|
||||||
|
target.updatedAt = Date.now()
|
||||||
|
s.projects[item.projectId].revision = (s.projects[item.projectId].revision ?? 0) + 1
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const recovered = []
|
||||||
|
for (const item of pending) {
|
||||||
|
try {
|
||||||
|
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) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { recovered, staleSending: sending.length }
|
||||||
|
},
|
||||||
|
|
||||||
|
// R-007:只对投递结果未知且未结束的任务,按 expectedDeliveryId 人工核对后重投一次。
|
||||||
|
async redispatchTask(projectId, taskId, input = {}) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
this._requireId(taskId, 'taskId')
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
|
const expectedDeliveryId = typeof input.expectedDeliveryId === 'string' ? input.expectedDeliveryId.trim() : ''
|
||||||
|
if (!expectedDeliveryId || task.deliveryId !== expectedDeliveryId) {
|
||||||
|
throw new ServiceError('sansheng/conflict', '任务投递标识已变化,拒绝重投')
|
||||||
|
}
|
||||||
|
const seat = project.seats?.[task.ownerSeatId]
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
|
throw new ServiceError('sansheng/seat-unbound', '主责部门会话未就绪,不能重投')
|
||||||
|
}
|
||||||
|
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 }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,114 @@
|
||||||
|
// 项目共识、交付成果与席位头像管理服务方法。
|
||||||
|
import { createHash, randomUUID } from 'node:crypto'
|
||||||
|
import { emptyArtifact } from '../../shared/schema.js'
|
||||||
|
import { mergeProjectMemory, normalizeProjectMemory } from '../../shared/project-memory.js'
|
||||||
|
import { cleanText } from '../../shared/utils.js'
|
||||||
|
import { ServiceError } from './shared.js'
|
||||||
|
|
||||||
|
const AVATAR_MAX_BYTES = 120 * 1024
|
||||||
|
const AVATAR_CHAR_MAX = 8
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的共识、成果与头像管理方法集。 */
|
||||||
|
export const memoryArtifactServiceMethods = {
|
||||||
|
async memory(projectId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
return { memory: normalizeProjectMemory(project.memory, projectId) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async memoryUpdate(projectId, patch = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
return this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const current = normalizeProjectMemory(project.memory, projectId)
|
||||||
|
const expected = patch?.expectedRevision
|
||||||
|
if (expected !== undefined && expected !== null && expected !== current.revision) {
|
||||||
|
throw new ServiceError('sansheng/memory-conflict', `项目共识已更新(当前 v${current.revision},提交基于 v${String(expected)}),请重新读取后再改`)
|
||||||
|
}
|
||||||
|
const next = mergeProjectMemory(current, patch, { makeId: () => randomUUID() })
|
||||||
|
next.contentHash = createHash('sha256').update(JSON.stringify(next)).digest('hex')
|
||||||
|
project.memory = next
|
||||||
|
project.updatedAt = Date.now()
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { memory: next }
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
async artifacts(projectId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
return { artifacts: [...(project.artifacts ?? [])] }
|
||||||
|
},
|
||||||
|
|
||||||
|
async artifactAdd(projectId, input = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
const title = String(input.title ?? '').trim()
|
||||||
|
if (!title) throw new ServiceError('sansheng/invalid', '成果名称不能为空')
|
||||||
|
const artifact = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
if (input.taskId && !(project.tasks ?? []).some(item => item.id === input.taskId)) {
|
||||||
|
throw new ServiceError('sansheng/invalid', `关联任务 ${input.taskId} 不存在`)
|
||||||
|
}
|
||||||
|
project.artifactSeq = (project.artifactSeq ?? 0) + 1
|
||||||
|
const next = emptyArtifact({
|
||||||
|
id: `artifact-${project.artifactSeq}`,
|
||||||
|
title,
|
||||||
|
path: typeof input.path === 'string' ? input.path : '',
|
||||||
|
summary: typeof input.summary === 'string' ? input.summary : '',
|
||||||
|
taskId: input.taskId ?? null,
|
||||||
|
})
|
||||||
|
if (!Array.isArray(project.artifacts)) project.artifacts = []
|
||||||
|
project.artifacts.push(next)
|
||||||
|
project.updatedAt = Date.now()
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { ...next }
|
||||||
|
})
|
||||||
|
return { artifact }
|
||||||
|
},
|
||||||
|
|
||||||
|
// 头像:字符或已缩放图片;图片超出上限直接拒绝,客户端负责缩放到 256×256。
|
||||||
|
async setAvatar(projectId, seatId, input = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId, 'sansheng/avatar-invalid', '未知席位')
|
||||||
|
const char = cleanText(input.char)
|
||||||
|
const dataUrl = cleanText(input.dataUrl)
|
||||||
|
let avatar
|
||||||
|
if (char) {
|
||||||
|
if ([...char].length > AVATAR_CHAR_MAX) {
|
||||||
|
throw new ServiceError('sansheng/avatar-invalid', '头像字符最多 8 个,emoji 也算一个')
|
||||||
|
}
|
||||||
|
avatar = { type: 'char', char }
|
||||||
|
} else if (dataUrl) {
|
||||||
|
const match = /^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/=]+)$/.exec(dataUrl)
|
||||||
|
if (!match) throw new ServiceError('sansheng/avatar-invalid', '头像只支持 PNG、JPEG 或 WebP 图片')
|
||||||
|
const bytes = Buffer.from(match[2], 'base64').length
|
||||||
|
if (bytes === 0) throw new ServiceError('sansheng/avatar-invalid', '图片内容为空')
|
||||||
|
if (bytes > AVATAR_MAX_BYTES) {
|
||||||
|
throw new ServiceError('sansheng/avatar-invalid', '图片超过 120KB,请换一张小一点的图片')
|
||||||
|
}
|
||||||
|
avatar = { type: 'image', mime: match[1], dataUrl, bytes }
|
||||||
|
} else {
|
||||||
|
throw new ServiceError('sansheng/avatar-invalid', '请提供图片或字符头像')
|
||||||
|
}
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
project.avatars ??= {}
|
||||||
|
project.avatars[seatId] = avatar
|
||||||
|
project.updatedAt = Date.now()
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
})
|
||||||
|
return { seatId, avatar }
|
||||||
|
},
|
||||||
|
|
||||||
|
async clearAvatar(projectId, seatId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId, 'sansheng/avatar-invalid', '未知席位')
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const project = state.projects[projectId]
|
||||||
|
if (project.avatars?.[seatId]) {
|
||||||
|
delete project.avatars[seatId]
|
||||||
|
project.updatedAt = Date.now()
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return { seatId, avatar: null }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,139 @@
|
||||||
|
// 模型目录、十席全局默认配置与跨项目模型同步服务方法。
|
||||||
|
import { basename } from 'node:path'
|
||||||
|
import { SEAT_IDS } from '../../shared/roles.js'
|
||||||
|
import { normalizeSelection } from '../model.js'
|
||||||
|
import { ServiceError } from './shared.js'
|
||||||
|
import { normalizeCatalog, seatView } from './view.js'
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的模型目录与全局默认配置方法集。 */
|
||||||
|
export const modelServiceMethods = {
|
||||||
|
async models() {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
const catalog = await this.host.sessionController.modelCatalog()
|
||||||
|
return normalizeCatalog(catalog)
|
||||||
|
},
|
||||||
|
|
||||||
|
async globalDefaults() {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||||||
|
await this.globalStore.ensureLoaded()
|
||||||
|
if (this.globalStore.exists && this._seedStatus?.status === 'unknown') this._seedStatus = { status: 'existing' }
|
||||||
|
return {
|
||||||
|
...this.globalStore.snapshot(),
|
||||||
|
path: this.globalStore.file,
|
||||||
|
seedStatus: this._seedStatus?.status ?? 'unknown',
|
||||||
|
candidates: this._seedStatus?.candidates ?? [],
|
||||||
|
sourceProjectId: this._seedStatus?.sourceProjectId ?? null,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async setGlobalDefault(seatId, model) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
const normalized = normalizeSelection(model)
|
||||||
|
if (!normalized) throw new ServiceError('sansheng/model-invalid', '全局默认模型不能为空;清除请使用 clearGlobalDefault')
|
||||||
|
await this.host.llm.resolveCallConfig(normalized)
|
||||||
|
await this.globalStore.setSeat(seatId, normalized)
|
||||||
|
return { globalDefaults: await this.globalDefaults(), ...(await this._syncInheritors(seatId)) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async clearGlobalDefault(seatId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
await this.globalStore.clearSeat(seatId)
|
||||||
|
return { globalDefaults: await this.globalDefaults(), ...(await this._syncInheritors(seatId)) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async _syncInheritors(seatId) {
|
||||||
|
const targets = []
|
||||||
|
for (const project of this.store.list()) {
|
||||||
|
const seat = project.seats?.[seatId]
|
||||||
|
if (!seat || seat.model || seat.status !== 'bound' || !seat.sessionId) continue
|
||||||
|
targets.push(project.id)
|
||||||
|
}
|
||||||
|
const applied = []
|
||||||
|
const failed = []
|
||||||
|
const pending = []
|
||||||
|
const started = Date.now()
|
||||||
|
for (const projectId of targets) {
|
||||||
|
if (Date.now() - started > 5000) { pending.push(projectId); continue }
|
||||||
|
try {
|
||||||
|
const sync = await this.modelSync.syncSeat(projectId, seatId, 'global-default')
|
||||||
|
if (sync?.status === 'synced') applied.push(projectId)
|
||||||
|
else if (sync?.status === 'pending') pending.push(projectId)
|
||||||
|
else failed.push({ projectId, error: sync?.error ?? sync?.status })
|
||||||
|
} catch (error) { failed.push({ projectId, error: error?.message ?? String(error) }) }
|
||||||
|
}
|
||||||
|
return { applied, failed, pending }
|
||||||
|
},
|
||||||
|
|
||||||
|
async seedGlobalDefaults(projectId = undefined) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.globalStore) throw new ServiceError('sansheng/global-setting-missing', '未配置全局默认模型存储')
|
||||||
|
await this.globalStore.ensureLoaded()
|
||||||
|
if (this.globalStore.exists) {
|
||||||
|
this._seedStatus = { status: 'existing' }
|
||||||
|
return { seeded: false, status: 'existing', globalDefaults: await this.globalDefaults() }
|
||||||
|
}
|
||||||
|
const projects = this.store.list()
|
||||||
|
let target = null
|
||||||
|
let status = 'seeded'
|
||||||
|
let candidates = []
|
||||||
|
if (projectId === null) {
|
||||||
|
// 显式 null 表示创建一个十席均为 null 的空白基线,不自动选择 dsh-brain。
|
||||||
|
await this.globalStore.mutate(state => {
|
||||||
|
for (const seatId of SEAT_IDS) state.seats[seatId] = null
|
||||||
|
})
|
||||||
|
this._seedStatus = { status: 'seeded', sourceProjectId: null }
|
||||||
|
return { seeded: true, status: 'seeded', sourceProjectId: null, globalDefaults: await this.globalDefaults() }
|
||||||
|
}
|
||||||
|
if (projectId !== undefined) {
|
||||||
|
target = projects.find(project => project.id === projectId) ?? null
|
||||||
|
if (!target) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
} else {
|
||||||
|
const byPath = projects.filter(project => {
|
||||||
|
if (typeof project.path !== 'string' || !project.path.trim()) return false
|
||||||
|
return basename(project.path).toLowerCase() === 'dsh-brain'
|
||||||
|
})
|
||||||
|
const byName = projects.filter(project => String(project.name ?? '').trim().toLowerCase() === 'dsh-brain')
|
||||||
|
if (byPath.length === 1) target = byPath[0]
|
||||||
|
else if (byPath.length > 1) { status = 'ambiguous-baseline'; candidates = byPath.map(p => ({ id: p.id, name: p.name, path: p.path })) }
|
||||||
|
else if (byName.length === 1) target = byName[0]
|
||||||
|
else if (byName.length > 1) { status = 'ambiguous-baseline'; candidates = byName.map(p => ({ id: p.id, name: p.name, path: p.path })) }
|
||||||
|
else status = 'missing-baseline'
|
||||||
|
}
|
||||||
|
if (!target) {
|
||||||
|
this._seedStatus = { status, candidates }
|
||||||
|
return { seeded: false, status, candidates, globalDefaults: await this.globalDefaults() }
|
||||||
|
}
|
||||||
|
await this.globalStore.mutate(state => {
|
||||||
|
for (const seatId of SEAT_IDS) state.seats[seatId] = target.seats?.[seatId]?.model ?? null
|
||||||
|
})
|
||||||
|
this._seedStatus = { status: 'seeded', sourceProjectId: target.id }
|
||||||
|
return { seeded: true, status: 'seeded', sourceProjectId: target.id, globalDefaults: await this.globalDefaults() }
|
||||||
|
},
|
||||||
|
|
||||||
|
async retrySeatModel(projectId, seatId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
const sync = await this.modelSync.retrySeat(projectId, seatId)
|
||||||
|
return { sync, seat: seatView(seatId, this.store.get(projectId).seats[seatId], this._seatExtras(projectId, { [seatId]: sync })[seatId] ?? {}) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async modelStatus(projectId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.modelSync) return { projects: {}, globalDefaults: this.globalStore ? await this.globalDefaults() : null }
|
||||||
|
if (projectId) {
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
await this.modelSync.syncProject(projectId)
|
||||||
|
return { projectId, seats: this.modelSync.statusOf(projectId), globalDefaults: this.globalStore ? await this.globalDefaults() : null }
|
||||||
|
}
|
||||||
|
const projects = {}
|
||||||
|
for (const project of this.store.list()) {
|
||||||
|
try { await this.modelSync.syncProject(project.id); projects[project.id] = this.modelSync.statusOf(project.id) } catch (error) { projects[project.id] = { error: error?.message ?? String(error) } }
|
||||||
|
}
|
||||||
|
return { projects, globalDefaults: this.globalStore ? await this.globalDefaults() : null }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,145 @@
|
||||||
|
// 项目管理与十席会话生命周期服务方法。
|
||||||
|
import { SEAT_IDS } from '../../shared/roles.js'
|
||||||
|
import { applyModel, normalizeSelection } from '../model.js'
|
||||||
|
import { ServiceError } from './shared.js'
|
||||||
|
import { projectView, seatView } from './view.js'
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的项目与席位操作方法集。 */
|
||||||
|
export const projectServiceMethods = {
|
||||||
|
async list() {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
return {
|
||||||
|
projects: [...this.store.list()]
|
||||||
|
.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN'))
|
||||||
|
.map(p => ({ id: p.id, name: p.name, status: p.status, revision: p.revision ?? 0 })),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async open({ workspaceId, name, path } = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!workspaceId && !path) throw new ServiceError('sansheng/invalid', '需要 workspaceId 或 path')
|
||||||
|
const registry = this.host.workspaceRegistry
|
||||||
|
let ws
|
||||||
|
if (workspaceId) {
|
||||||
|
ws = registry.get(workspaceId)
|
||||||
|
if (!ws) throw new ServiceError('sansheng/not-found', `未找到工作区 ${workspaceId}`)
|
||||||
|
} else {
|
||||||
|
ws = await registry.resolveByPath(path)
|
||||||
|
if (!ws) ws = await registry.create(path, name)
|
||||||
|
}
|
||||||
|
const id = ws.id ?? ws.workspaceId
|
||||||
|
await this.store.mutate(() => {
|
||||||
|
this.store.ensureProjectRecord({
|
||||||
|
id,
|
||||||
|
name: name ?? ws.title ?? ws.name ?? id,
|
||||||
|
workspaceId: id,
|
||||||
|
path: ws.path ?? path ?? null,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
await this.provisioner.ensureTitles(id)
|
||||||
|
return projectView(this.store.get(id))
|
||||||
|
},
|
||||||
|
|
||||||
|
async project(projectId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
if (this.modelSync?.syncProject) {
|
||||||
|
try { await this.modelSync.syncProject(projectId) } catch (error) {
|
||||||
|
console.warn('[sansheng] 模型同步失败:', error?.message ?? error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await this.provisioner.ensureTitles(projectId)
|
||||||
|
const statusMap = this.modelSync?.statusOf?.(projectId) ?? {}
|
||||||
|
const extras = this._seatExtras(projectId, statusMap)
|
||||||
|
if (this.seatActivity?.reconcileProject) {
|
||||||
|
try {
|
||||||
|
const activity = await this.seatActivity.reconcileProject(projectId)
|
||||||
|
for (const seatId of SEAT_IDS) if (activity?.[seatId]) extras[seatId].runtimeState = activity[seatId]
|
||||||
|
} catch { /* 运行状态读取失败不阻断项目视图 */ }
|
||||||
|
}
|
||||||
|
return projectView(this.store.get(projectId), extras)
|
||||||
|
},
|
||||||
|
|
||||||
|
async enable(projectId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
await this.provisioner.enable(projectId)
|
||||||
|
return this.project(projectId)
|
||||||
|
},
|
||||||
|
|
||||||
|
async enableSeat(projectId, seatId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
await this.provisioner.enableSeat(projectId, seatId)
|
||||||
|
return this.project(projectId)
|
||||||
|
},
|
||||||
|
|
||||||
|
async openSeat(projectId, seatId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
const result = await this.provisioner.openSeat(projectId, seatId)
|
||||||
|
const currentView = await this.project(projectId)
|
||||||
|
return { ...currentView, sessionId: result.sessionId, seatId: result.seatId }
|
||||||
|
},
|
||||||
|
|
||||||
|
async rebuildSeat(projectId, seatId, { expectedSessionId } = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
if (expectedSessionId !== undefined && expectedSessionId !== null && typeof expectedSessionId !== 'string') {
|
||||||
|
throw new ServiceError('sansheng/invalid', 'expectedSessionId 必须是字符串')
|
||||||
|
}
|
||||||
|
const result = await this.provisioner.rebuildSeat(projectId, seatId, { expectedSessionId })
|
||||||
|
const currentView = await this.project(projectId)
|
||||||
|
return {
|
||||||
|
...currentView,
|
||||||
|
sessionId: result.sessionId,
|
||||||
|
seatId: result.seatId,
|
||||||
|
previousSessionId: result.previousSessionId ?? null,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async configure(projectId, seatId, { model, instructions } = {}) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
this._requireSeat(seatId)
|
||||||
|
|
||||||
|
let normalized
|
||||||
|
if (model !== undefined) {
|
||||||
|
normalized = normalizeSelection(model) // null=清除项目覆盖;非法抛 sansheng/model-invalid
|
||||||
|
// 非空选择必须在写状态前验证路由;清除覆盖不需要。
|
||||||
|
if (normalized !== null) await this.host.llm.resolveCallConfig(normalized)
|
||||||
|
}
|
||||||
|
if (instructions !== undefined && typeof instructions !== 'string') {
|
||||||
|
throw new ServiceError('sansheng/invalid', 'instructions 必须是字符串')
|
||||||
|
}
|
||||||
|
// 兼容无 modelSync 的旧调用路径:仍在写状态前把选择应用到已绑定会话。
|
||||||
|
let applied = null
|
||||||
|
if (model !== undefined && normalized && !this.modelSync?.syncSeat && project.seats[seatId].sessionId) {
|
||||||
|
applied = await applyModel(this.host, project.seats[seatId].sessionId, normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.store.mutate(s => {
|
||||||
|
const target = s.projects[projectId].seats[seatId]
|
||||||
|
if (model !== undefined) target.model = normalized
|
||||||
|
if (instructions !== undefined) target.instructions = instructions
|
||||||
|
target.updatedAt = Date.now()
|
||||||
|
s.projects[projectId].updatedAt = Date.now()
|
||||||
|
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||||
|
})
|
||||||
|
let sync = null
|
||||||
|
if (model !== undefined && this.modelSync?.syncSeat) {
|
||||||
|
try { sync = await this.modelSync.syncSeat(projectId, seatId, 'configure') } catch (error) {
|
||||||
|
sync = { status: 'failed', error: error?.message ?? String(error) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const extras = this._seatExtras(projectId, sync ? { [seatId]: sync } : {})
|
||||||
|
return { seat: seatView(seatId, this.store.get(projectId).seats[seatId], extras[seatId] ?? {}), sync, applied }
|
||||||
|
},
|
||||||
|
|
||||||
|
async statusSnapshot(projectId) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.seatActivity) return { projects: {}, available: false }
|
||||||
|
if (projectId) {
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
return { projectId, seats: await this.seatActivity.reconcileProject(projectId), available: true }
|
||||||
|
}
|
||||||
|
return { projects: await this.seatActivity.reconcileAll(), available: true }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,128 @@
|
||||||
|
// 需求门控、快照合成、失效作废与审核移交的纯领域辅助函数。
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { cleanText } from '../../shared/utils.js'
|
||||||
|
import { REQUIREMENT_FILL_FIELDS, ServiceError, voidDelivery } from './shared.js'
|
||||||
|
|
||||||
|
export const REQUIREMENT_TEXT_FIELDS = [
|
||||||
|
'title', 'summary', 'originalText', 'judgement', 'judgementReason', 'scope',
|
||||||
|
'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo',
|
||||||
|
]
|
||||||
|
|
||||||
|
// 下派只需用户明确授权、标题和用户原话;范围与验收标准由中书拟案补齐。
|
||||||
|
// 只有丞相明确判断 not_now 时才继续阻止下派,空白或默认 needs_discussion 都放行。
|
||||||
|
export function requirementReadyProblem(req) {
|
||||||
|
if (!req || !cleanText(req.title)) return '缺少需求标题'
|
||||||
|
if (!cleanText(req.originalText)) return '缺少用户原始要求'
|
||||||
|
if (req.judgement === 'not_now') return '丞相判断暂不可做'
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requirementStatusOf(req) {
|
||||||
|
if (req.status === 'cancelled') return 'cancelled'
|
||||||
|
if (req.status === 'published') return 'published'
|
||||||
|
if (req.status === 'returned') return 'returned'
|
||||||
|
return requirementReadyProblem(req) ? 'discussing' : 'ready'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requirementBlockedReason(req) {
|
||||||
|
if (req.status === 'cancelled') return '已取消'
|
||||||
|
if (req.status === 'published') return req.blockedReason || '已发布,等待流程推进'
|
||||||
|
if (req.status === 'returned') return req.blockedReason || '已退回,等待重新商讨或拟案'
|
||||||
|
if (req.judgement === 'not_now') return req.judgementReason || '丞相判断暂不可做'
|
||||||
|
return '可以交中书拟案,范围与验收标准由中书补齐'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requirementSnapshot(req) {
|
||||||
|
return {
|
||||||
|
id: req.id, revision: req.revision, title: req.title, summary: req.summary,
|
||||||
|
originalText: req.originalText, scope: req.scope, nonGoals: req.nonGoals,
|
||||||
|
acceptanceCriteria: req.acceptanceCriteria, risks: req.risks, dependencies: req.dependencies, missingInfo: req.missingInfo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 列表按当前门槛重算非终态需求:旧数据存成 discussing、但已可下派的条目也显示为 ready。
|
||||||
|
export function requirementView(req) {
|
||||||
|
const view = structuredClone(req)
|
||||||
|
if (!['published', 'cancelled', 'returned'].includes(view.status)) {
|
||||||
|
view.status = requirementStatusOf(view)
|
||||||
|
view.blockedReason = requirementBlockedReason(view)
|
||||||
|
}
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
|
// 中书补缺只存在任务上:只认需求里仍为空的字段,用户已确认的内容永远优先。
|
||||||
|
export 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批准、派发和六部回报共用这一份有效快照:需求原字段 + 中书补缺。
|
||||||
|
export function effectiveRequirementSnapshot(task, req) {
|
||||||
|
return { ...requirementSnapshot(req), ...requirementFillOf(task, req) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 需求改版或取消时使旧批准与未结束任务失效。 */
|
||||||
|
export function invalidateRequirementWork(project, requirementId, nextRevision, now) {
|
||||||
|
for (const approval of project.approvals ?? []) {
|
||||||
|
if (approval.requirementId === requirementId && approval.status === 'approved') {
|
||||||
|
approval.status = 'invalidated'
|
||||||
|
approval.invalidatedAt = now
|
||||||
|
approval.invalidateReason = `需求已更新到 v${nextRevision},旧批准失效`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const task of project.tasks ?? []) {
|
||||||
|
if (task.requirementId !== requirementId) continue
|
||||||
|
if (task.status === 'done' || task.status === 'cancelled') continue
|
||||||
|
if (task.kind === 'workflow') {
|
||||||
|
task.status = 'reconfirm'
|
||||||
|
task.stage = 'reconfirm'
|
||||||
|
task.blockedReason = `需求已更新到 v${nextRevision},旧发布与批准失效;需重新商讨并发布`
|
||||||
|
} else if (task.kind === 'execution') {
|
||||||
|
task.status = 'returned'
|
||||||
|
task.blockedReason = `需求已更新到 v${nextRevision},停止新增工作并报告是否需要重新确认`
|
||||||
|
}
|
||||||
|
voidDelivery(task)
|
||||||
|
task.updatedAt = now
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 审核或用户确认通过后生成批准记录并流转至尚书调度阶段。 */
|
||||||
|
export 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: approvedScope,
|
||||||
|
status: 'approved', approvedAt: now, approvedBy,
|
||||||
|
}
|
||||||
|
project.approvals ??= []
|
||||||
|
project.approvals.push(approval)
|
||||||
|
task.approvalId = approval.id
|
||||||
|
task.approvalScope = approval.scope
|
||||||
|
task.stage = 'shangshu_dispatch'
|
||||||
|
task.ownerSeatId = 'shangshu'
|
||||||
|
task.status = 'draft'
|
||||||
|
task.blockedReason = '方案已通过,等待尚书派工'
|
||||||
|
requirement.status = 'published'
|
||||||
|
requirement.blockedReason = task.blockedReason
|
||||||
|
requirement.updatedAt = now
|
||||||
|
}
|
||||||
|
|
||||||
|
export function legacyApprovalDecision(now) {
|
||||||
|
return {
|
||||||
|
id: randomUUID(), kind: 'legacy-approval', status: 'pending', createdAt: now,
|
||||||
|
question: '是否按已审核的方案继续执行?',
|
||||||
|
options: [{ label: '继续执行', value: 'continue' }, { label: '结束任务', value: 'cancel' }],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function taskDecisionBlock(task) {
|
||||||
|
if (task.awaitingLeadDecision || task.decisions?.some(item => item.status === 'pending')) {
|
||||||
|
throw new ServiceError('sansheng/decision-pending', '任务正在等待会商决定')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,236 @@
|
||||||
|
// 需求清单增改、取消与真人命令门控发布服务方法。
|
||||||
|
import { emptyRequirement, emptyTask } from '../../shared/schema.js'
|
||||||
|
import { cleanText } from '../../shared/utils.js'
|
||||||
|
import { getCommand, putCommand } from '../command-ledger.js'
|
||||||
|
import { OPEN_TASK_STATUS, ServiceError, queueDelivery } from './shared.js'
|
||||||
|
import {
|
||||||
|
REQUIREMENT_TEXT_FIELDS,
|
||||||
|
invalidateRequirementWork,
|
||||||
|
requirementBlockedReason,
|
||||||
|
requirementReadyProblem,
|
||||||
|
requirementSnapshot,
|
||||||
|
requirementStatusOf,
|
||||||
|
requirementView,
|
||||||
|
} from './requirement-helpers.js'
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的需求管理与门控发布方法集。 */
|
||||||
|
export const requirementServiceMethods = {
|
||||||
|
async requirements(projectId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
return {
|
||||||
|
requirements: (project.requirements ?? []).map(requirementView),
|
||||||
|
approvals: structuredClone(project.approvals ?? []),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async requirementUpsert(projectId, input = {}, actor = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以整理需求清单')
|
||||||
|
const id = cleanText(input.id)
|
||||||
|
const expectedRevision = input.expectedRevision === undefined || input.expectedRevision === null ? null : Number(input.expectedRevision)
|
||||||
|
return this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
let req
|
||||||
|
let created = false
|
||||||
|
if (id) {
|
||||||
|
req = (project.requirements ?? []).find(item => item.id === id)
|
||||||
|
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${id} 不存在`)
|
||||||
|
if (expectedRevision !== null && req.revision !== expectedRevision) {
|
||||||
|
throw new ServiceError('sansheng/requirement-conflict', `需求已更新(当前 v${req.revision},提交基于 v${expectedRevision}),请重新读取后再改`)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const title = cleanText(input.title)
|
||||||
|
if (!title) throw new ServiceError('sansheng/invalid', '需求标题不能为空')
|
||||||
|
project.requirementSeq = (project.requirementSeq ?? 0) + 1
|
||||||
|
req = emptyRequirement({
|
||||||
|
id: `R-${String(project.requirementSeq).padStart(3, '0')}`,
|
||||||
|
title,
|
||||||
|
summary: cleanText(input.summary),
|
||||||
|
originalText: cleanText(input.originalText) || title,
|
||||||
|
})
|
||||||
|
if (!Array.isArray(project.requirements)) project.requirements = []
|
||||||
|
project.requirements.push(req)
|
||||||
|
created = true
|
||||||
|
}
|
||||||
|
const originalText = req.originalText
|
||||||
|
const before = JSON.stringify(REQUIREMENT_TEXT_FIELDS.map(field => req[field] ?? ''))
|
||||||
|
for (const field of REQUIREMENT_TEXT_FIELDS) {
|
||||||
|
if (input[field] !== undefined) req[field] = cleanText(input[field])
|
||||||
|
}
|
||||||
|
if (!req.originalText) req.originalText = req.title
|
||||||
|
const after = JSON.stringify(REQUIREMENT_TEXT_FIELDS.map(field => req[field] ?? ''))
|
||||||
|
const previousAuthorization = req.dispatchAuthorization
|
||||||
|
if (input.dispatchAfterClarification === true && actor.command?.seq != null && actor.sessionId && !previousAuthorization) {
|
||||||
|
req.dispatchAuthorization = { sessionId: actor.sessionId, seq: actor.command.seq }
|
||||||
|
} else if (input.dispatchAfterClarification === false || req.originalText !== originalText || req.status === 'published' || req.status === 'cancelled') {
|
||||||
|
delete req.dispatchAuthorization
|
||||||
|
}
|
||||||
|
if (!created && before === after && previousAuthorization === req.dispatchAuthorization) {
|
||||||
|
return { requirement: { ...req }, created: false, changed: false }
|
||||||
|
}
|
||||||
|
const now = Date.now()
|
||||||
|
if (!created && (req.status === 'published' || (project.tasks ?? []).some(task => task.requirementId === req.id && OPEN_TASK_STATUS.has(task.status)))) {
|
||||||
|
invalidateRequirementWork(project, req.id, req.revision + 1, now)
|
||||||
|
}
|
||||||
|
if (!created && (req.status === 'published' || req.status === 'returned')) req.status = 'discussing'
|
||||||
|
if (created) req.revision = 1
|
||||||
|
else req.revision = (req.revision ?? 1) + 1
|
||||||
|
req.status = requirementStatusOf(req)
|
||||||
|
req.blockedReason = requirementBlockedReason(req)
|
||||||
|
req.updatedAt = now
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { requirement: { ...req }, created, changed: true }
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
async requirementCancel(projectId, requirementId, actor = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以取消需求')
|
||||||
|
return this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const req = (project.requirements ?? []).find(item => item.id === requirementId)
|
||||||
|
if (!req) throw new ServiceError('sansheng/not-found', `需求 ${requirementId} 不存在`)
|
||||||
|
const now = Date.now()
|
||||||
|
req.status = 'cancelled'
|
||||||
|
delete req.dispatchAuthorization
|
||||||
|
req.cancelledAt = now
|
||||||
|
req.blockedReason = '已取消'
|
||||||
|
req.updatedAt = now
|
||||||
|
invalidateRequirementWork(project, req.id, req.revision, now)
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { requirement: { ...req } }
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
async requirementPublish(projectId, requirementId, input = {}, actor = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以发布需求给中书省')
|
||||||
|
const command = cleanText(input.command)
|
||||||
|
const commandRef = input.commandRef && typeof input.commandRef === 'object' ? input.commandRef : null
|
||||||
|
const commandSeq = commandRef?.seq ?? null
|
||||||
|
const sessionId = actor.sessionId ?? null
|
||||||
|
const existing = getCommand(this.store.get(projectId), sessionId, commandSeq)
|
||||||
|
if (existing) {
|
||||||
|
if (existing.outcome === 'published') {
|
||||||
|
return { ok: true, duplicate: true, taskId: existing.taskId, deliveryId: existing.deliveryId, requirementId: existing.requirementId }
|
||||||
|
}
|
||||||
|
throw new ServiceError('sansheng/command-used', `该发布命令已处理(${existing.outcome})${existing.error ? ':' + existing.error : ''}`)
|
||||||
|
}
|
||||||
|
// 丞相根据当前对话选定需求,只有存在唯一候选时才允许省略编号。
|
||||||
|
let effectiveId = cleanText(requirementId).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 => 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: '多个待发布需求' })
|
||||||
|
throw new ServiceError('sansheng/requirement-ambiguous', `当前有多个待发布需求:${ready.map(item => item.id).join('、')};请确认要下派哪一项`)
|
||||||
|
} else {
|
||||||
|
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-not-ready', { error: '没有待发布需求' })
|
||||||
|
throw new ServiceError('sansheng/requirement-not-ready', '当前没有待发布的需求')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!effectiveId) {
|
||||||
|
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-invalid', { error: '未识别需求编号' })
|
||||||
|
throw new ServiceError('sansheng/publish-not-explicit', '请先确认要下派哪一项')
|
||||||
|
}
|
||||||
|
if (!command || !sessionId || !Number.isSafeInteger(commandSeq) || !commandRef?.messageId) {
|
||||||
|
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, 'rejected-invalid', { error: '未检测到明确发布命令' })
|
||||||
|
throw new ServiceError('sansheng/current-user-message-unavailable', '宿主未能验证本轮用户消息,本次下派没有执行')
|
||||||
|
}
|
||||||
|
const expectedRevision = Number(input.expectedRevision)
|
||||||
|
let published
|
||||||
|
try {
|
||||||
|
published = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const used = getCommand(project, sessionId, commandSeq)
|
||||||
|
if (used) throw new ServiceError('sansheng/command-used', '该用户消息已处理')
|
||||||
|
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},已失效`)
|
||||||
|
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', '这项需求缺少同一会话中有效的澄清后下派授权')
|
||||||
|
}
|
||||||
|
const problem = requirementReadyProblem(req)
|
||||||
|
if (problem) throw new ServiceError('sansheng/requirement-incomplete', `需求不可发布:${problem}`)
|
||||||
|
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()
|
||||||
|
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||||||
|
const task = emptyTask({
|
||||||
|
id: `task-${project.taskSeq}`,
|
||||||
|
title: `${req.id} · ${req.title}`,
|
||||||
|
goal: req.summary || req.scope || req.title,
|
||||||
|
requirement: req.originalText,
|
||||||
|
ownerSeatId: 'zhongshu',
|
||||||
|
kind: 'workflow',
|
||||||
|
requirementId: req.id,
|
||||||
|
requirementRevision: req.revision,
|
||||||
|
stage: 'zhongshu_draft',
|
||||||
|
now,
|
||||||
|
})
|
||||||
|
task.requirementSnapshot = requirementSnapshot(req)
|
||||||
|
task.blockedReason = '中书省拟案中'
|
||||||
|
task.executionAuthorizedAtDispatch = true
|
||||||
|
task.publishCommandRef = commandRef.messageId
|
||||||
|
const deliveryId = queueDelivery(task, 'dispatched')
|
||||||
|
if (!Array.isArray(project.tasks)) project.tasks = []
|
||||||
|
project.tasks.push(task)
|
||||||
|
delete req.dispatchAuthorization
|
||||||
|
req.status = 'published'
|
||||||
|
req.publishedRevision = req.revision
|
||||||
|
req.publishedAt = now
|
||||||
|
req.blockedReason = '已发布,等待中书省拟案'
|
||||||
|
req.updatedAt = now
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
putCommand(project, {
|
||||||
|
sessionId, seq: commandSeq, messageId: commandRef?.messageId ?? null,
|
||||||
|
outcome: 'published', requirementId: req.id, requirementRevision: req.revision,
|
||||||
|
taskId: task.id, deliveryId, at: now,
|
||||||
|
})
|
||||||
|
return { task: { ...task }, requirement: { ...req }, deliveryId }
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
await this._recordRejectedCommand(projectId, sessionId, commandSeq, commandRef, error?.code === 'sansheng/requirement-duplicate' ? 'rejected-duplicate' : 'rejected-invalid', { error: error?.message ?? String(error) })
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
void this.taskDispatch(projectId, published.task.id, { deliveryId: published.deliveryId }).catch(async error => {
|
||||||
|
await this.store.mutate(state => {
|
||||||
|
const task = state.projects[projectId]?.tasks?.find(item => item.id === published.task.id)
|
||||||
|
if (task?.deliveryId !== published.deliveryId || task.deliveryState !== 'pending') return
|
||||||
|
task.note = error?.message ?? String(error)
|
||||||
|
task.blockedReason = task.note
|
||||||
|
task.updatedAt = Date.now()
|
||||||
|
})
|
||||||
|
}).catch(error => console.warn('[sansheng] 后台投递状态保存失败:', error))
|
||||||
|
return { ok: true, queued: true, taskId: published.task.id, deliveryId: published.deliveryId, requirement: published.requirement }
|
||||||
|
},
|
||||||
|
|
||||||
|
async _recordRejectedCommand(projectId, sessionId, seq, commandRef, outcome, extra = {}) {
|
||||||
|
if (!sessionId || seq === null || seq === undefined) return
|
||||||
|
try {
|
||||||
|
await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
if (!project || getCommand(project, sessionId, seq)) return
|
||||||
|
putCommand(project, {
|
||||||
|
sessionId, seq, messageId: commandRef?.messageId ?? null, outcome,
|
||||||
|
requirementId: extra.requirementId ?? null, requirementRevision: extra.requirementRevision ?? null,
|
||||||
|
error: extra.error ?? null, at: Date.now(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
} catch { /* 拒绝记录失败不能掩盖原始业务错误 */ }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,80 @@
|
||||||
|
// SanshengService 子模块共用的错误类型、状态常量与流程辅助函数。
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const OPEN_TASK_STATUS = new Set([
|
||||||
|
'draft', 'dispatched', 'running', 'prepared', 'waiting_user', 'returned', 'reconfirm',
|
||||||
|
])
|
||||||
|
|
||||||
|
// 中书拟案时只能补这些空缺字段;标题、用户原话和判断仍由丞相维护。
|
||||||
|
export const REQUIREMENT_FILL_FIELDS = [
|
||||||
|
'scope', 'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo',
|
||||||
|
]
|
||||||
|
|
||||||
|
export function appendLeadReport(state, projectId, task, event, summary, extra = {}) {
|
||||||
|
if (!state?.projects?.[projectId] || !task) return null
|
||||||
|
return recordLeadReportInState(state, projectId, {
|
||||||
|
taskId: task.id,
|
||||||
|
transitionId: task.lastTransitionId || `${task.id}:${task.stage ?? ''}:${event}`,
|
||||||
|
event,
|
||||||
|
stage: task.stage ?? null,
|
||||||
|
ownerSeatId: task.ownerSeatId ?? null,
|
||||||
|
requirementId: task.requirementId ?? null,
|
||||||
|
requirementRevision: task.requirementRevision ?? null,
|
||||||
|
summary: String(summary ?? '').slice(0, 800),
|
||||||
|
textSnapshot: String(summary ?? '').slice(0, 800),
|
||||||
|
sourceKind: 'sansheng-report',
|
||||||
|
...extra,
|
||||||
|
}, Date.now())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 作废当前投递:回写只认投递标识与领取者,清掉领取者即可让迟到回写失效。
|
||||||
|
export function voidDelivery(task) {
|
||||||
|
if (!task) return
|
||||||
|
task.deliveryState = 'none'
|
||||||
|
task.sendingOwner = null
|
||||||
|
}
|
||||||
|
|
||||||
|
// 阶段切换统一登记一次待发投递,并记下发送成功后要写入的状态(恢复时直接沿用)。
|
||||||
|
export function queueDelivery(task, status) {
|
||||||
|
task.deliveryId = randomUUID()
|
||||||
|
task.deliveryState = 'pending'
|
||||||
|
task.deliveryStatus = status
|
||||||
|
task.sendingOwner = null
|
||||||
|
task.sendingAt = null
|
||||||
|
return task.deliveryId
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readyForDepartmentSummary(project, task) {
|
||||||
|
if (task.kind !== 'workflow' || task.ownerSeatId !== 'shangshu' || task.stage !== 'department_exec'
|
||||||
|
|| task.status !== 'running' || task.deliveryState !== 'none') return false
|
||||||
|
const children = project.tasks.filter(child => child.kind === 'execution' && child.parentTaskId === task.id)
|
||||||
|
return children.length > 0 && children.every(child => !OPEN_TASK_STATUS.has(child.status))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectTask(project, task) {
|
||||||
|
if (!task.workflowBlockage) return { ...task }
|
||||||
|
const { workflowBlockage: _ignored, ...rest } = task
|
||||||
|
const current = workflowBlockageOf(project, task)
|
||||||
|
return current ? { ...rest, workflowBlockage: current } : rest
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 阶段切换落盘后统一投递下一棒,并在 finally 异步冲刷丞相阶段回报。 */
|
||||||
|
export async function dispatchAndFlushReport(service, projectId, taskId, next, extraFields = {}) {
|
||||||
|
try {
|
||||||
|
const dispatched = await service.taskDispatch(projectId, taskId, { deliveryId: next.task.deliveryId })
|
||||||
|
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task, ...extraFields }
|
||||||
|
} finally {
|
||||||
|
if (next.reportCreated) service._flushLeadReports(projectId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,287 @@
|
||||||
|
// 任务查询、创建、状态汇报、修改、取消与尚书汇总服务方法。
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { SEAT_IDS, SEATS } from '../../shared/roles.js'
|
||||||
|
import { emptyTask } from '../../shared/schema.js'
|
||||||
|
import { internalSource } from '../message-source.js'
|
||||||
|
import { workflowBlockageOf } from '../workflow-blockage.js'
|
||||||
|
import {
|
||||||
|
ServiceError,
|
||||||
|
appendLeadReport,
|
||||||
|
projectTask,
|
||||||
|
queueDelivery,
|
||||||
|
readyForDepartmentSummary,
|
||||||
|
voidDelivery,
|
||||||
|
} from './shared.js'
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的任务读写、回报与尚书汇总方法集。 */
|
||||||
|
export const taskServiceMethods = {
|
||||||
|
async tasks(projectId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
return { tasks: (project.tasks ?? []).map(task => projectTask(project, task)) }
|
||||||
|
},
|
||||||
|
|
||||||
|
// 只读任务汇总:按状态/主责席位统计,并返回可追溯的任务明细。
|
||||||
|
async taskSummary(projectId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
const tasks = Array.isArray(project.tasks) ? project.tasks : []
|
||||||
|
const statusCounts = {}
|
||||||
|
const seatCounts = {}
|
||||||
|
for (const task of tasks) {
|
||||||
|
const status = typeof task.status === 'string' ? task.status : 'unknown'
|
||||||
|
statusCounts[status] = (statusCounts[status] ?? 0) + 1
|
||||||
|
const seatId = task.ownerSeatId
|
||||||
|
if (!seatCounts[seatId]) seatCounts[seatId] = { total: 0, done: 0, running: 0, open: 0 }
|
||||||
|
const row = seatCounts[seatId]
|
||||||
|
row.total += 1
|
||||||
|
if (status === 'done') row.done += 1
|
||||||
|
else if (status === 'running') row.running += 1
|
||||||
|
else if (status !== 'cancelled') row.open += 1
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
projectId,
|
||||||
|
projectName: project.name,
|
||||||
|
revision: project.revision ?? 0,
|
||||||
|
total: tasks.length,
|
||||||
|
statusCounts,
|
||||||
|
seatCounts,
|
||||||
|
openTasks: tasks
|
||||||
|
.filter(task => task.status !== 'done' && task.status !== 'cancelled')
|
||||||
|
.map(task => task.id),
|
||||||
|
tasks: tasks.map(task => ({
|
||||||
|
id: task.id,
|
||||||
|
title: task.title,
|
||||||
|
status: task.status,
|
||||||
|
ownerSeatId: task.ownerSeatId,
|
||||||
|
ownerLabel: SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId,
|
||||||
|
goal: task.goal ?? '',
|
||||||
|
requirement: task.requirement ?? '',
|
||||||
|
result: task.result ?? '',
|
||||||
|
note: task.note ?? '',
|
||||||
|
resultSessionId: task.resultSessionId ?? null,
|
||||||
|
deliveryState: task.deliveryState ?? 'none',
|
||||||
|
workflowBlockage: workflowBlockageOf(project, task),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// 内部投递统一入口:先 resolveAgent,再以 source 标记为非用户消息;优先 followup。
|
||||||
|
async _deliverInternal(sessionId, text, source) {
|
||||||
|
const controller = this.host.sessionController
|
||||||
|
let resolved = null
|
||||||
|
try { resolved = await controller.resolveAgent(sessionId) } catch (error) {
|
||||||
|
throw new ServiceError('sansheng/delivery-failed', `会话不可用:${error?.message ?? error}`)
|
||||||
|
}
|
||||||
|
if (!resolved || ('error' in resolved && resolved.error)) {
|
||||||
|
throw new ServiceError('sansheng/seat-unbound', `会话不可用:${resolved?.error?.message ?? resolved?.error?.code ?? 'resolve failed'}`)
|
||||||
|
}
|
||||||
|
const agent = resolved.agent
|
||||||
|
if (this.host.agents?.get?.(sessionId) !== agent) throw new ServiceError('sansheng/conflict', '投递期间 Agent 已变化')
|
||||||
|
const content = [{ type: 'text', text }]
|
||||||
|
const factory = typeof this.host.createUserMessage === 'function' ? this.host.createUserMessage : null
|
||||||
|
const message = factory ? await Promise.resolve(factory({ content, source })) : { role: 'user', content, source }
|
||||||
|
if (typeof agent?.followup === 'function') {
|
||||||
|
await agent.followup(message)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (typeof controller.prompt === 'function') {
|
||||||
|
await controller.prompt({ requestId: randomUUID(), sessionId, mode: 'queue', content, source }, new AbortController().signal)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
throw new ServiceError('sansheng/delivery-failed', '宿主未提供 followup/prompt 接口')
|
||||||
|
},
|
||||||
|
|
||||||
|
// 轻量版尚书汇总:只把当前真实任务快照发给尚书汇总,不改变丞相直派流程,不创建新任务。
|
||||||
|
async shangshuSummary(projectId) {
|
||||||
|
const summary = await this.taskSummary(projectId)
|
||||||
|
let project = this.store.get(projectId)
|
||||||
|
let seat = project?.seats?.shangshu
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
|
await this.provisioner.enableSeat(projectId, 'shangshu')
|
||||||
|
project = this.store.get(projectId)
|
||||||
|
seat = project?.seats?.shangshu
|
||||||
|
}
|
||||||
|
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
|
||||||
|
throw new ServiceError('sansheng/seat-unbound', '「尚书」的会话还没开启成功,请稍后重试')
|
||||||
|
}
|
||||||
|
const controller = this.host.sessionController
|
||||||
|
if (typeof controller?.resolveAgent !== 'function' && typeof controller?.prompt !== 'function') {
|
||||||
|
throw new ServiceError('sansheng/delivery-failed', '宿主未提供会话投递接口,无法发送尚书汇总请求')
|
||||||
|
}
|
||||||
|
const clip = (value, max = 800) => {
|
||||||
|
const raw = typeof value === 'string' ? value.trim() : ''
|
||||||
|
return raw.length > max ? `${raw.slice(0, max)}…` : raw
|
||||||
|
}
|
||||||
|
const detail = summary.tasks.length === 0
|
||||||
|
? '当前项目还没有任务记录。'
|
||||||
|
: summary.tasks.map(task => {
|
||||||
|
const parts = [`${task.id} [${task.status}] ${task.ownerLabel}:${task.title}`]
|
||||||
|
if (task.goal) parts.push(`目标:${clip(task.goal)}`)
|
||||||
|
if (task.requirement) parts.push(`用户原话:${clip(task.requirement)}`)
|
||||||
|
if (task.result) parts.push(`结果:${clip(task.result)}`)
|
||||||
|
if (task.note) parts.push(`备注:${clip(task.note)}`)
|
||||||
|
return `- ${parts.join(';')}`
|
||||||
|
}).join('\n')
|
||||||
|
const statusText = Object.entries(summary.statusCounts).map(([status, count]) => `${status} ${count}`).join(',') || '无'
|
||||||
|
const text = [
|
||||||
|
`【尚书汇总】请汇总项目「${summary.projectName ?? projectId}」的真实任务进度。`,
|
||||||
|
`任务总数:${summary.total};状态统计:${statusText}。`,
|
||||||
|
'任务明细:',
|
||||||
|
detail,
|
||||||
|
'',
|
||||||
|
'汇总要求:',
|
||||||
|
'1. 按已完成 / 执行中 / 已派工 / 待执行 / 失败或取消分组汇总,列出任务 ID、主责部门、当前状态和关键结果。',
|
||||||
|
'2. 明确区分「已派工/已收到」和「已完成」,不要把已派工当成完成。',
|
||||||
|
'3. 只做汇总,不重派任务;按需求门控流程报告真实阻塞、完成与待复核事项。',
|
||||||
|
].join('\n')
|
||||||
|
try {
|
||||||
|
await this._deliverInternal(seat.sessionId, text, internalSource('sansheng-report', { seatId: 'shangshu' }))
|
||||||
|
} catch (error) {
|
||||||
|
throw new ServiceError('sansheng/delivery-failed', `尚书汇总请求发送失败:${error?.message ?? error}`)
|
||||||
|
}
|
||||||
|
return { ok: true, sessionId: seat.sessionId, summary }
|
||||||
|
},
|
||||||
|
|
||||||
|
async taskCreate(projectId, input = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const title = String(input.title ?? '').trim()
|
||||||
|
if (!title) throw new ServiceError('sansheng/invalid', '任务标题不能为空')
|
||||||
|
if (!SEAT_IDS.includes(input.ownerSeatId)) throw new ServiceError('sansheng/invalid', `未知主责席 ${String(input.ownerSeatId)}`)
|
||||||
|
const goal = typeof input.goal === 'string' ? input.goal : ''
|
||||||
|
const requirement = typeof input.requirement === 'string' ? input.requirement : ''
|
||||||
|
const task = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||||||
|
const next = emptyTask({
|
||||||
|
id: `task-${project.taskSeq}`, title, goal, requirement, ownerSeatId: input.ownerSeatId,
|
||||||
|
kind: input.kind === 'workflow' || input.kind === 'execution' ? input.kind : 'legacy',
|
||||||
|
requirementId: input.requirementId ?? null, requirementRevision: input.requirementRevision ?? null,
|
||||||
|
approvalId: input.approvalId ?? null, parentTaskId: input.parentTaskId ?? null, stage: input.stage ?? null,
|
||||||
|
})
|
||||||
|
if (input.requirementSnapshot && typeof input.requirementSnapshot === 'object') next.requirementSnapshot = structuredClone(input.requirementSnapshot)
|
||||||
|
if (typeof input.approvalScope === 'string') next.approvalScope = input.approvalScope
|
||||||
|
if (typeof input.blockedReason === 'string') next.blockedReason = input.blockedReason
|
||||||
|
if (!Array.isArray(project.tasks)) project.tasks = []
|
||||||
|
project.tasks.push(next)
|
||||||
|
project.updatedAt = Date.now()
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { ...next }
|
||||||
|
})
|
||||||
|
return { task }
|
||||||
|
},
|
||||||
|
|
||||||
|
async taskGet(projectId, taskId) {
|
||||||
|
const project = await this._requireProject(projectId)
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
|
return { task: projectTask(project, task) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async taskReport(projectId, taskId, input = {}) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
const status = input.status
|
||||||
|
if (!['running', 'done', 'failed'].includes(status)) throw new ServiceError('sansheng/invalid', '报告状态必须是 running、done 或 failed')
|
||||||
|
const result = typeof input.result === 'string' ? input.result.trim() : ''
|
||||||
|
if (status === 'done' && !result) throw new ServiceError('sansheng/invalid', '完成报告必须包含真实结果,不能只写“已完成”')
|
||||||
|
const { task: next, summaryDelivery, reportCreated } = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const task = project.tasks.find(item => item.id === taskId)
|
||||||
|
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
|
||||||
|
if (input.seatId && task.ownerSeatId !== input.seatId) {
|
||||||
|
throw new ServiceError('sansheng/forbidden', `只有主责部门 ${task.ownerSeatId} 可以报告这个任务`)
|
||||||
|
}
|
||||||
|
if (task.kind === 'execution') {
|
||||||
|
const approval = (project.approvals ?? []).find(item => item.id === task.approvalId)
|
||||||
|
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||||
|
if (!approval || approval.status !== 'approved') throw new ServiceError('sansheng/approval-invalid', '执行批准无效或已失效,不能执行或报告')
|
||||||
|
if (!req || req.revision !== task.requirementRevision || approval.requirementRevision !== task.requirementRevision) {
|
||||||
|
throw new ServiceError('sansheng/approval-invalid', '需求版本与批准版本不一致,旧任务不能继续执行')
|
||||||
|
}
|
||||||
|
if (!task.approvalScope || task.approvalScope !== approval.scope) throw new ServiceError('sansheng/approval-invalid', '任务超出批准范围,不能报告')
|
||||||
|
}
|
||||||
|
if (task.status === 'done' && status !== 'done') throw new ServiceError('sansheng/invalid', '已完成的任务不能回退状态')
|
||||||
|
if ((status === 'done' || status === 'failed') && task.status === status && task.reportStatus === status) {
|
||||||
|
const parent = project.tasks.find(item => item.id === task.parentTaskId)
|
||||||
|
const summaryDelivery = parent?.stage === 'department_exec' && parent.deliveryState === 'pending'
|
||||||
|
? { taskId: parent.id, deliveryId: parent.deliveryId } : null
|
||||||
|
return { task: { ...task, late: false, duplicate: true }, summaryDelivery, reportCreated: false }
|
||||||
|
}
|
||||||
|
// 已取消任务的结果迟到:保留取消状态,但把真实结果留档,不假装没发生。
|
||||||
|
const late = task.status === 'cancelled'
|
||||||
|
if (!late) task.status = status
|
||||||
|
if (result) task.result = result
|
||||||
|
let reportCreated = false
|
||||||
|
if (late || status === 'done' || status === 'failed') {
|
||||||
|
task.resultAt = Date.now()
|
||||||
|
task.resultSessionId = input.sessionId ?? null
|
||||||
|
task.reportStatus = late ? 'late' : status
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
const report = appendLeadReport(s, projectId, task, status === 'done' ? 'dept_done' : 'dept_failed', result || input.note || '')
|
||||||
|
reportCreated = Boolean(report?.created)
|
||||||
|
} else {
|
||||||
|
task.reportStatus = 'running'
|
||||||
|
}
|
||||||
|
if (typeof input.note === 'string' && input.note.trim()) task.note = input.note.trim()
|
||||||
|
task.updatedAt = Date.now()
|
||||||
|
s.projects[projectId].updatedAt = Date.now()
|
||||||
|
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||||
|
const parent = task.kind === 'execution' && !late && status !== 'running'
|
||||||
|
? project.tasks.find(item => item.id === task.parentTaskId) : null
|
||||||
|
const summaryDelivery = parent && readyForDepartmentSummary(project, parent)
|
||||||
|
? { taskId: parent.id, deliveryId: queueDelivery(parent, parent.status) } : null
|
||||||
|
if (summaryDelivery) parent.updatedAt = task.updatedAt
|
||||||
|
return { task: { ...task, late }, summaryDelivery, reportCreated }
|
||||||
|
})
|
||||||
|
if (summaryDelivery) {
|
||||||
|
try {
|
||||||
|
await this.taskDispatch(projectId, summaryDelivery.taskId, { deliveryId: summaryDelivery.deliveryId })
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[sansheng] 尚书汇总通知发送失败:', summaryDelivery.taskId, error?.message ?? error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (reportCreated) this._flushLeadReports(projectId)
|
||||||
|
return { task: next, late: Boolean(next.late) }
|
||||||
|
},
|
||||||
|
|
||||||
|
async taskRevise(projectId, taskId, input = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
|
||||||
|
const goal = typeof input.goal === 'string' ? input.goal.trim() : undefined
|
||||||
|
const requirement = typeof input.requirement === 'string' ? input.requirement.trim() : undefined
|
||||||
|
if (goal === undefined && requirement === undefined) throw new ServiceError('sansheng/invalid', '修改要求需要提供 goal 或 requirement')
|
||||||
|
const next = await this.store.mutate(s => {
|
||||||
|
const task = s.projects[projectId].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', '已完成或已取消的任务不能修改要求;请新建任务保留历史结果')
|
||||||
|
if (goal !== undefined) task.goal = goal
|
||||||
|
if (requirement !== undefined) task.requirement = requirement
|
||||||
|
task.status = 'draft'
|
||||||
|
task.result = null
|
||||||
|
task.resultAt = null
|
||||||
|
task.resultSessionId = null
|
||||||
|
task.reportStatus = 'none'
|
||||||
|
voidDelivery(task)
|
||||||
|
task.updatedAt = Date.now()
|
||||||
|
s.projects[projectId].updatedAt = Date.now()
|
||||||
|
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
|
||||||
|
return { ...task }
|
||||||
|
})
|
||||||
|
return { task: next }
|
||||||
|
},
|
||||||
|
|
||||||
|
async taskCancel(projectId, taskId) {
|
||||||
|
await this._requireProject(projectId)
|
||||||
|
this._requireId(taskId, 'taskId')
|
||||||
|
const next = await this.store.mutate(s => {
|
||||||
|
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||||||
|
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 }
|
||||||
|
})
|
||||||
|
return { task: next }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,103 @@
|
||||||
|
// 席位视图、项目视图与宿主模型目录规范化。
|
||||||
|
import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../../shared/roles.js'
|
||||||
|
|
||||||
|
/** 构造返回给工作台的单个席位视图。 */
|
||||||
|
export function seatView(seatId, seat, extra = {}) {
|
||||||
|
const def = SEATS[seatId]
|
||||||
|
return {
|
||||||
|
id: seatId,
|
||||||
|
label: def.label,
|
||||||
|
duty: def.duty,
|
||||||
|
responsibility: def.responsibility,
|
||||||
|
status: seat.status,
|
||||||
|
sessionId: seat.sessionId ?? null,
|
||||||
|
previousSessionIds: Array.isArray(seat.previousSessionIds) ? [...seat.previousSessionIds] : [],
|
||||||
|
model: seat.model ?? null,
|
||||||
|
configuredModel: extra.configuredModel ?? seat.model ?? null,
|
||||||
|
modelSource: extra.modelSource ?? (seat.model ? 'project' : 'none'),
|
||||||
|
sessionModel: extra.sessionModel ?? null,
|
||||||
|
modelSync: extra.modelSync ?? null,
|
||||||
|
runtimeState: extra.runtimeState ?? null,
|
||||||
|
instructions: seat.instructions ?? '',
|
||||||
|
error: seat.error ?? null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 构造包含固定十席与分组的项目完整视图。 */
|
||||||
|
export function projectView(project, seatExtras = {}) {
|
||||||
|
return {
|
||||||
|
revision: project.revision ?? 0,
|
||||||
|
project: {
|
||||||
|
id: project.id,
|
||||||
|
name: project.name,
|
||||||
|
workspaceId: project.workspaceId ?? null,
|
||||||
|
path: project.path ?? null,
|
||||||
|
status: project.status,
|
||||||
|
avatars: { ...(project.avatars ?? {}) },
|
||||||
|
seats: SEAT_IDS.map(id => seatView(id, project.seats[id], seatExtras[id] ?? {})),
|
||||||
|
groups: {
|
||||||
|
lead: [...SEAT_GROUPS.lead],
|
||||||
|
sansheng: [...SEAT_GROUPS.sansheng],
|
||||||
|
liubu: [...SEAT_GROUPS.liubu],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function effortValuesOf(value) {
|
||||||
|
if (!value) return []
|
||||||
|
if (typeof value === 'string') return value.trim() ? [value] : []
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.flatMap(item => {
|
||||||
|
if (typeof item === 'string') return item.trim() ? [item] : []
|
||||||
|
if (item && typeof item === 'object') {
|
||||||
|
const id = item.id ?? item.value ?? item.name
|
||||||
|
return typeof id === 'string' && id.trim() ? [id] : []
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (typeof value === 'object') {
|
||||||
|
if (value.efforts !== undefined) return effortValuesOf(value.efforts)
|
||||||
|
if (value.values !== undefined) return effortValuesOf(value.values)
|
||||||
|
if (value.options !== undefined) return effortValuesOf(value.options)
|
||||||
|
return Object.keys(value).filter(key => key !== 'defaultEffort' && key.trim() !== '' && typeof value[key] !== 'object')
|
||||||
|
}
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 将宿主返回的异构模型目录统一成前端与同步器消费的格式。 */
|
||||||
|
export function normalizeCatalog(catalog) {
|
||||||
|
const providers = []
|
||||||
|
const entryFor = provider => {
|
||||||
|
let entry = providers.find(p => p.provider === provider)
|
||||||
|
if (!entry) { entry = { provider, models: [] }; providers.push(entry) }
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
const groups = catalog?.providers ?? catalog?.groups ?? catalog?.entries ?? []
|
||||||
|
if (Array.isArray(groups)) {
|
||||||
|
for (const g of groups) {
|
||||||
|
const provider = g?.provider ?? g?.id ?? g?.ref ?? g?.name
|
||||||
|
const list = g?.models ?? g?.entries ?? []
|
||||||
|
for (const m of Array.isArray(list) ? list : []) {
|
||||||
|
const modelId = typeof m === 'string' ? m : (m?.model ?? m?.id ?? m?.name)
|
||||||
|
if (!provider || !modelId) continue
|
||||||
|
const entry = entryFor(provider)
|
||||||
|
if (entry.models.some(x => x.model === modelId)) continue
|
||||||
|
const effort = typeof m === 'object' ? (m.reasoningEfforts ?? m.reasoningEffort ?? m.reasoning) : undefined
|
||||||
|
const effortValues = effortValuesOf(effort)
|
||||||
|
entry.models.push(effortValues.length > 0 ? { model: modelId, reasoningEffort: effortValues } : { model: modelId })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const def = catalog?.default ?? catalog?.deploymentDefault ?? null
|
||||||
|
// 部署默认只有在 provider 与 model 都是非空字符串时才完整;半截对象不能当有效路由。
|
||||||
|
const defProvider = typeof def?.provider === 'string' && def.provider.trim() !== '' ? def.provider : null
|
||||||
|
const defModel = typeof def?.model === 'string' && def.model.trim() !== '' ? def.model : null
|
||||||
|
return {
|
||||||
|
providers,
|
||||||
|
default: defProvider && defModel ? { provider: defProvider, model: defModel } : null,
|
||||||
|
defaultError: !def || (!defProvider && !defModel) ? (def ? 'incomplete' : 'missing') : (defProvider && defModel ? null : 'incomplete'),
|
||||||
|
failures: catalog?.failures ?? catalog?.isolated ?? [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,316 @@
|
||||||
|
// 三省六部流程推进服务方法:中书拟案、门下审核、尚书派工、尚书汇总、门下验收与丞相交付。
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { SEATS, SEAT_GROUPS } from '../../shared/roles.js'
|
||||||
|
import { emptyTask } from '../../shared/schema.js'
|
||||||
|
import { cleanText } from '../../shared/utils.js'
|
||||||
|
import {
|
||||||
|
OPEN_TASK_STATUS,
|
||||||
|
REQUIREMENT_FILL_FIELDS,
|
||||||
|
ServiceError,
|
||||||
|
appendLeadReport,
|
||||||
|
dispatchAndFlushReport,
|
||||||
|
queueDelivery,
|
||||||
|
voidDelivery,
|
||||||
|
} from './shared.js'
|
||||||
|
import {
|
||||||
|
effectiveRequirementSnapshot,
|
||||||
|
handOffReviewedTask,
|
||||||
|
legacyApprovalDecision,
|
||||||
|
taskDecisionBlock,
|
||||||
|
} from './requirement-helpers.js'
|
||||||
|
|
||||||
|
/** 挂载到 SanshengService 的流程阶段流转方法集。 */
|
||||||
|
export const workflowServiceMethods = {
|
||||||
|
async workflowSubmitDraft(projectId, taskId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
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} 不存在`)
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||||||
|
if (task.ownerSeatId !== 'zhongshu' || task.stage !== 'zhongshu_draft' || task.status === 'done' || task.status === 'cancelled') {
|
||||||
|
throw new ServiceError('sansheng/stage-forbidden', '当前任务不在中书拟案阶段,不能提交拟案')
|
||||||
|
}
|
||||||
|
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'
|
||||||
|
task.status = 'draft'
|
||||||
|
task.blockedReason = '待门下省审核'
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
const report = appendLeadReport(s, projectId, task, 'zhongshu_submit', draft)
|
||||||
|
queueDelivery(task, 'dispatched')
|
||||||
|
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 }, filledFields, keptFields, reportCreated: Boolean(report?.created) }
|
||||||
|
})
|
||||||
|
return dispatchAndFlushReport(this, projectId, taskId, next, {
|
||||||
|
filledFields: next.filledFields,
|
||||||
|
keptFields: next.keptFields,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
async workflowReview(projectId, taskId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (actor.seatId !== 'menxia') throw new ServiceError('sansheng/forbidden', '只有门下省可以审核拟案')
|
||||||
|
const action = cleanText(input.action)
|
||||||
|
if (!['approve', 'return'].includes(action)) throw new ServiceError('sansheng/invalid', '审核动作必须是 approve 或 return')
|
||||||
|
const note = cleanText(input.note)
|
||||||
|
if (action === 'return' && !note) throw new ServiceError('sansheng/invalid', '退回应写明原因')
|
||||||
|
const next = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||||||
|
if (task.ownerSeatId !== 'menxia' || task.stage !== 'menxia_review') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在门下审核阶段')
|
||||||
|
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()
|
||||||
|
taskDecisionBlock(task)
|
||||||
|
if (action === 'return' && task.reviewReturns) throw new ServiceError('sansheng/consultation-required', '已有一次退回,请先三省会商,有分歧交丞相')
|
||||||
|
if (action === 'return') {
|
||||||
|
task.reviewReturns = 1
|
||||||
|
task.stage = 'zhongshu_draft'
|
||||||
|
task.ownerSeatId = 'zhongshu'
|
||||||
|
task.status = 'returned'
|
||||||
|
task.reviewNote = note
|
||||||
|
task.blockedReason = '门下退回中书省修订'
|
||||||
|
req.status = 'returned'
|
||||||
|
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 {
|
||||||
|
task.stage = 'awaiting_execution_approval'
|
||||||
|
task.ownerSeatId = 'lead'
|
||||||
|
task.status = 'waiting_user'
|
||||||
|
task.blockedReason = '待你处理:确认旧方案是否执行'
|
||||||
|
req.status = 'published'
|
||||||
|
req.blockedReason = task.blockedReason
|
||||||
|
task.decisions ??= []
|
||||||
|
task.decisions.push(legacyApprovalDecision(now))
|
||||||
|
}
|
||||||
|
task.reviewNote = note
|
||||||
|
}
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
const report = appendLeadReport(s, projectId, task, action === 'return' ? 'menxia_return' : 'menxia_approve', note || '审核通过')
|
||||||
|
queueDelivery(task, task.status)
|
||||||
|
task.updatedAt = now
|
||||||
|
req.updatedAt = now
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { task: { ...task }, reportCreated: Boolean(report?.created) }
|
||||||
|
})
|
||||||
|
return dispatchAndFlushReport(this, projectId, taskId, next)
|
||||||
|
},
|
||||||
|
|
||||||
|
async workflowDispatch(projectId, taskId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (actor.seatId !== 'shangshu') throw new ServiceError('sansheng/forbidden', '只有尚书省可以调度六部')
|
||||||
|
const assignments = Array.isArray(input.assignments) ? input.assignments : []
|
||||||
|
if (assignments.length === 0) throw new ServiceError('sansheng/invalid', '至少需要给一个六部席位分派任务')
|
||||||
|
const liubu = new Set(SEAT_GROUPS.liubu)
|
||||||
|
for (const assignment of assignments) {
|
||||||
|
const seatId = cleanText(assignment?.seatId)
|
||||||
|
if (!liubu.has(seatId)) throw new ServiceError('sansheng/route-forbidden', `尚书省只能调度六部,不能派给 ${seatId || '空目标'}`)
|
||||||
|
if (!cleanText(assignment?.title)) throw new ServiceError('sansheng/invalid', '每个六部任务必须有标题')
|
||||||
|
}
|
||||||
|
const assignmentSummary = assignments.map(item => `${SEATS[item.seatId]?.label ?? item.seatId}:${item.title}`).join(';')
|
||||||
|
const result = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||||||
|
if (task.ownerSeatId !== 'shangshu' || task.stage !== 'shangshu_dispatch') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在尚书调度阶段')
|
||||||
|
taskDecisionBlock(task)
|
||||||
|
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||||
|
if (!req || req.revision !== task.requirementRevision) throw new ServiceError('sansheng/requirement-changed', '需求版本已变化,批准失效')
|
||||||
|
const approval = (project.approvals ?? []).find(item => item.id === task.approvalId)
|
||||||
|
if (!approval || approval.status !== 'approved' || approval.requirementRevision !== req.revision || approval.scope !== task.approvalScope) {
|
||||||
|
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)
|
||||||
|
project.taskSeq = (project.taskSeq ?? 0) + 1
|
||||||
|
const child = emptyTask({
|
||||||
|
id: `task-${project.taskSeq}`,
|
||||||
|
title: cleanText(assignment.title),
|
||||||
|
goal: cleanText(assignment.goal) || effective.scope || effective.title,
|
||||||
|
requirement: req.originalText,
|
||||||
|
ownerSeatId: seatId,
|
||||||
|
kind: 'execution',
|
||||||
|
requirementId: req.id,
|
||||||
|
requirementRevision: req.revision,
|
||||||
|
approvalId: approval.id,
|
||||||
|
parentTaskId: task.id,
|
||||||
|
stage: 'department_exec',
|
||||||
|
now,
|
||||||
|
})
|
||||||
|
child.approvalScope = approval.scope
|
||||||
|
child.requirementSnapshot = { ...effective }
|
||||||
|
child.blockedReason = '六部执行中'
|
||||||
|
queueDelivery(child, 'dispatched')
|
||||||
|
project.tasks.push(child)
|
||||||
|
children.push({ ...child })
|
||||||
|
}
|
||||||
|
task.stage = 'department_exec'
|
||||||
|
task.status = 'running'
|
||||||
|
task.blockedReason = '六部执行中'
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
const report = appendLeadReport(s, projectId, task, 'shangshu_dispatch', assignmentSummary)
|
||||||
|
voidDelivery(task)
|
||||||
|
task.updatedAt = now
|
||||||
|
req.blockedReason = '六部执行中'
|
||||||
|
req.updatedAt = now
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { task: { ...task }, children, reportCreated: Boolean(report?.created) }
|
||||||
|
})
|
||||||
|
const deliveries = await Promise.all(result.children.map(async child => {
|
||||||
|
try {
|
||||||
|
const delivered = await this.taskDispatch(projectId, child.id, { deliveryId: child.deliveryId })
|
||||||
|
return { taskId: child.id, seatId: child.ownerSeatId, delivered: delivered.delivered }
|
||||||
|
} catch (error) {
|
||||||
|
return { taskId: child.id, seatId: child.ownerSeatId, delivered: false, error: error?.message ?? String(error) }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
if (result.reportCreated) this._flushLeadReports(projectId)
|
||||||
|
return { ok: deliveries.every(item => item.delivered), task: result.task, children: result.children, deliveries }
|
||||||
|
},
|
||||||
|
|
||||||
|
async workflowSummarize(projectId, taskId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (actor.seatId !== 'shangshu') throw new ServiceError('sansheng/forbidden', '只有尚书省可以汇总六部结果')
|
||||||
|
const summaryInput = cleanText(input.summary)
|
||||||
|
const next = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||||||
|
if (task.ownerSeatId !== 'shangshu' || task.stage !== 'department_exec') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在六部执行阶段,不能汇总')
|
||||||
|
const children = (project.tasks ?? []).filter(item => item.parentTaskId === task.id && item.kind === 'execution')
|
||||||
|
if (children.length === 0) throw new ServiceError('sansheng/invalid', '没有六部执行任务可汇总')
|
||||||
|
const open = children.filter(item => OPEN_TASK_STATUS.has(item.status))
|
||||||
|
if (open.length > 0) throw new ServiceError('sansheng/tasks-open', `还有 ${open.length} 个六部任务未结束,不能汇总:${open.map(item => item.id).join('、')}`)
|
||||||
|
const summary = summaryInput || children.map(item => `- ${item.id} ${SEATS[item.ownerSeatId]?.label ?? item.ownerSeatId} [${item.status}]:${item.result || item.note || '无结果'}`).join('\n')
|
||||||
|
const now = Date.now()
|
||||||
|
task.summary = summary
|
||||||
|
task.stage = 'menxia_acceptance'
|
||||||
|
task.ownerSeatId = 'menxia'
|
||||||
|
task.status = 'draft'
|
||||||
|
task.blockedReason = '待门下省验收'
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
const report = appendLeadReport(s, projectId, task, 'shangshu_summarize', summary)
|
||||||
|
queueDelivery(task, 'dispatched')
|
||||||
|
task.updatedAt = now
|
||||||
|
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||||
|
if (req) { req.blockedReason = '门下验收中'; req.updatedAt = now }
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { task: { ...task }, reportCreated: Boolean(report?.created) }
|
||||||
|
})
|
||||||
|
return dispatchAndFlushReport(this, projectId, taskId, next)
|
||||||
|
},
|
||||||
|
|
||||||
|
async workflowAccept(projectId, taskId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (actor.seatId !== 'menxia') throw new ServiceError('sansheng/forbidden', '只有门下省可以验收')
|
||||||
|
const action = cleanText(input.action)
|
||||||
|
if (!['accept', 'reject'].includes(action)) throw new ServiceError('sansheng/invalid', '验收动作必须是 accept 或 reject')
|
||||||
|
const note = cleanText(input.note)
|
||||||
|
if (action === 'reject' && !note) throw new ServiceError('sansheng/invalid', '验收退回必须写明原因')
|
||||||
|
const next = await this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||||||
|
if (task.ownerSeatId !== 'menxia' || task.stage !== 'menxia_acceptance') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在门下验收阶段')
|
||||||
|
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||||
|
const now = Date.now()
|
||||||
|
task.reviewNote = note
|
||||||
|
if (action === 'reject') {
|
||||||
|
task.stage = 'shangshu_dispatch'
|
||||||
|
task.ownerSeatId = 'shangshu'
|
||||||
|
task.status = 'returned'
|
||||||
|
task.blockedReason = '验收退回尚书省重新调度'
|
||||||
|
if (req) { req.blockedReason = `验收退回:${note}`; req.updatedAt = now }
|
||||||
|
} else {
|
||||||
|
task.stage = 'lead_delivery'
|
||||||
|
task.ownerSeatId = 'lead'
|
||||||
|
task.status = 'prepared'
|
||||||
|
task.blockedReason = '待丞相交付'
|
||||||
|
if (req) { req.blockedReason = '待丞相交付'; req.updatedAt = now }
|
||||||
|
}
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
const report = appendLeadReport(s, projectId, task, action === 'reject' ? 'menxia_accept_return' : 'menxia_accept', note || '验收通过')
|
||||||
|
queueDelivery(task, task.status)
|
||||||
|
task.updatedAt = now
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { task: { ...task }, reportCreated: Boolean(report?.created) }
|
||||||
|
})
|
||||||
|
return dispatchAndFlushReport(this, projectId, taskId, next)
|
||||||
|
},
|
||||||
|
|
||||||
|
async workflowDeliver(projectId, taskId, input = {}, actor = {}) {
|
||||||
|
await this.store.ensureLoaded()
|
||||||
|
if (actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以交付')
|
||||||
|
const deliveryNote = cleanText(input.delivery)
|
||||||
|
if (!deliveryNote) throw new ServiceError('sansheng/invalid', '交付内容不能为空')
|
||||||
|
return this.store.mutate(s => {
|
||||||
|
const project = s.projects[projectId]
|
||||||
|
const task = (project.tasks ?? []).find(item => item.id === taskId)
|
||||||
|
if (!task || task.kind !== 'workflow') throw new ServiceError('sansheng/not-found', `流程任务 ${taskId} 不存在`)
|
||||||
|
if (task.ownerSeatId !== 'lead' || task.stage !== 'lead_delivery') throw new ServiceError('sansheng/stage-forbidden', '当前任务不在丞相交付阶段')
|
||||||
|
const now = Date.now()
|
||||||
|
task.stage = 'delivered'
|
||||||
|
task.status = 'done'
|
||||||
|
task.deliveryNote = deliveryNote
|
||||||
|
task.deliveredAt = now
|
||||||
|
voidDelivery(task)
|
||||||
|
task.deliveredBySessionId = actor.sessionId ?? null
|
||||||
|
task.lastTransitionId = randomUUID()
|
||||||
|
task.blockedReason = ''
|
||||||
|
task.updatedAt = now
|
||||||
|
const req = (project.requirements ?? []).find(item => item.id === task.requirementId)
|
||||||
|
if (req) { req.blockedReason = '已交付'; req.updatedAt = now }
|
||||||
|
project.updatedAt = now
|
||||||
|
project.revision = (project.revision ?? 0) + 1
|
||||||
|
return { ok: true, task: { ...task } }
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue