dsh-sansheng-liubu/sansheng/src/host/service.js

1113 lines
57 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { randomUUID, createHash } from 'node:crypto'
import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../shared/roles.js'
import { emptyTask, emptyArtifact, emptyRequirement } from '../shared/schema.js'
import { mergeProjectMemory, normalizeProjectMemory, renderProjectMemory } from '../shared/project-memory.js'
import { applyModel, normalizeSelection } from './model.js'
export class ServiceError extends Error {
constructor(code, message) { super(message); this.name = 'ServiceError'; this.code = code }
}
export function seatView(seatId, seat) {
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,
instructions: seat.instructions ?? '',
error: seat.error ?? null,
}
}
export function projectView(project) {
return {
revision: project.revision ?? 0,
project: {
id: project.id,
name: project.name,
workspaceId: project.workspaceId ?? null,
path: project.path ?? null,
status: project.status,
seats: SEAT_IDS.map(id => seatView(id, project.seats[id])),
groups: {
lead: [...SEAT_GROUPS.lead],
sansheng: [...SEAT_GROUPS.sansheng],
liubu: [...SEAT_GROUPS.liubu],
},
},
}
}
const REQUIREMENT_TEXT_FIELDS = [
'title', 'summary', 'originalText', 'judgement', 'judgementReason', 'scope',
'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo',
]
const OPEN_TASK_STATUS = new Set(['draft', 'dispatched', 'running', 'prepared', 'waiting_user', 'returned', 'reconfirm'])
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
function requirementReadyProblem(req) {
if (!req || !cleanText(req.title)) return '缺少需求标题'
if (!cleanText(req.originalText)) return '缺少用户原始要求'
if (req.judgement !== 'can_do') return '丞相判断尚不可立项'
if (!cleanText(req.scope)) return '缺少范围'
if (!cleanText(req.acceptanceCriteria)) return '缺少验收标准'
return ''
}
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'
}
function requirementBlockedReason(req) {
if (req.status === 'cancelled') return '已取消'
if (req.status === 'published') return req.blockedReason || '已发布,等待流程推进'
if (req.status === 'returned') return req.blockedReason || '已退回,等待重新商讨或拟案'
const problem = requirementReadyProblem(req)
if (problem) return problem
return '待用户明确发布:在聊天中发送「发布 ' + req.id + ' 给中书」'
}
function explicitPublishCommand(command, requirementId) {
const raw = cleanText(command)
if (!raw || /(不要|别|暂不|取消|不发布)/.test(raw)) return false
const id = requirementId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
return new RegExp('发布\\s*' + id, 'i').test(raw) && /中书/.test(raw)
}
function explicitApprovalCommand(command, requirementId) {
const raw = cleanText(command)
if (!raw || /(不要|别|暂不|取消|不批准|拒绝)/.test(raw)) return false
const id = requirementId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
return /批准执行/.test(raw) && new RegExp(id, 'i').test(raw)
}
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,
}
}
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},停止新增工作并报告是否需要重新确认`
}
task.updatedAt = now
}
}
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: '请执行获批任务,并使用 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 === 'awaiting_execution_approval')) 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 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
return {
providers,
default: def && (def.provider || def.model) ? { provider: def.provider ?? null, model: def.model ?? null } : null,
failures: catalog?.failures ?? catalog?.isolated ?? [],
}
}
export class SanshengService {
constructor({ store, host, provisioner }) {
this.store = store
this.host = host
this.provisioner = provisioner
}
async memory(projectId) {
await this.store.ensureLoaded()
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
return { memory: normalizeProjectMemory(project.memory, projectId) }
}
async memoryUpdate(projectId, patch = {}) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${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 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.store.ensureLoaded()
const p = this.store.get(projectId)
if (!p) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
await this.provisioner.ensureTitles(projectId)
return projectView(this.store.get(projectId))
}
async enable(projectId) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
await this.provisioner.enable(projectId)
return this.project(projectId)
}
async enableSeat(projectId, seatId) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${String(seatId)}`)
await this.provisioner.enableSeat(projectId, seatId)
return this.project(projectId)
}
async openSeat(projectId, seatId) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${String(seatId)}`)
const result = await this.provisioner.openSeat(projectId, seatId)
return { ...this.project(projectId), sessionId: result.sessionId, seatId: result.seatId }
}
async rebuildSeat(projectId, seatId, { expectedSessionId } = {}) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${String(seatId)}`)
const result = await this.provisioner.rebuildSeat(projectId, seatId, { expectedSessionId })
return {
...this.project(projectId),
sessionId: result.sessionId,
seatId: result.seatId,
previousSessionId: result.previousSessionId ?? null,
}
}
async configure(projectId, seatId, { model, instructions } = {}) {
await this.store.ensureLoaded()
if (!SEAT_IDS.includes(seatId)) throw new ServiceError('sansheng/invalid', `未知席 ${seatId}`)
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
const seat = project.seats[seatId]
let normalized
let applied = null
if (model !== undefined) {
normalized = normalizeSelection(model) // 可能抛 sansheng/model-invalid
if (seat.sessionId) applied = await applyModel(this.host, seat.sessionId, normalized)
}
if (instructions !== undefined && typeof instructions !== 'string') {
throw new ServiceError('sansheng/invalid', 'instructions 必须是字符串')
}
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
})
return { seat: seatView(seatId, this.store.get(projectId).seats[seatId]), applied }
}
async models() {
await this.store.ensureLoaded()
const catalog = await this.host.sessionController.modelCatalog()
return normalizeCatalog(catalog)
}
async tasks(projectId) {
await this.store.ensureLoaded()
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
return { tasks: [...(project.tasks ?? [])] }
}
// 只读任务汇总:按状态/主责席位统计,并返回可追溯的任务明细。
async taskSummary(projectId) {
await this.store.ensureLoaded()
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${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',
})),
}
}
// 轻量版尚书汇总:只把当前真实任务快照发给尚书汇总,不改变丞相直派流程,不创建新任务。
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?.prompt !== 'function') {
throw new ServiceError('sansheng/delivery-failed', '宿主未提供 prompt 接口,无法发送尚书汇总请求')
}
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')
const requestId = randomUUID()
try {
await controller.prompt({
requestId,
sessionId: seat.sessionId,
mode: 'queue',
content: [{ type: 'text', text }],
}, new AbortController().signal)
} catch (error) {
throw new ServiceError('sansheng/delivery-failed', `尚书汇总请求发送失败:${error?.message ?? error}`)
}
return { ok: true, sessionId: seat.sessionId, summary }
}
async requirements(projectId) {
await this.store.ensureLoaded()
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
return {
requirements: structuredClone(project.requirements ?? []),
approvals: structuredClone(project.approvals ?? []),
}
}
async requirementUpsert(projectId, input = {}, actor = {}) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${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 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] ?? ''))
if (!created && before === after) {
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.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${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'
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.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以发布需求给中书省')
if (!explicitPublishCommand(input.command, requirementId)) {
throw new ServiceError('sansheng/publish-not-explicit', `未检测到明确发布命令。请在聊天中发送「发布 ${requirementId} 给中书」`)
}
const expectedRevision = Number(input.expectedRevision)
if (!Number.isFinite(expectedRevision)) throw new ServiceError('sansheng/invalid', '发布需求必须带 expectedRevision')
const published = await 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} 不存在`)
if (req.revision !== expectedRevision) throw new ServiceError('sansheng/requirement-conflict', `需求已更新到 v${req.revision},发布命令基于 v${expectedRevision},已失效`)
if (req.status !== 'ready') throw new ServiceError('sansheng/requirement-not-ready', `需求 ${req.id} 当前状态为 ${req.status},只有「待发布」的需求可以发布`)
const 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,
requirement: req.originalText,
ownerSeatId: 'zhongshu',
kind: 'workflow',
requirementId: req.id,
requirementRevision: req.revision,
stage: 'zhongshu_draft',
now,
})
task.requirementSnapshot = requirementSnapshot(req)
task.blockedReason = '中书省拟案中'
if (!Array.isArray(project.tasks)) project.tasks = []
project.tasks.push(task)
req.status = 'published'
req.publishedRevision = req.revision
req.publishedAt = now
req.blockedReason = '已发布,等待中书省拟案'
req.updatedAt = now
project.updatedAt = now
project.revision = (project.revision ?? 0) + 1
return { task: { ...task }, requirement: { ...req } }
})
let dispatched = { delivered: false, task: published.task }
try { dispatched = await this.taskDispatch(projectId, published.task.id, { force: true }) } catch (error) {
const reason = error?.code === 'sansheng/seat-unbound' ? 'target-seat-unavailable' : 'delivery-failed'
return { ok: false, delivered: false, reason, taskId: published.task.id, requirement: published.requirement, error: `已创建中书任务但投递失败:${error?.message ?? error}` }
}
const delivered = Boolean(dispatched.delivered)
return { ok: delivered, delivered, reason: delivered ? undefined : 'delivery-failed', taskId: published.task.id, task: dispatched.task, requirement: published.requirement }
}
async requirementApprove(projectId, requirementId, input = {}, actor = {}) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
if (actor.seatId && actor.seatId !== 'lead') throw new ServiceError('sansheng/forbidden', '只有丞相可以提交用户批准')
if (!explicitApprovalCommand(input.command, requirementId)) {
throw new ServiceError('sansheng/approval-not-explicit', `未检测到明确批准命令。请在聊天中发送「批准执行 ${requirementId}」`)
}
const expectedRevision = Number(input.expectedRevision)
if (!Number.isFinite(expectedRevision)) throw new ServiceError('sansheng/invalid', '批准必须带 expectedRevision')
const approved = await 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} 不存在`)
if (req.revision !== expectedRevision) throw new ServiceError('sansheng/requirement-conflict', `需求已更新到 v${req.revision},批准命令已失效`)
if (req.status !== 'published' || req.publishedRevision !== req.revision) throw new ServiceError('sansheng/not-published', '需求不在已发布状态,不能批准执行')
if ((project.approvals ?? []).some(item => item.requirementId === req.id && item.requirementRevision === req.revision && item.status === 'approved')) {
throw new ServiceError('sansheng/approval-duplicate', '该需求版本已经批准,不能重复批准')
}
const task = [...(project.tasks ?? [])].reverse().find(item => item.requirementId === req.id && item.requirementRevision === req.revision && item.kind === 'workflow' && item.stage === 'awaiting_execution_approval' && item.status === 'waiting_user')
if (!task) throw new ServiceError('sansheng/approval-not-ready', '门下审核尚未通过或需求已变更,当前没有等待用户批准的执行方案')
const now = Date.now()
project.approvalSeq = (project.approvalSeq ?? 0) + 1
const approval = {
id: `AP-${String(project.approvalSeq).padStart(3, '0')}`,
requirementId: req.id, requirementRevision: req.revision,
status: 'approved', scope: req.scope, approvedAt: now,
approvedBy: 'user', approvalCommand: cleanText(input.command),
}
if (!Array.isArray(project.approvals)) 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 = '用户已批准执行,等待尚书省调度六部'
task.deliveryState = 'none'
task.updatedAt = now
req.blockedReason = '用户已批准执行,等待尚书省调度六部'
req.updatedAt = now
project.updatedAt = now
project.revision = (project.revision ?? 0) + 1
return { task: { ...task }, approval: { ...approval }, requirement: { ...req } }
})
let dispatched = { delivered: false, task: approved.task }
try { dispatched = await this.taskDispatch(projectId, approved.task.id, { force: true }) } catch (error) {
const reason = error?.code === 'sansheng/seat-unbound' ? 'target-seat-unavailable' : 'delivery-failed'
return { ok: false, delivered: false, reason, taskId: approved.task.id, approval: approved.approval, error: `已记录批准但投递尚书失败:${error?.message ?? error}` }
}
const delivered = Boolean(dispatched.delivered)
return { ok: delivered, delivered, reason: delivered ? undefined : 'delivery-failed', taskId: approved.task.id, task: dispatched.task, approval: approved.approval, requirement: approved.requirement }
}
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 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()
task.draft = draft
task.stage = 'menxia_review'
task.ownerSeatId = 'menxia'
task.status = 'draft'
task.blockedReason = '待门下省审核'
task.deliveryState = 'none'
task.result = null
task.resultAt = null
task.updatedAt = now
req.status = 'published'
req.blockedReason = '门下省审核中'
req.updatedAt = now
project.updatedAt = now
project.revision = (project.revision ?? 0) + 1
return { task: { ...task } }
})
const dispatched = await this.taskDispatch(projectId, taskId, { force: true })
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
}
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()
if (action === 'return') {
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', '中书尚未提交拟案,不能审核通过')
task.stage = 'awaiting_execution_approval'
task.ownerSeatId = 'lead'
task.status = 'waiting_user'
task.reviewNote = note
task.blockedReason = '等待用户明确批准执行'
req.status = 'published'
req.blockedReason = '方案已审核,等待用户批准执行'
}
task.deliveryState = 'none'
task.updatedAt = now
req.updatedAt = now
project.updatedAt = now
project.revision = (project.revision ?? 0) + 1
return { task: { ...task } }
})
const dispatched = await this.taskDispatch(projectId, taskId, { force: true, keepStatus: true })
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
}
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 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', '当前任务不在尚书调度阶段')
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 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) || req.scope,
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 = requirementSnapshot(req)
child.blockedReason = '六部执行中'
project.tasks.push(child)
children.push({ ...child })
}
task.stage = 'department_exec'
task.status = 'running'
task.blockedReason = '六部执行中'
task.deliveryState = 'none'
task.updatedAt = now
req.blockedReason = '六部执行中'
req.updatedAt = now
project.updatedAt = now
project.revision = (project.revision ?? 0) + 1
return { task: { ...task }, children }
})
const deliveries = []
for (const child of result.children) {
try {
const delivered = await this.taskDispatch(projectId, child.id, { force: true })
deliveries.push({ taskId: child.id, seatId: child.ownerSeatId, delivered: delivered.delivered })
} catch (error) {
deliveries.push({ taskId: child.id, seatId: child.ownerSeatId, delivered: false, error: error?.message ?? String(error) })
}
}
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.deliveryState = 'none'
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 } }
})
const dispatched = await this.taskDispatch(projectId, taskId, { force: true })
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
}
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.deliveryState = 'none'
task.updatedAt = now
project.updatedAt = now
project.revision = (project.revision ?? 0) + 1
return { task: { ...task } }
})
const dispatched = await this.taskDispatch(projectId, taskId, { force: true, keepStatus: true })
return { ok: dispatched.delivered, delivered: dispatched.delivered, task: dispatched.task }
}
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
task.deliveredBySessionId = actor.sessionId ?? null
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 } }
})
}
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 taskDispatch(projectId, taskId, options = {}) {
await this.store.ensureLoaded()
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
const task = (project.tasks ?? []).find(item => item.id === taskId)
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
if (task.status === 'done' || task.status === 'cancelled') throw new ServiceError('sansheng/invalid', '已完成或已取消的任务不能再次派工;请新建任务保留历史结果')
// 同一任务已成功投递时不重复刷屏;修改要求后由 taskRevise 显式 force 重发。
if (task.deliveryState === 'accepted' && task.status === 'dispatched' && !options.force) {
return { task: { ...task }, delivered: true, duplicate: true }
}
let seat = project.seats[task.ownerSeatId]
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
// 按需开启:丞相派工时只给出主责部门,由系统用该部门预配置的模型开启会话;丞相不选模型。
await this.provisioner.enableSeat(projectId, task.ownerSeatId)
seat = this.store.get(projectId)?.seats?.[task.ownerSeatId]
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
throw new ServiceError('sansheng/seat-unbound', `「${SEATS[task.ownerSeatId]?.label ?? task.ownerSeatId}」的会话还没开启成功,请稍后重试`)
}
}
const memory = normalizeProjectMemory(project.memory, projectId)
const memoryText = renderProjectMemory(memory)
const detail = [
`【任务】${task.title}`,
task.goal ? `任务说明:${task.goal}` : '',
task.requirement ? `用户原话:${task.requirement}` : '',
workflowStageHint(task),
].filter(Boolean).join('\n')
const text = [memoryText, detail].filter(Boolean).join('\n\n')
const deliveryId = randomUUID()
let delivered = false
let note = ''
const controller = this.host.sessionController
if (typeof controller?.prompt === 'function') {
try {
await controller.prompt({
requestId: deliveryId,
sessionId: seat.sessionId,
mode: 'queue',
content: [{ type: 'text', text }],
}, new AbortController().signal)
delivered = true
} catch (error) {
note = `发送失败:${error?.message ?? error}`
}
} else {
note = '宿主未提供 prompt 接口,已记录待执行'
}
const activeDecisions = memory.decisions.filter(item => item.status === 'active').map(item => item.id)
const next = await this.store.mutate(s => {
const target = s.projects[projectId].tasks.find(item => item.id === taskId)
target.status = options.status ? options.status : (options.keepStatus ? target.status : (delivered ? 'dispatched' : 'prepared'))
target.note = delivered ? '' : note
target.sessionId = seat.sessionId
target.dispatchedAt = Date.now()
target.updatedAt = Date.now()
target.contextRevision = memory.revision
target.contextHash = memory.contentHash
target.decisionIds = activeDecisions
target.sourceRefs = memory.sources.slice(0, 20)
target.deliveryId = deliveryId
target.deliveryState = delivered ? 'accepted' : 'unknown'
target.contextSyncState = delivered ? 'provided' : 'observed'
s.projects[projectId].updatedAt = Date.now()
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
return { ...target }
})
return { task: next, delivered, duplicate: false }
}
async taskGet(projectId, taskId) {
await this.store.ensureLoaded()
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
const task = (project.tasks ?? []).find(item => item.id === taskId)
if (!task) throw new ServiceError('sansheng/not-found', `任务 ${taskId} 不存在`)
return { task: { ...task } }
}
async taskReport(projectId, taskId, input = {}) {
await this.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${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 next = 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', '已完成的任务不能回退状态')
// 已取消任务的结果迟到:保留取消状态,但把真实结果留档,不假装没发生。
const late = task.status === 'cancelled'
if (!late) task.status = status
if (result) task.result = result
if (late || status === 'done' || status === 'failed') {
task.resultAt = Date.now()
task.resultSessionId = input.sessionId ?? null
task.reportStatus = late ? 'late' : status
} 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
return { ...task, late }
})
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'
task.deliveryState = 'none'
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.store.ensureLoaded()
if (!this.store.get(projectId)) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
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'
target.updatedAt = Date.now()
s.projects[projectId].revision = (s.projects[projectId].revision ?? 0) + 1
return { ...target }
})
return { task: next }
}
async artifacts(projectId) {
await this.store.ensureLoaded()
const project = this.store.get(projectId)
if (!project) throw new ServiceError('sansheng/not-found', `项目 ${projectId} 不存在`)
return { artifacts: [...(project.artifacts ?? [])] }
}
async artifactAdd(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', '成果名称不能为空')
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 }
}
}