import { budgetOf } from './gate.js' import { ROLE_IDS, ROLE_LABEL } from './roles.js' const DETAIL_MAX = 80 function clip(text, max = DETAIL_MAX) { const value = String(text ?? '').replace(/\s+/g, ' ').trim() if (value === '') return '' return value.length <= max ? value : `${value.slice(0, max - 1)}…` } function sortReviews(reviews) { return [...(reviews ?? [])].sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0)) } function latest(reviews) { const sorted = sortReviews(reviews) return sorted.length > 0 ? sorted[0] : undefined } function taskCounts(stage, botId) { const tasks = (stage?.tasks ?? []).filter(task => task.botId === botId) const done = tasks.filter(task => task.status === 'done').length const active = tasks.filter(task => task.status === 'active' || task.status === 'doing' || task.status === 'working').length return { total: tasks.length, done, active, open: tasks.length - done } } function botChatSessionId(bot) { // DS Bot 的 Bot id 就是它的私聊 root Session id;部分状态版本另有 sessionId 字段。 return bot?.sessionId ?? bot?.id ?? null } function leadCard({ project, goal, bot, goalReviews }) { const review = latest(goalReviews) const card = { role: 'lead', label: ROLE_LABEL.lead, duty: '定目标 · 最终验收', botId: project.bots?.lead ?? null, name: bot?.name ?? null, model: project.models?.lead ?? bot?.model ?? null, exists: Boolean(bot), sessionId: botChatSessionId(bot), clickable: Boolean(botChatSessionId(bot)), line: '等待交付', detail: '', tone: 'idle', next: '', } if (review) { card.line = review.verdict === 'pass' ? `已验收 rev ${review.goalRevision ?? '?'}` : `驳回 rev ${review.goalRevision ?? '?'}` card.detail = clip(review.reason ?? review.evidence) card.tone = review.verdict === 'pass' ? 'ok' : 'warn' return card } if (goal && (goal.stages ?? []).length > 0 && (goal.stages ?? []).every(stage => stage.status === 'passed')) { card.line = '等待验收' card.tone = 'attention' card.next = '打开丞相会话,核对整体交付后记录 goal_pass。' } else if (goal) { card.line = '目标进行中' } card.detail = clip(goal?.objective ?? '') return card } function shangshuCard({ project, goal, bot, budget, unknown, dispatches }) { const card = { role: 'shangshu', label: ROLE_LABEL.shangshu, duty: '调度阶段 · 核查证据', botId: project.bots?.shangshu ?? null, name: bot?.name ?? null, model: project.models?.shangshu ?? bot?.model ?? null, exists: Boolean(bot), sessionId: botChatSessionId(bot), clickable: Boolean(botChatSessionId(bot)), line: '未起草目标', detail: '', tone: 'idle', next: '', } if (!goal) { card.detail = '用 group_goal draft / start 起草目标' card.next = '打开尚书会话,起草目标与阶段。' return card } const stages = goal.stages ?? [] const passed = stages.filter(stage => stage.status === 'passed').length const stage = stages[goal.current] card.line = stage ? `阶段 ${passed}/${stages.length} · ${clip(stage.title, 24)}` : `阶段 ${passed}/${stages.length}` const parts = [`返工 ${budget.used}/${budget.max}`] if (unknown > 0) parts.push(`待核实 ${unknown}`) const recent = latest(dispatches) if (recent) parts.push(clip(recent.action, 12)) card.detail = parts.join(' · ') card.tone = goal.status === 'complete' ? 'ok' : unknown > 0 ? 'warn' : 'active' if (unknown > 0) card.next = '先核对 unknown 派发,再决定是否重发。' return card } function gongbuCard({ project, goal, bot, stageReviews, currentStageIndex }) { const card = { role: 'gongbu', label: ROLE_LABEL.gongbu, duty: '执行工单 · 提交证据', botId: project.bots?.gongbu ?? null, name: bot?.name ?? null, model: project.models?.gongbu ?? bot?.model ?? null, exists: Boolean(bot), sessionId: botChatSessionId(bot), clickable: Boolean(botChatSessionId(bot)), line: '无工单', detail: '', tone: 'idle', next: '', } const stage = goal?.stages?.[goal.current] const counts = taskCounts(stage, project.bots?.gongbu) // 只看当前阶段的最新审查:历史驳回在后续通过后不再显示为返工中。 // 兼容旧记录:0-based(goal.current)与 1-based(审查工具)都接受。 const currentIndexes = new Set([currentStageIndex, goal?.current]) const currentReviews = (stageReviews ?? []).filter(review => currentIndexes.has(review.stageIndex ?? null)) const latestStage = latest(currentReviews) const reject = latestStage?.verdict === 'reject' ? latestStage : undefined if (counts.total > 0) { const open = (stage.tasks ?? []).find(task => task.botId === project.bots?.gongbu && task.status !== 'done') card.line = reject ? `返工中 · 工单 ${counts.done}/${counts.total}` : counts.open > 0 ? `工单 ${counts.done}/${counts.total}` : `工单 ${counts.total} 条已完成` card.detail = clip(reject?.reason ?? open?.task ?? (stage.tasks ?? []).find(task => task.botId === project.bots?.gongbu)?.task ?? '') card.tone = reject ? 'warn' : counts.open > 0 ? 'active' : 'ok' if (reject) card.next = '按驳回原因返工,完成后提交证据。' return card } if (reject) { card.line = '返工中' card.detail = clip(reject.reason) card.tone = 'warn' card.next = '按驳回原因返工,完成后提交证据。' } return card } function stageDecisionFor(project, goal, state) { if (!goal) return undefined const stageIndex = (goal.current ?? -1) + 1 const matches = (state.reviews ?? []).filter(review => review.projectId === project.id && review.goalId === goal.id && review.kind === 'stage' && (review.stageIndex ?? null) === stageIndex) return latest(matches) } function computePhase({ project, goal, roomExists, unknown, state }) { if (!roomExists) return '失败' if (!goal) return Object.keys(project.bots ?? {}).length === 3 ? '待执行' : '待配置' if (goal.status === 'paused') return '暂停' if (goal.status === 'complete') return '已完成' if (goal.status === 'stopped') return '失败' if (goal.status === 'drafting') return '待执行' if (unknown > 0) return '待核实' const stages = goal.stages ?? [] const stage = stages[goal.current] const decision = stageDecisionFor(project, goal, state) if (decision?.verdict === 'reject') return '返工中' if (stages.length > 0 && stages.every(item => item.status === 'passed')) return '待审查' if (stage) { const tasks = stage.tasks ?? [] const open = tasks.filter(task => task.status !== 'done') if (tasks.length > 0 && open.length === 0) return '待审查' if (tasks.length > 0) return '执行中' } return '待执行' } /** * 右侧栏三卡片的数据源:纯函数,方便单测。 * 只读 sansheng 自己的状态 + DS Bot 的只读视图,不写任何东西。 * v3 增加 phase / attention / currentStage / submission / 折叠历史;旧字段保持兼容。 */ export function buildStatePayload({ store, dsbot, now = Date.now() }) { const state = store.peek() const projects = Object.values(state.projects ?? {}).map(project => { const room = dsbot.roomOf(project.roomId) const goal = room?.goal const budget = budgetOf(goal, project, state.reworks) const unknown = store.unknownDispatches(project.id).length const dispatches = store.dispatchesFor(project.id, 3) const goalReviews = store.reviewsFor({ projectId: project.id, kind: 'goal' }) const stageReviews = store.reviewsFor({ projectId: project.id, kind: 'stage' }) const bots = ROLE_IDS.map(role => dsbot.botOf(project.bots?.[role])) const roles = [ leadCard({ project, goal, bot: bots[0], goalReviews }), shangshuCard({ project, goal, bot: bots[1], budget, unknown, dispatches }), gongbuCard({ project, goal, bot: bots[2], stageReviews, currentStageIndex: (goal?.current ?? -1) + 1 }), ] // 角色卡上的 sessionId 以 DS Bot 当前会话为准(私聊 Bot 的 sessionId)。 for (const card of roles) { const bot = dsbot.botOf(card.botId) const botSession = botChatSessionId(bot) if (botSession) { card.sessionId = botSession card.clickable = true } } const phase = computePhase({ project, goal, roomExists: Boolean(room), unknown, state }) const attention = roles .filter(card => card.tone === 'warn' || card.tone === 'attention') .map(card => ({ role: card.role, label: card.label, reason: card.detail || card.line, next: card.next })) if (unknown > 0 && !attention.some(item => item.role === 'shangshu')) { attention.push({ role: 'shangshu', label: ROLE_LABEL.shangshu, reason: `${unknown} 条派发待核实`, next: '核对 unknown 派发后再决定是否重发。' }) } const stage = goal?.stages?.[goal.current] const decision = stageDecisionFor(project, goal, state) const history = [...(state.reviews ?? []).filter(review => review.projectId === project.id)] .sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0)) .slice(0, 20) .map(review => ({ id: review.id, kind: review.kind, verdict: review.verdict, reviewerRole: review.reviewerRole, goalRevision: review.goalRevision, stageIndex: review.stageIndex, reason: clip(review.reason ?? review.evidence, 120), at: review.at, })) const artifacts = typeof store.artifactsFor === 'function' ? store.artifactsFor(project.id, 1) : [] return { id: project.id, name: project.name, roomId: project.roomId, roomName: room?.name ?? null, roomExists: Boolean(room), workspaceId: project.workspaceId ?? null, hostWorkspaceId: project.hostWorkspaceId ?? project.workspaceId ?? null, workDir: project.workDir ?? null, autoRework: project.autoRework !== false, phase, attention, submissionSeq: project.submissionSeq ?? artifacts[0]?.submissionSeq ?? 0, lastSubmission: artifacts.length > 0 ? { id: artifacts[0].id, digest: artifacts[0].digest, kind: artifacts[0].kind, fileCount: artifacts[0].fileCount, totalBytes: artifacts[0].totalBytes, submissionSeq: artifacts[0].submissionSeq, createdAt: artifacts[0].createdAt, } : null, lease: typeof store.leaseOf === 'function' && store.leaseOf(project.id) ? { holder: store.leaseOf(project.id).holder, taskId: store.leaseOf(project.id).taskId, expiresAt: store.leaseOf(project.id).expiresAt } : null, roles, goal: goal ? { status: goal.status, revision: goal.revision, title: clip(goal.title, 60), objective: clip(goal.objective), stages: (goal.stages ?? []).length, passed: (goal.stages ?? []).filter(stage => stage.status === 'passed').length, stageIndex: goal.current, stageTitle: clip(goal.stages?.[goal.current]?.title, 60), } : null, currentStage: stage ? { index: goal.current + 1, title: clip(stage.title, 60), acceptance: clip(stage.acceptance, 120), reworks: Number(stage.reworks) || 0, taskCounts: taskCounts(stage, project.bots?.gongbu), lastDecision: decision ? { verdict: decision.verdict, reason: clip(decision.reason ?? decision.evidence, 120), at: decision.at } : null, } : null, budget, unknownDispatches: unknown, reviews: goalReviews.concat(stageReviews) .sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0)) .slice(0, 3) .map(review => ({ kind: review.kind, verdict: review.verdict, reviewerRole: review.reviewerRole, goalRevision: review.goalRevision, stageIndex: review.stageIndex, at: review.at, })), reviewsHistory: history, recentDispatches: dispatches.map(item => ({ id: item.id, action: item.action, status: item.status, at: item.at, stageIndex: item.stageIndex, })), // 只有需要人类动作时才突出显示;其余状态保持安静。 nextAction: attention[0]?.next ?? null, } }) projects.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN')) return { generatedAt: now, projects } } /** 当前 DS Bot 花名册(只读),供右栏「Bot 切换」使用;不改变项目绑定。 */ export function listBots({ dsbot, store }) { let state = {} try { state = dsbot.snapshot() ?? {} } catch { state = {} } const mainIds = new Set(state.mainBotIds ?? []) const bots = Object.values(state.bots ?? {}).map(bot => { const project = typeof store.projectsByBot === 'function' ? store.projectsByBot(bot.id)[0] : store.projectByBot(bot.id) return { id: bot.id, name: bot.name ?? bot.id, role: bot.role ?? null, model: bot.model ?? null, sessionId: bot.sessionId ?? bot.id, isMain: mainIds.has(bot.id), projectId: project?.id ?? null, projectName: project?.name ?? null, } }).sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN')) const rooms = Object.values(state.rooms ?? {}).map(room => { const project = typeof store.projectByRoom === 'function' ? store.projectByRoom(room.id) : undefined return { id: room.id, name: room.name ?? room.id, sessionId: room.sessionId ?? room.id, memberCount: (room.members ?? []).length, projectId: project?.id ?? null, projectName: project?.name ?? null, } }).sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN')) return { bots, rooms } } /** 根据 workspaceId / sessionId 找出当前项目(由调用方决定 workspaceId 来源)。 */ export function resolveCurrentProject(payload, { workspaceId, sessionId } = {}) { const projects = payload?.projects ?? [] if (workspaceId) { const byWorkspace = projects.find(project => project.workspaceId === workspaceId || project.hostWorkspaceId === workspaceId) if (byWorkspace) return { project: byWorkspace, matchedBy: 'workspace' } } if (sessionId) { const bySession = projects.find(project => project.roles?.some(role => role.sessionId === sessionId)) if (bySession) return { project: bySession, matchedBy: 'session' } } return { project: undefined, matchedBy: null } }