feat(requirement-gate): 实现丞相需求门控模式与工作台需求清单
This commit is contained in:
parent
16da0b1568
commit
d1c7112c8b
|
|
@ -383,7 +383,10 @@ var TASK_LABELS = {
|
|||
prepared: "待复核",
|
||||
done: "已完成",
|
||||
cancelled: "已取消",
|
||||
failed: "失败"
|
||||
failed: "失败",
|
||||
waiting_user: "待用户批准",
|
||||
returned: "已退回",
|
||||
reconfirm: "待重新确认"
|
||||
};
|
||||
var TASK_TONES = {
|
||||
draft: "idle",
|
||||
|
|
@ -392,9 +395,35 @@ var TASK_TONES = {
|
|||
prepared: "review",
|
||||
done: "done",
|
||||
cancelled: "idle",
|
||||
failed: "fail"
|
||||
failed: "fail",
|
||||
waiting_user: "review",
|
||||
returned: "fail",
|
||||
reconfirm: "fail"
|
||||
};
|
||||
var OPEN_STATUS = /* @__PURE__ */ new Set(["dispatched", "running", "prepared"]);
|
||||
var REQ_STATUS_LABELS = {
|
||||
discussing: "商讨中",
|
||||
ready: "待发布",
|
||||
published: "已发布",
|
||||
returned: "已退回",
|
||||
cancelled: "已取消"
|
||||
};
|
||||
var REQ_JUDGEMENT_LABELS = {
|
||||
can_do: "可立项",
|
||||
needs_discussion: "需商讨",
|
||||
not_now: "暂不可做"
|
||||
};
|
||||
var WORKFLOW_STAGE_LABELS = {
|
||||
zhongshu_draft: "中书拟案",
|
||||
menxia_review: "门下审核",
|
||||
awaiting_execution_approval: "待用户批准",
|
||||
shangshu_dispatch: "尚书调度",
|
||||
department_exec: "六部执行",
|
||||
menxia_acceptance: "门下验收",
|
||||
lead_delivery: "丞相交付",
|
||||
delivered: "已交付",
|
||||
reconfirm: "待重新确认"
|
||||
};
|
||||
function toneOfSeat(seat) {
|
||||
if (!seat) return "idle";
|
||||
if (seat.status === "bound" || seat.status === "creating") return "run";
|
||||
|
|
@ -606,6 +635,9 @@ function WorkbenchV2(props) {
|
|||
const [memory, setMemory] = (0, import_react.useState)(null);
|
||||
const [memoryDraft, setMemoryDraft] = (0, import_react.useState)({ goal: "", constraints: "", acceptance: "", decisions: "" });
|
||||
const [tasks, setTasks] = (0, import_react.useState)([]);
|
||||
const [requirements, setRequirements] = (0, import_react.useState)([]);
|
||||
const [approvals, setApprovals] = (0, import_react.useState)([]);
|
||||
const [reqView, setReqView] = (0, import_react.useState)("requirements");
|
||||
const [artifacts, setArtifacts] = (0, import_react.useState)([]);
|
||||
const [artifactDraft, setArtifactDraft] = (0, import_react.useState)({ title: "", path: "", summary: "" });
|
||||
const [artifactFormOpen, setArtifactFormOpen] = (0, import_react.useState)(false);
|
||||
|
|
@ -647,11 +679,16 @@ function WorkbenchV2(props) {
|
|||
}
|
||||
let taskList = [];
|
||||
let artifactList = [];
|
||||
let requirementData = { requirements: [], approvals: [] };
|
||||
try {
|
||||
taskList = (await request("tasks", { projectId: projectView.project.id })).tasks ?? [];
|
||||
} catch (taskError) {
|
||||
console.warn("[sansheng] 任务加载失败:", taskError && taskError.message ? taskError.message : taskError);
|
||||
}
|
||||
try {
|
||||
requirementData = await request("requirements", { projectId: projectView.project.id });
|
||||
} catch {
|
||||
}
|
||||
try {
|
||||
artifactList = (await request("artifacts", { projectId: projectView.project.id })).artifacts ?? [];
|
||||
} catch {
|
||||
|
|
@ -663,6 +700,8 @@ function WorkbenchV2(props) {
|
|||
setMemoryDraft({ goal: memoryData?.goal ?? "", constraints: (memoryData?.constraints ?? []).join("\n"), acceptance: (memoryData?.acceptance ?? []).join("\n"), decisions: "" });
|
||||
setTasks(taskList);
|
||||
setArtifacts(artifactList);
|
||||
setRequirements(Array.isArray(requirementData.requirements) ? requirementData.requirements : []);
|
||||
setApprovals(Array.isArray(requirementData.approvals) ? requirementData.approvals : []);
|
||||
setPhase("ready");
|
||||
} catch (loadError) {
|
||||
if (!alive.current) return;
|
||||
|
|
@ -685,16 +724,19 @@ function WorkbenchV2(props) {
|
|||
if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
|
||||
running = true;
|
||||
try {
|
||||
const [projectView, taskRes, artifactRes] = await Promise.all([
|
||||
const [projectView, taskRes, artifactRes, requirementData] = await Promise.all([
|
||||
request("project", { projectId }),
|
||||
request("tasks", { projectId }),
|
||||
request("artifacts", { projectId })
|
||||
request("artifacts", { projectId }),
|
||||
request("requirements", { projectId }).catch(() => ({ requirements: [], approvals: [] }))
|
||||
]);
|
||||
if (disposed || !alive.current) return;
|
||||
setView(projectView);
|
||||
const nextTasks = taskRes && Array.isArray(taskRes.tasks) ? taskRes.tasks : [];
|
||||
setTasks(nextTasks);
|
||||
setArtifacts(artifactRes && Array.isArray(artifactRes.artifacts) ? artifactRes.artifacts : []);
|
||||
setRequirements(Array.isArray(requirementData?.requirements) ? requirementData.requirements : []);
|
||||
setApprovals(Array.isArray(requirementData?.approvals) ? requirementData.approvals : []);
|
||||
setSelectedTask((previous) => previous ? nextTasks.find((task) => task.id === previous.id) || previous : previous);
|
||||
} catch {
|
||||
} finally {
|
||||
|
|
@ -1006,6 +1048,139 @@ function WorkbenchV2(props) {
|
|||
(0, import_react.createElement)("div", { className: "node-foot" }, (0, import_react.createElement)("span", { className: "elapsed" }, latest ? taskLabel(latest.status) : seat.status === "bound" ? "在线 · 待命" : "未运行 · 待命"))
|
||||
);
|
||||
}
|
||||
function reqTone(status) {
|
||||
if (status === "ready" || status === "published") return "review";
|
||||
if (status === "returned") return "fail";
|
||||
if (status === "cancelled") return "idle";
|
||||
return "run";
|
||||
}
|
||||
function copyRequirementText(text) {
|
||||
try {
|
||||
if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
|
||||
void navigator.clipboard.writeText(text).then(() => setNotice("已复制:" + text)).catch(() => {
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
function renderRequirementGate(selected) {
|
||||
const views = [
|
||||
{ id: "requirements", label: "需求清单" },
|
||||
{ id: "flow", label: "流转任务" },
|
||||
{ id: "delivery", label: "交付结果" }
|
||||
];
|
||||
const workflowTasks = tasks.filter((task) => task.kind === "workflow" || task.kind === "execution");
|
||||
const deliveryTasks = tasks.filter((task) => task.kind === "workflow" && (task.stage === "delivered" || task.status === "done"));
|
||||
let body;
|
||||
if (reqView === "flow") {
|
||||
body = workflowTasks.length ? (0, import_react.createElement)("div", { className: "review-list req-list" }, workflowTasks.map((task) => (0, import_react.createElement)(
|
||||
"article",
|
||||
{ className: "review-card req-card", key: task.id },
|
||||
(0, import_react.createElement)(
|
||||
"div",
|
||||
{ className: "rc-head" },
|
||||
(0, import_react.createElement)("div", { className: "rc-title" }, task.title),
|
||||
(0, import_react.createElement)("span", { className: "rc-status " + taskTone(task.status) }, (0, import_react.createElement)("i"), taskLabel(task.status))
|
||||
),
|
||||
(0, import_react.createElement)(
|
||||
"div",
|
||||
{ className: "req-meta" },
|
||||
(0, import_react.createElement)("span", null, task.id),
|
||||
(0, import_react.createElement)("span", null, SEATS[task.ownerSeatId] && SEATS[task.ownerSeatId].label || task.ownerSeatId || "—"),
|
||||
(0, import_react.createElement)("span", null, WORKFLOW_STAGE_LABELS[task.stage] || task.stage || "—"),
|
||||
task.requirementId ? (0, import_react.createElement)("span", null, task.requirementId + " v" + task.requirementRevision) : null,
|
||||
task.approvalId ? (0, import_react.createElement)("span", null, task.approvalId) : null
|
||||
),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: task.goal || task.requirement || "", label: "任务说明", empty: "(无任务说明)", max: 110 }),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: task.result || task.note || task.blockedReason || "", label: "当前结果 / 阻塞", empty: "(尚未回报)", max: 110 }),
|
||||
(0, import_react.createElement)("div", { className: "rc-actions" }, (0, import_react.createElement)("span", { className: "spacer" }), (0, import_react.createElement)("button", { type: "button", className: "r-open", onClick: () => setSelectedTask(task) }, "查看详情 →"))
|
||||
))) : (0, import_react.createElement)("p", { className: "empty-note" }, "还没有流转任务。需求发布后会出现在这里。");
|
||||
} else if (reqView === "delivery") {
|
||||
body = deliveryTasks.length ? (0, import_react.createElement)("div", { className: "review-list req-list" }, deliveryTasks.map((task) => {
|
||||
const children = tasks.filter((item) => item.parentTaskId === task.id && item.kind === "execution");
|
||||
return (0, import_react.createElement)(
|
||||
"article",
|
||||
{ className: "review-card req-card", key: task.id },
|
||||
(0, import_react.createElement)("div", { className: "rc-head" }, (0, import_react.createElement)("div", { className: "rc-title" }, task.title), (0, import_react.createElement)("span", { className: "rc-status done" }, (0, import_react.createElement)("i"), "已交付")),
|
||||
(0, import_react.createElement)("div", { className: "req-meta" }, (0, import_react.createElement)("span", null, task.requirementId || "—"), (0, import_react.createElement)("span", null, "v" + (task.requirementRevision || "—")), (0, import_react.createElement)("span", null, task.id)),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: task.deliveryNote || task.summary || "", label: "交付说明", empty: "(暂无交付说明)", max: 110 }),
|
||||
children.length ? (0, import_react.createElement)("div", { className: "req-children" }, children.map((child) => (0, import_react.createElement)(
|
||||
"div",
|
||||
{ className: "req-child", key: child.id },
|
||||
(0, import_react.createElement)("span", { className: "req-child-owner" }, SEATS[child.ownerSeatId] && SEATS[child.ownerSeatId].label || child.ownerSeatId),
|
||||
(0, import_react.createElement)("span", { className: "rc-status " + taskTone(child.status) }, (0, import_react.createElement)("i"), taskLabel(child.status)),
|
||||
(0, import_react.createElement)("span", { className: "req-child-result" }, child.result || child.note || "(暂无结果)"),
|
||||
(0, import_react.createElement)("span", { className: "req-child-session" }, child.resultSessionId ? "结果会话 " + child.resultSessionId : "尚无结果会话")
|
||||
))) : null
|
||||
);
|
||||
})) : (0, import_react.createElement)("p", { className: "empty-note" }, "还没有已交付结果。");
|
||||
} else {
|
||||
body = requirements.length ? (0, import_react.createElement)("div", { className: "review-list req-list" }, requirements.map((req) => (0, import_react.createElement)(
|
||||
"article",
|
||||
{ className: "review-card req-card", key: req.id },
|
||||
(0, import_react.createElement)(
|
||||
"div",
|
||||
{ className: "rc-head" },
|
||||
(0, import_react.createElement)("div", { className: "rc-title" }, req.id + " · " + req.title),
|
||||
(0, import_react.createElement)("span", { className: "rc-status " + reqTone(req.status) }, (0, import_react.createElement)("i"), REQ_STATUS_LABELS[req.status] || req.status)
|
||||
),
|
||||
(0, import_react.createElement)(
|
||||
"div",
|
||||
{ className: "req-meta" },
|
||||
(0, import_react.createElement)("span", null, "v" + req.revision),
|
||||
(0, import_react.createElement)("span", null, "丞相判断:" + (REQ_JUDGEMENT_LABELS[req.judgement] || req.judgement || "—")),
|
||||
(0, import_react.createElement)("span", null, "当前阻塞:" + (req.blockedReason || "—"))
|
||||
),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: req.summary || req.originalText || "", label: "摘要", empty: "(暂无摘要)", max: 110 }),
|
||||
(0, import_react.createElement)(SummaryBlock, { text: req.judgementReason || "", label: "判断理由", empty: "(暂无判断理由)", max: 110 }),
|
||||
(0, import_react.createElement)(
|
||||
"details",
|
||||
{ className: "req-details" },
|
||||
(0, import_react.createElement)("summary", null, "范围、验收与待补信息"),
|
||||
(0, import_react.createElement)(
|
||||
"dl",
|
||||
{ className: "kv" },
|
||||
(0, import_react.createElement)("dt", null, "用户原话"),
|
||||
(0, import_react.createElement)("dd", null, req.originalText || "—"),
|
||||
(0, import_react.createElement)("dt", null, "范围"),
|
||||
(0, import_react.createElement)("dd", null, req.scope || "—"),
|
||||
(0, import_react.createElement)("dt", null, "非目标"),
|
||||
(0, import_react.createElement)("dd", null, req.nonGoals || "—"),
|
||||
(0, import_react.createElement)("dt", null, "验收标准"),
|
||||
(0, import_react.createElement)("dd", null, req.acceptanceCriteria || "—"),
|
||||
(0, import_react.createElement)("dt", null, "风险"),
|
||||
(0, import_react.createElement)("dd", null, req.risks || "—"),
|
||||
(0, import_react.createElement)("dt", null, "依赖"),
|
||||
(0, import_react.createElement)("dd", null, req.dependencies || "—"),
|
||||
(0, import_react.createElement)("dt", null, "待补信息"),
|
||||
(0, import_react.createElement)("dd", null, req.missingInfo || "—")
|
||||
)
|
||||
),
|
||||
(0, import_react.createElement)(
|
||||
"div",
|
||||
{ className: "rc-actions" },
|
||||
(0, import_react.createElement)("button", { type: "button", className: "btn", onClick: () => copyRequirementText(req.id) }, "复制条目编号"),
|
||||
req.status === "ready" ? (0, import_react.createElement)("button", { type: "button", className: "btn", onClick: () => copyRequirementText("发布 " + req.id + " 给中书") }, "复制发布命令") : null,
|
||||
(0, import_react.createElement)("span", { className: "spacer" })
|
||||
)
|
||||
))) : (0, import_react.createElement)("p", { className: "empty-note" }, "还没有需求条目。可以先与丞相讨论,尚未发布的内容不会进入执行流程。");
|
||||
}
|
||||
return (0, import_react.createElement)(
|
||||
"section",
|
||||
{ className: "card req-gate", "aria-label": "丞相需求门控" },
|
||||
(0, import_react.createElement)("h3", null, "需求门控 ", (0, import_react.createElement)("span", { className: "seat-tag" }, selected.name)),
|
||||
(0, import_react.createElement)("p", { className: "foot-note ws-hint" }, "与丞相商讨后,需求会整理到这里。清单条目不会自动执行;在聊天中发送“发布 R-001 给中书”才会立项。"),
|
||||
(0, import_react.createElement)("div", { className: "req-tabs", role: "tablist" }, views.map((view2) => (0, import_react.createElement)("button", {
|
||||
key: view2.id,
|
||||
type: "button",
|
||||
role: "tab",
|
||||
"aria-selected": reqView === view2.id,
|
||||
className: "req-tab" + (reqView === view2.id ? " is-active" : ""),
|
||||
onClick: () => setReqView(view2.id)
|
||||
}, view2.label))),
|
||||
body
|
||||
);
|
||||
}
|
||||
function renderOverview() {
|
||||
const stats = [
|
||||
(0, import_react.createElement)(
|
||||
|
|
@ -1068,12 +1243,12 @@ function WorkbenchV2(props) {
|
|||
),
|
||||
(0, import_react.createElement)("div", { className: "excerpt" }, (0, import_react.createElement)(SummaryBlock, { text: excerpt, label: "最近产出", empty: "(暂无产出)", max: 110 }))
|
||||
);
|
||||
const workspace = (0, import_react.createElement)(
|
||||
const workspace = selected.id === "lead" ? renderRequirementGate(selected) : (0, import_react.createElement)(
|
||||
"section",
|
||||
{ className: "card", "aria-label": "席位工作区" },
|
||||
(0, import_react.createElement)("h3", null, "席位工作区 ", (0, import_react.createElement)("span", { className: "seat-tag" }, selected.name), " ", (0, import_react.createElement)("span", { className: "w-kind" }, seatKind(selected.id))),
|
||||
selected.id === "shangshu" ? (0, import_react.createElement)("div", { className: "ws-actions" }, (0, import_react.createElement)("button", { type: "button", className: "btn primary", disabled: summaryBusy || busy, onClick: summarizeByShangshu }, summaryBusy ? "汇总中…" : "尚书汇总当前任务")) : null,
|
||||
(0, import_react.createElement)("p", { className: "foot-note ws-hint" }, "派工请在聊天中通过 sansheng_dispatch_task 下达;工作台只查看任务与结果。"),
|
||||
(0, import_react.createElement)("p", { className: "foot-note ws-hint" }, "需求请先在聊天中与丞相商讨;明确发布并经用户批准后,由尚书向六部派工;工作台只查看任务与结果。"),
|
||||
selectedTasks.length === 0 ? (0, import_react.createElement)("p", { className: "empty-note" }, "该席位还没有任务记录。") : (0, import_react.createElement)("div", { className: "review-list" }, selectedTasks.slice(0, 3).map((task) => (0, import_react.createElement)(
|
||||
"article",
|
||||
{ className: "review-card", key: task.id },
|
||||
|
|
@ -2288,6 +2463,24 @@ body[data-ds-dark-theme] .ssv2,html[data-theme=dark] .ssv2,.ssv2[data-ssv-theme=
|
|||
.ssv2 .m-rich{margin-top:2px;font-size:13.5px;color:var(--ink-2);max-width:100%;overflow:hidden}
|
||||
.ssv2 .m-rich p{margin:0 0 6px}
|
||||
.ssv2 .m-rich p:last-child{margin-bottom:0}
|
||||
/* ---------- 需求门控工作区 ---------- */
|
||||
.ssv2 .req-gate{padding:18px}
|
||||
.ssv2 .req-gate h3{margin-bottom:6px}
|
||||
.ssv2 .req-tabs{display:flex;gap:6px;margin:12px 0 14px;border-bottom:1px solid var(--panel-line);padding-bottom:2px}
|
||||
.ssv2 .req-tab{border:0;background:transparent;color:var(--muted);font-family:var(--font-ui);font-size:13px;padding:7px 10px;border-radius:6px 6px 0 0;cursor:pointer}
|
||||
.ssv2 .req-tab:hover{background:var(--muted-bg);color:var(--ink)}
|
||||
.ssv2 .req-tab.is-active{color:var(--cobalt);font-weight:700;box-shadow:inset 0 -2px 0 var(--cobalt)}
|
||||
.ssv2 .req-list{gap:10px}
|
||||
.ssv2 .req-card{padding:13px 14px}
|
||||
.ssv2 .req-meta{display:flex;flex-wrap:wrap;gap:8px 14px;margin:6px 0 8px;color:var(--muted);font-family:var(--font-num);font-size:11px}
|
||||
.ssv2 .req-details{margin:8px 0;border-top:1px dashed var(--panel-line);padding-top:8px}
|
||||
.ssv2 .req-details>summary{cursor:pointer;color:var(--ink-2);font-size:12px}
|
||||
.ssv2 .req-details .kv{margin-top:8px}
|
||||
.ssv2 .req-children{display:flex;flex-direction:column;gap:6px;margin-top:10px;border-top:1px dashed var(--panel-line);padding-top:8px}
|
||||
.ssv2 .req-child{display:grid;grid-template-columns:74px auto 1fr;gap:6px 10px;align-items:start;font-size:12px;color:var(--ink-2)}
|
||||
.ssv2 .req-child-owner{font-family:var(--font-seat);font-weight:700;color:var(--ink)}
|
||||
.ssv2 .req-child-result{grid-column:1/-1;color:var(--muted);overflow-wrap:anywhere}
|
||||
.ssv2 .req-child-session{grid-column:1/-1;color:var(--muted);font-family:var(--font-num);font-size:10px;overflow-wrap:anywhere}
|
||||
`;
|
||||
|
||||
// src/native/panel.js
|
||||
|
|
|
|||
|
|
@ -702,4 +702,22 @@ body[data-ds-dark-theme] .ssv2,html[data-theme=dark] .ssv2,.ssv2[data-ssv-theme=
|
|||
.ssv2 .m-rich{margin-top:2px;font-size:13.5px;color:var(--ink-2);max-width:100%;overflow:hidden}
|
||||
.ssv2 .m-rich p{margin:0 0 6px}
|
||||
.ssv2 .m-rich p:last-child{margin-bottom:0}
|
||||
/* ---------- 需求门控工作区 ---------- */
|
||||
.ssv2 .req-gate{padding:18px}
|
||||
.ssv2 .req-gate h3{margin-bottom:6px}
|
||||
.ssv2 .req-tabs{display:flex;gap:6px;margin:12px 0 14px;border-bottom:1px solid var(--panel-line);padding-bottom:2px}
|
||||
.ssv2 .req-tab{border:0;background:transparent;color:var(--muted);font-family:var(--font-ui);font-size:13px;padding:7px 10px;border-radius:6px 6px 0 0;cursor:pointer}
|
||||
.ssv2 .req-tab:hover{background:var(--muted-bg);color:var(--ink)}
|
||||
.ssv2 .req-tab.is-active{color:var(--cobalt);font-weight:700;box-shadow:inset 0 -2px 0 var(--cobalt)}
|
||||
.ssv2 .req-list{gap:10px}
|
||||
.ssv2 .req-card{padding:13px 14px}
|
||||
.ssv2 .req-meta{display:flex;flex-wrap:wrap;gap:8px 14px;margin:6px 0 8px;color:var(--muted);font-family:var(--font-num);font-size:11px}
|
||||
.ssv2 .req-details{margin:8px 0;border-top:1px dashed var(--panel-line);padding-top:8px}
|
||||
.ssv2 .req-details>summary{cursor:pointer;color:var(--ink-2);font-size:12px}
|
||||
.ssv2 .req-details .kv{margin-top:8px}
|
||||
.ssv2 .req-children{display:flex;flex-direction:column;gap:6px;margin-top:10px;border-top:1px dashed var(--panel-line);padding-top:8px}
|
||||
.ssv2 .req-child{display:grid;grid-template-columns:74px auto 1fr;gap:6px 10px;align-items:start;font-size:12px;color:var(--ink-2)}
|
||||
.ssv2 .req-child-owner{font-family:var(--font-seat);font-weight:700;color:var(--ink)}
|
||||
.ssv2 .req-child-result{grid-column:1/-1;color:var(--muted);overflow-wrap:anywhere}
|
||||
.ssv2 .req-child-session{grid-column:1/-1;color:var(--muted);font-family:var(--font-num);font-size:10px;overflow-wrap:anywhere}
|
||||
`;
|
||||
|
|
|
|||
|
|
@ -25,6 +25,9 @@ const TASK_LABELS = {
|
|||
done: '已完成',
|
||||
cancelled: '已取消',
|
||||
failed: '失败',
|
||||
waiting_user: '待用户批准',
|
||||
returned: '已退回',
|
||||
reconfirm: '待重新确认',
|
||||
}
|
||||
const TASK_TONES = {
|
||||
draft: 'idle',
|
||||
|
|
@ -34,8 +37,34 @@ const TASK_TONES = {
|
|||
done: 'done',
|
||||
cancelled: 'idle',
|
||||
failed: 'fail',
|
||||
waiting_user: 'review',
|
||||
returned: 'fail',
|
||||
reconfirm: 'fail',
|
||||
}
|
||||
const OPEN_STATUS = new Set(['dispatched', 'running', 'prepared'])
|
||||
const REQ_STATUS_LABELS = {
|
||||
discussing: '商讨中',
|
||||
ready: '待发布',
|
||||
published: '已发布',
|
||||
returned: '已退回',
|
||||
cancelled: '已取消',
|
||||
}
|
||||
const REQ_JUDGEMENT_LABELS = {
|
||||
can_do: '可立项',
|
||||
needs_discussion: '需商讨',
|
||||
not_now: '暂不可做',
|
||||
}
|
||||
const WORKFLOW_STAGE_LABELS = {
|
||||
zhongshu_draft: '中书拟案',
|
||||
menxia_review: '门下审核',
|
||||
awaiting_execution_approval: '待用户批准',
|
||||
shangshu_dispatch: '尚书调度',
|
||||
department_exec: '六部执行',
|
||||
menxia_acceptance: '门下验收',
|
||||
lead_delivery: '丞相交付',
|
||||
delivered: '已交付',
|
||||
reconfirm: '待重新确认',
|
||||
}
|
||||
|
||||
function toneOfSeat(seat) {
|
||||
if (!seat) return 'idle'
|
||||
|
|
@ -237,6 +266,9 @@ export function WorkbenchV2(props) {
|
|||
const [memory, setMemory] = useState(null)
|
||||
const [memoryDraft, setMemoryDraft] = useState({ goal: '', constraints: '', acceptance: '', decisions: '' })
|
||||
const [tasks, setTasks] = useState([])
|
||||
const [requirements, setRequirements] = useState([])
|
||||
const [approvals, setApprovals] = useState([])
|
||||
const [reqView, setReqView] = useState('requirements')
|
||||
const [artifacts, setArtifacts] = useState([])
|
||||
const [artifactDraft, setArtifactDraft] = useState({ title: '', path: '', summary: '' })
|
||||
const [artifactFormOpen, setArtifactFormOpen] = useState(false)
|
||||
|
|
@ -264,14 +296,19 @@ export function WorkbenchV2(props) {
|
|||
try { memoryData = (await request('memory', { projectId: projectView.project.id })).memory } catch { /* 项目共识尚未建立 */ }
|
||||
let taskList = []
|
||||
let artifactList = []
|
||||
let requirementData = { requirements: [], approvals: [] }
|
||||
try { taskList = (await request('tasks', { projectId: projectView.project.id })).tasks ?? [] } catch (taskError) {
|
||||
console.warn('[sansheng] 任务加载失败:', taskError && taskError.message ? taskError.message : taskError)
|
||||
}
|
||||
try { requirementData = await request('requirements', { projectId: projectView.project.id }) } catch { /* 兼容旧宿主无需求清单 */ }
|
||||
try { artifactList = (await request('artifacts', { projectId: projectView.project.id })).artifacts ?? [] } catch { /* 暂无成果 */ }
|
||||
if (!alive.current) return
|
||||
setView(projectView); setModels(modelCatalog); setMemory(memoryData)
|
||||
setMemoryDraft({ goal: memoryData?.goal ?? '', constraints: (memoryData?.constraints ?? []).join('\n'), acceptance: (memoryData?.acceptance ?? []).join('\n'), decisions: '' })
|
||||
setTasks(taskList); setArtifacts(artifactList); setPhase('ready')
|
||||
setTasks(taskList); setArtifacts(artifactList)
|
||||
setRequirements(Array.isArray(requirementData.requirements) ? requirementData.requirements : [])
|
||||
setApprovals(Array.isArray(requirementData.approvals) ? requirementData.approvals : [])
|
||||
setPhase('ready')
|
||||
} catch (loadError) {
|
||||
if (!alive.current) return
|
||||
setError(loadError && loadError.message ? loadError.message : '加载失败')
|
||||
|
|
@ -295,16 +332,19 @@ export function WorkbenchV2(props) {
|
|||
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
|
||||
running = true
|
||||
try {
|
||||
const [projectView, taskRes, artifactRes] = await Promise.all([
|
||||
const [projectView, taskRes, artifactRes, requirementData] = await Promise.all([
|
||||
request('project', { projectId }),
|
||||
request('tasks', { projectId }),
|
||||
request('artifacts', { projectId }),
|
||||
request('requirements', { projectId }).catch(() => ({ requirements: [], approvals: [] })),
|
||||
])
|
||||
if (disposed || !alive.current) return
|
||||
setView(projectView)
|
||||
const nextTasks = taskRes && Array.isArray(taskRes.tasks) ? taskRes.tasks : []
|
||||
setTasks(nextTasks)
|
||||
setArtifacts(artifactRes && Array.isArray(artifactRes.artifacts) ? artifactRes.artifacts : [])
|
||||
setRequirements(Array.isArray(requirementData?.requirements) ? requirementData.requirements : [])
|
||||
setApprovals(Array.isArray(requirementData?.approvals) ? requirementData.approvals : [])
|
||||
setSelectedTask(previous => previous ? (nextTasks.find(task => task.id === previous.id) || previous) : previous)
|
||||
} catch { /* 轮询失败保留上一份真实数据,不弹错误打断编辑 */ } finally {
|
||||
running = false
|
||||
|
|
@ -577,6 +617,112 @@ export function WorkbenchV2(props) {
|
|||
)
|
||||
}
|
||||
|
||||
function reqTone(status) {
|
||||
if (status === 'ready' || status === 'published') return 'review'
|
||||
if (status === 'returned') return 'fail'
|
||||
if (status === 'cancelled') return 'idle'
|
||||
return 'run'
|
||||
}
|
||||
|
||||
function copyRequirementText(text) {
|
||||
try {
|
||||
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
||||
void navigator.clipboard.writeText(text).then(() => setNotice('已复制:' + text)).catch(() => {})
|
||||
}
|
||||
} catch { /* 剪贴板不可用时保留可手动选择文本 */ }
|
||||
}
|
||||
|
||||
function renderRequirementGate(selected) {
|
||||
const views = [
|
||||
{ id: 'requirements', label: '需求清单' },
|
||||
{ id: 'flow', label: '流转任务' },
|
||||
{ id: 'delivery', label: '交付结果' },
|
||||
]
|
||||
const workflowTasks = tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution')
|
||||
const deliveryTasks = tasks.filter(task => task.kind === 'workflow' && (task.stage === 'delivered' || task.status === 'done'))
|
||||
let body
|
||||
if (reqView === 'flow') {
|
||||
body = workflowTasks.length
|
||||
? h('div', { className: 'review-list req-list' }, workflowTasks.map(task => h('article', { className: 'review-card req-card', key: task.id },
|
||||
h('div', { className: 'rc-head' },
|
||||
h('div', { className: 'rc-title' }, task.title),
|
||||
h('span', { className: 'rc-status ' + taskTone(task.status) }, h('i'), taskLabel(task.status)),
|
||||
),
|
||||
h('div', { className: 'req-meta' },
|
||||
h('span', null, task.id),
|
||||
h('span', null, (SEATS[task.ownerSeatId] && SEATS[task.ownerSeatId].label) || task.ownerSeatId || '—'),
|
||||
h('span', null, WORKFLOW_STAGE_LABELS[task.stage] || task.stage || '—'),
|
||||
task.requirementId ? h('span', null, task.requirementId + ' v' + task.requirementRevision) : null,
|
||||
task.approvalId ? h('span', null, task.approvalId) : null,
|
||||
),
|
||||
h(SummaryBlock, { text: task.goal || task.requirement || '', label: '任务说明', empty: '(无任务说明)', max: 110 }),
|
||||
h(SummaryBlock, { text: task.result || task.note || task.blockedReason || '', label: '当前结果 / 阻塞', empty: '(尚未回报)', max: 110 }),
|
||||
h('div', { className: 'rc-actions' }, h('span', { className: 'spacer' }), h('button', { type: 'button', className: 'r-open', onClick: () => setSelectedTask(task) }, '查看详情 →')),
|
||||
)))
|
||||
: h('p', { className: 'empty-note' }, '还没有流转任务。需求发布后会出现在这里。')
|
||||
} else if (reqView === 'delivery') {
|
||||
body = deliveryTasks.length
|
||||
? h('div', { className: 'review-list req-list' }, deliveryTasks.map(task => {
|
||||
const children = tasks.filter(item => item.parentTaskId === task.id && item.kind === 'execution')
|
||||
return h('article', { className: 'review-card req-card', key: task.id },
|
||||
h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, task.title), h('span', { className: 'rc-status done' }, h('i'), '已交付')),
|
||||
h('div', { className: 'req-meta' }, h('span', null, task.requirementId || '—'), h('span', null, 'v' + (task.requirementRevision || '—')), h('span', null, task.id)),
|
||||
h(SummaryBlock, { text: task.deliveryNote || task.summary || '', label: '交付说明', empty: '(暂无交付说明)', max: 110 }),
|
||||
children.length ? h('div', { className: 'req-children' }, children.map(child => h('div', { className: 'req-child', key: child.id },
|
||||
h('span', { className: 'req-child-owner' }, (SEATS[child.ownerSeatId] && SEATS[child.ownerSeatId].label) || child.ownerSeatId),
|
||||
h('span', { className: 'rc-status ' + taskTone(child.status) }, h('i'), taskLabel(child.status)),
|
||||
h('span', { className: 'req-child-result' }, child.result || child.note || '(暂无结果)'),
|
||||
h('span', { className: 'req-child-session' }, child.resultSessionId ? '结果会话 ' + child.resultSessionId : '尚无结果会话'),
|
||||
))) : null,
|
||||
)
|
||||
}))
|
||||
: h('p', { className: 'empty-note' }, '还没有已交付结果。')
|
||||
} else {
|
||||
body = requirements.length
|
||||
? h('div', { className: 'review-list req-list' }, requirements.map(req => h('article', { className: 'review-card req-card', key: req.id },
|
||||
h('div', { className: 'rc-head' },
|
||||
h('div', { className: 'rc-title' }, req.id + ' · ' + req.title),
|
||||
h('span', { className: 'rc-status ' + reqTone(req.status) }, h('i'), REQ_STATUS_LABELS[req.status] || req.status),
|
||||
),
|
||||
h('div', { className: 'req-meta' },
|
||||
h('span', null, 'v' + req.revision),
|
||||
h('span', null, '丞相判断:' + (REQ_JUDGEMENT_LABELS[req.judgement] || req.judgement || '—')),
|
||||
h('span', null, '当前阻塞:' + (req.blockedReason || '—')),
|
||||
),
|
||||
h(SummaryBlock, { text: req.summary || req.originalText || '', label: '摘要', empty: '(暂无摘要)', max: 110 }),
|
||||
h(SummaryBlock, { text: req.judgementReason || '', label: '判断理由', empty: '(暂无判断理由)', max: 110 }),
|
||||
h('details', { className: 'req-details' },
|
||||
h('summary', null, '范围、验收与待补信息'),
|
||||
h('dl', { className: 'kv' },
|
||||
h('dt', null, '用户原话'), h('dd', null, req.originalText || '—'),
|
||||
h('dt', null, '范围'), h('dd', null, req.scope || '—'),
|
||||
h('dt', null, '非目标'), h('dd', null, req.nonGoals || '—'),
|
||||
h('dt', null, '验收标准'), h('dd', null, req.acceptanceCriteria || '—'),
|
||||
h('dt', null, '风险'), h('dd', null, req.risks || '—'),
|
||||
h('dt', null, '依赖'), h('dd', null, req.dependencies || '—'),
|
||||
h('dt', null, '待补信息'), h('dd', null, req.missingInfo || '—'),
|
||||
),
|
||||
),
|
||||
h('div', { className: 'rc-actions' },
|
||||
h('button', { type: 'button', className: 'btn', onClick: () => copyRequirementText(req.id) }, '复制条目编号'),
|
||||
req.status === 'ready' ? h('button', { type: 'button', className: 'btn', onClick: () => copyRequirementText('发布 ' + req.id + ' 给中书') }, '复制发布命令') : null,
|
||||
h('span', { className: 'spacer' }),
|
||||
),
|
||||
)))
|
||||
: h('p', { className: 'empty-note' }, '还没有需求条目。可以先与丞相讨论,尚未发布的内容不会进入执行流程。')
|
||||
}
|
||||
return h('section', { className: 'card req-gate', 'aria-label': '丞相需求门控' },
|
||||
h('h3', null, '需求门控 ', h('span', { className: 'seat-tag' }, selected.name)),
|
||||
h('p', { className: 'foot-note ws-hint' }, '与丞相商讨后,需求会整理到这里。清单条目不会自动执行;在聊天中发送“发布 R-001 给中书”才会立项。'),
|
||||
h('div', { className: 'req-tabs', role: 'tablist' }, views.map(view => h('button', {
|
||||
key: view.id, type: 'button', role: 'tab', 'aria-selected': reqView === view.id,
|
||||
className: 'req-tab' + (reqView === view.id ? ' is-active' : ''),
|
||||
onClick: () => setReqView(view.id),
|
||||
}, view.label))),
|
||||
body,
|
||||
)
|
||||
}
|
||||
|
||||
function renderOverview() {
|
||||
const stats = [
|
||||
h('button', { type: 'button', className: 'stat stat-link', key: 'cost', onClick: () => setTokenPanelOpen(true) },
|
||||
|
|
@ -623,23 +769,25 @@ export function WorkbenchV2(props) {
|
|||
h('div', { className: 'excerpt' }, h(SummaryBlock, { text: excerpt, label: '最近产出', empty: '(暂无产出)', max: 110 })),
|
||||
)
|
||||
|
||||
const workspace = h('section', { className: 'card', 'aria-label': '席位工作区' },
|
||||
h('h3', null, '席位工作区 ', h('span', { className: 'seat-tag' }, selected.name), ' ', h('span', { className: 'w-kind' }, seatKind(selected.id))),
|
||||
selected.id === 'shangshu'
|
||||
? h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', disabled: summaryBusy || busy, onClick: summarizeByShangshu }, summaryBusy ? '汇总中…' : '尚书汇总当前任务'))
|
||||
: null,
|
||||
h('p', { className: 'foot-note ws-hint' }, '派工请在聊天中通过 sansheng_dispatch_task 下达;工作台只查看任务与结果。'),
|
||||
selectedTasks.length === 0
|
||||
? h('p', { className: 'empty-note' }, '该席位还没有任务记录。')
|
||||
: h('div', { className: 'review-list' }, selectedTasks.slice(0, 3).map(task => h('article', { className: 'review-card', key: task.id },
|
||||
h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, task.title), h('span', { className: 'rc-status ' + taskTone(task.status) }, h('i'), taskLabel(task.status))),
|
||||
h(SummaryBlock, { text: task.goal || task.requirement || '', label: '任务说明', empty: '(无任务说明)', max: 110 }),
|
||||
h(SummaryBlock, { text: task.result || taskLabel(task.status), label: '任务完成情况', empty: '(暂无结果)', max: 110 }),
|
||||
h('div', { className: 'rc-actions' }, h('span', { className: 'spacer' }),
|
||||
h('button', { type: 'button', className: 'r-open', onClick: () => setSelectedTask(task) }, '查看详情 →'),
|
||||
),
|
||||
))),
|
||||
)
|
||||
const workspace = selected.id === 'lead'
|
||||
? renderRequirementGate(selected)
|
||||
: h('section', { className: 'card', 'aria-label': '席位工作区' },
|
||||
h('h3', null, '席位工作区 ', h('span', { className: 'seat-tag' }, selected.name), ' ', h('span', { className: 'w-kind' }, seatKind(selected.id))),
|
||||
selected.id === 'shangshu'
|
||||
? h('div', { className: 'ws-actions' }, h('button', { type: 'button', className: 'btn primary', disabled: summaryBusy || busy, onClick: summarizeByShangshu }, summaryBusy ? '汇总中…' : '尚书汇总当前任务'))
|
||||
: null,
|
||||
h('p', { className: 'foot-note ws-hint' }, '需求请先在聊天中与丞相商讨;明确发布并经用户批准后,由尚书向六部派工;工作台只查看任务与结果。'),
|
||||
selectedTasks.length === 0
|
||||
? h('p', { className: 'empty-note' }, '该席位还没有任务记录。')
|
||||
: h('div', { className: 'review-list' }, selectedTasks.slice(0, 3).map(task => h('article', { className: 'review-card', key: task.id },
|
||||
h('div', { className: 'rc-head' }, h('div', { className: 'rc-title' }, task.title), h('span', { className: 'rc-status ' + taskTone(task.status) }, h('i'), taskLabel(task.status))),
|
||||
h(SummaryBlock, { text: task.goal || task.requirement || '', label: '任务说明', empty: '(无任务说明)', max: 110 }),
|
||||
h(SummaryBlock, { text: task.result || taskLabel(task.status), label: '任务完成情况', empty: '(暂无结果)', max: 110 }),
|
||||
h('div', { className: 'rc-actions' }, h('span', { className: 'spacer' }),
|
||||
h('button', { type: 'button', className: 'r-open', onClick: () => setSelectedTask(task) }, '查看详情 →'),
|
||||
),
|
||||
))),
|
||||
)
|
||||
|
||||
const modelChoices = []
|
||||
const seenModels = new Set()
|
||||
|
|
|
|||
|
|
@ -66,10 +66,8 @@ export function createApiHandler(service) {
|
|||
return { ok: true, value: await service.taskSummary(requireProjectId(payload)) }
|
||||
case 'shangshuSummary':
|
||||
return { ok: true, value: await service.shangshuSummary(requireProjectId(payload)) }
|
||||
case 'taskCreate':
|
||||
return { ok: true, value: await service.taskCreate(requireProjectId(payload), payload ?? {}) }
|
||||
case 'taskDispatch':
|
||||
return { ok: true, value: await service.taskDispatch(requireProjectId(payload), requireTaskId(payload)) }
|
||||
case 'requirements':
|
||||
return { ok: true, value: await service.requirements(requireProjectId(payload)) }
|
||||
case 'taskCancel':
|
||||
return { ok: true, value: await service.taskCancel(requireProjectId(payload), requireTaskId(payload)) }
|
||||
case 'artifacts':
|
||||
|
|
|
|||
|
|
@ -15,18 +15,24 @@ export function renderSeatPrompt({ project, seatId, seat }) {
|
|||
if (seatId === 'lead') {
|
||||
lines.push(
|
||||
'',
|
||||
'派工硬性规则:你必须使用 sansheng_dispatch_task 工具把任务派给目标部门已绑定的真实会话,并把用户原话和最新项目共识一起带上;禁止用同名子代理、普通 agent、自己代写、页面“派工成功”或口头通知来冒充部门执行。工具返回 ok:false / delivered:false 时必须明确告诉用户投递失败,不能降级、不能声称已完成。',
|
||||
'需求门控硬性规则:你是丞相,负责需求澄清、合理性初审、清单整理、流程协调和最终交付。所有用户输入默认仅用于商讨,不构成执行授权。你必须使用 sansheng_requirement_upsert 整理需求清单并等待用户明确发布;列入清单不等于创建任务,也不得自动派工。',
|
||||
'只有用户明确说出「发布 R-001 给中书」这类发布意图时,才可调用 sansheng_requirement_publish,且只能发布给中书省。你严禁直接向六部派工;sansheng_dispatch_task 已停用,任何直接派工都会被系统拒绝且无副作用。',
|
||||
'中书拟案和门下审核后,你只能向用户展示方案、影响范围、风险和验收方式,并等待用户明确说「批准执行 R-001」;只有那时才可调用 sansheng_requirement_approve。你不得代替用户确认,不得代替三省六部伪造或填写执行结果。',
|
||||
'需求改口、扩大范围或增加要求时,必须用 sansheng_requirement_upsert 更新原需求(revision 自动增加);旧发布命令和旧批准立即失效,旧任务会停止推进并等待重新确认。',
|
||||
)
|
||||
} else {
|
||||
lines.push(
|
||||
'',
|
||||
'回报硬性规则:你必须使用 sansheng_task_report 工具回报真实状态(running 执行中、done 完成、failed 失败);done 必须附真实结果(文件路径、输出或验证结果),不得虚报。丞相不能代替部门报告。',
|
||||
)
|
||||
if (seatId === 'shangshu') {
|
||||
lines.push(
|
||||
'',
|
||||
'统筹汇总规则:丞相可以直接向六部派工,你不需要拦截或重新分配;当用户或丞相要求汇总时,请用 sansheng_task_list / sansheng_task_result 读取本项目真实任务与结果,按状态汇总,并明确区分「已派工/已收到」和「已完成」。',
|
||||
)
|
||||
if (seatId === 'zhongshu') {
|
||||
lines.push('中书流程规则:收到丞相发布的需求后,只读调查并完成拟案,使用 sansheng_workflow_submit 提交门下审核。拟案阶段不得修改工程、不得向六部派工、不得跳过门下。')
|
||||
} else if (seatId === 'menxia') {
|
||||
lines.push('门下流程规则:使用 sansheng_workflow_review 审核中书拟案,通过后交丞相等待用户明确批准;退回则写清原因交回中书。后续用 sansheng_workflow_accept 验收尚书汇总。你不得直接向六部派工。')
|
||||
} else if (seatId === 'shangshu') {
|
||||
lines.push('尚书流程规则:只有用户已明确批准执行、批准版本与当前需求 revision 一致时,才可使用 sansheng_workflow_dispatch 把获批任务分派给六部;只能派六部,不能给中书、门下或丞相。所有六部任务结束后用 sansheng_workflow_summarize 汇总真实结果并交门下验收。不得把已派工当成已完成。')
|
||||
} else if (['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'].includes(seatId)) {
|
||||
lines.push('六部执行规则:你只能执行尚书分派且已获用户批准的执行任务;不得跨部门改派、不得自行扩大范围。任务完成后必须通过 sansheng_task_report 回报真实文件和验证结果。')
|
||||
}
|
||||
}
|
||||
lines.push('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { randomUUID, createHash } from 'node:crypto'
|
||||
import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
import { emptyTask, emptyArtifact } from '../shared/schema.js'
|
||||
import { emptyTask, emptyArtifact, emptyRequirement } from '../shared/schema.js'
|
||||
import { mergeProjectMemory, normalizeProjectMemory, renderProjectMemory } from '../shared/project-memory.js'
|
||||
import { applyModel, normalizeSelection } from './model.js'
|
||||
|
||||
|
|
@ -43,6 +43,104 @@ export function projectView(project) {
|
|||
}
|
||||
}
|
||||
|
||||
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] : []
|
||||
|
|
@ -332,7 +430,7 @@ export class SanshengService {
|
|||
'汇总要求:',
|
||||
'1. 按已完成 / 执行中 / 已派工 / 待执行 / 失败或取消分组汇总,列出任务 ID、主责部门、当前状态和关键结果。',
|
||||
'2. 明确区分「已派工/已收到」和「已完成」,不要把已派工当成完成。',
|
||||
'3. 只做汇总,不重派任务,不拦截丞相直接派工;指出仍未完成或需要复核的事项。',
|
||||
'3. 只做汇总,不重派任务;按需求门控流程报告真实阻塞、完成与待复核事项。',
|
||||
].join('\n')
|
||||
const requestId = randomUUID()
|
||||
try {
|
||||
|
|
@ -348,6 +446,443 @@ export class SanshengService {
|
|||
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} 不存在`)
|
||||
|
|
@ -359,7 +894,15 @@ export class SanshengService {
|
|||
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 })
|
||||
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()
|
||||
|
|
@ -395,6 +938,7 @@ export class SanshengService {
|
|||
`【任务】${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()
|
||||
|
|
@ -419,7 +963,7 @@ export class SanshengService {
|
|||
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 = delivered ? 'dispatched' : 'prepared'
|
||||
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()
|
||||
|
|
@ -455,11 +999,21 @@ export class SanshengService {
|
|||
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 task = s.projects[projectId].tasks.find(item => item.id === taskId)
|
||||
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'
|
||||
|
|
|
|||
|
|
@ -27,8 +27,12 @@ function normalizeProjects(state) {
|
|||
}
|
||||
if (!Array.isArray(project.tasks)) project.tasks = []
|
||||
if (!Array.isArray(project.artifacts)) project.artifacts = []
|
||||
if (!Array.isArray(project.requirements)) project.requirements = []
|
||||
if (!Array.isArray(project.approvals)) project.approvals = []
|
||||
if (!Number.isFinite(project.taskSeq)) project.taskSeq = 0
|
||||
if (!Number.isFinite(project.artifactSeq)) project.artifactSeq = 0
|
||||
if (!Number.isFinite(project.requirementSeq)) project.requirementSeq = 0
|
||||
if (!Number.isFinite(project.approvalSeq)) project.approvalSeq = 0
|
||||
project.memory = normalizeProjectMemory(project.memory, project.id)
|
||||
}
|
||||
return state
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
// 十席会话专用工具:把“部门”落到已绑定的真实 session,而不是同名普通子代理。
|
||||
import { SEAT_IDS, SEATS } from '../shared/roles.js'
|
||||
import { SEAT_IDS, SEATS, SEAT_GROUPS } from '../shared/roles.js'
|
||||
|
||||
function text(value) {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
|
|
@ -51,114 +51,307 @@ const seatToolOutput = {
|
|||
},
|
||||
}
|
||||
|
||||
function lastUserCommand(exec) {
|
||||
try {
|
||||
const messages = exec?.agent?.session?.deriveMessages?.() ?? []
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
const message = messages[i]
|
||||
if (!message || message.role !== 'user') continue
|
||||
if (typeof message.content === 'string') return message.content.trim()
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content
|
||||
.filter(block => block && block.type === 'text' && typeof block.text === 'string')
|
||||
.map(block => block.text)
|
||||
.join('\n')
|
||||
.trim()
|
||||
}
|
||||
return ''
|
||||
}
|
||||
} catch {}
|
||||
return ''
|
||||
}
|
||||
|
||||
function failure(error, extra = {}) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: error?.code ?? 'error',
|
||||
error: error?.message ?? String(error),
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
function actorOf(located) {
|
||||
return { seatId: located.seatId, sessionId: located.sessionId }
|
||||
}
|
||||
|
||||
function seatToolDefinitions({ store, service }) {
|
||||
const definitions = []
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_dispatch_task',
|
||||
description: '丞相专用:把任务正式派给当前项目已绑定的部门会话(工部/吏部等),使用该部门原有会话和模型。禁止用同名子代理、普通 agent 或自己代写来冒充部门。派工前会把用户原话与最新项目共识写入共识,并把共识和原话一起投递。',
|
||||
name: 'sansheng_requirement_upsert',
|
||||
description: '丞相专用:把与用户商讨出的需求整理进需求清单。新增或更新同一个需求条目都不会创建任务、不会派工;只有用户明确发布后才会进入中书省。条目包含判断、范围、非目标、验收标准、风险/依赖/待补信息。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
targetSeatId: { type: 'string', description: '目标部门 id,例如 gongbu(工部)、libu(吏部)' },
|
||||
title: { type: 'string', description: '任务标题' },
|
||||
goal: { type: 'string', description: '任务说明/验收目标' },
|
||||
requirement: { type: 'string', description: '用户对部门提出的具体要求(尽量保留原话)' },
|
||||
sourceText: { type: 'string', description: '用户原话或讨论原文,用于写入项目共识来源' },
|
||||
id: { type: 'string', description: '已有需求 id(如 R-001);省略表示新建' },
|
||||
expectedRevision: { type: 'number', description: '更新时必填:当前 revision,用于防止并发覆盖' },
|
||||
title: { type: 'string', description: '需求标题' },
|
||||
summary: { type: 'string', description: '一句话摘要' },
|
||||
originalText: { type: 'string', description: '用户原始要求,尽量保留原话' },
|
||||
judgement: { type: 'string', enum: ['can_do', 'needs_discussion', 'not_now'], description: '丞相判断:可立项 / 需商讨 / 暂不可做' },
|
||||
judgementReason: { type: 'string', description: '判断理由' },
|
||||
scope: { type: 'string', description: '范围(可发布必填)' },
|
||||
nonGoals: { type: 'string', description: '非目标' },
|
||||
acceptanceCriteria: { type: 'string', description: '验收标准(可发布必填)' },
|
||||
risks: { type: 'string', description: '风险' },
|
||||
dependencies: { type: 'string', description: '依赖' },
|
||||
missingInfo: { type: 'string', description: '待补信息' },
|
||||
},
|
||||
required: ['targetSeatId', 'title'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
// 区分三种失败:本席工具未就绪 / 目标部门未开启 / 任务投递失败;成功才回 ok:true。
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以整理需求清单' }
|
||||
try {
|
||||
located = await locateSeat(service, exec)
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
delivered: false,
|
||||
reason: 'tool-not-ready',
|
||||
error: `本席派工工具未就绪:${error?.message ?? error}`,
|
||||
hint: '当前会话没有有效的席位绑定,不能派工;请从已绑定的丞相会话发起。',
|
||||
}
|
||||
}
|
||||
const { project, seatId } = located
|
||||
if (seatId !== 'lead') throw new Error('只有丞相可以派工,部门不能自行派工')
|
||||
const result = await service.requirementUpsert(located.project.id, args, actorOf(located))
|
||||
return { ok: true, ...result }
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_requirement_list',
|
||||
description: '查看当前项目真实需求清单、版本、状态、阻塞原因和对应流程任务。需求清单不是执行任务,列入清单不等于已派工。',
|
||||
parameters: { type: 'object', properties: {} },
|
||||
async execute(_args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
const data = await service.requirements(located.project.id)
|
||||
const tasks = (await service.tasks(located.project.id)).tasks.filter(task => task.kind === 'workflow' || task.kind === 'execution')
|
||||
return { ok: true, projectId: located.project.id, ...data, tasks }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_requirement_publish',
|
||||
description: '丞相专用:只有在用户明确发送「发布 R-001 给中书」后才可发布需求。发布只创建丞相根任务并投递中书省拟案,不代表批准施工;不能直接投递尚书省或六部。命令由宿主从当前会话最后一条用户消息独立校验。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
requirementId: { type: 'string', description: '需求 id,如 R-001' },
|
||||
expectedRevision: { type: 'number', description: '要发布的最新 revision' },
|
||||
targetSeatId: { type: 'string', enum: ['zhongshu'], description: '只能发布给中书省' },
|
||||
},
|
||||
required: ['requirementId', 'expectedRevision', 'targetSeatId'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以发布需求' }
|
||||
const targetSeatId = text(args.targetSeatId)
|
||||
if (!SEAT_IDS.includes(targetSeatId) || targetSeatId === 'lead') throw new Error('目标必须是丞相以外的十席部门')
|
||||
const title = text(args.title)
|
||||
if (!title) throw new Error('任务标题不能为空')
|
||||
const goal = text(args.goal)
|
||||
const requirement = text(args.requirement)
|
||||
const sourceText = text(args.sourceText)
|
||||
const source = sourceText || requirement || title
|
||||
// 先写共识:派工必须带最新共识和用户原话,不能只发一句“让工部做”。
|
||||
if (requirement || sourceText) {
|
||||
await service.memoryUpdate(project.id, {
|
||||
decisions: [{ type: 'user', status: 'active', text: sourceText || requirement }],
|
||||
sources: [{ type: 'user', excerpt: source, at: Date.now() }],
|
||||
})
|
||||
if (targetSeatId !== 'zhongshu') {
|
||||
return { ok: false, reason: 'workflow-route-forbidden', error: `丞相只能把需求发布给中书省,不能直接派给「${labelOf(targetSeatId) || targetSeatId}」。未创建任务、未写入共识、未投递任何会话。` }
|
||||
}
|
||||
const created = await service.taskCreate(project.id, {
|
||||
title,
|
||||
goal,
|
||||
requirement,
|
||||
ownerSeatId: targetSeatId,
|
||||
})
|
||||
let dispatched
|
||||
try {
|
||||
dispatched = await service.taskDispatch(project.id, created.task.id, { force: true })
|
||||
} catch (error) {
|
||||
const code = String(error?.code ?? '')
|
||||
const message = String(error?.message ?? error)
|
||||
if (code === 'sansheng/seat-unbound' || /会话还没开启|seat-unbound|未开启/.test(message)) {
|
||||
return {
|
||||
ok: false,
|
||||
delivered: false,
|
||||
reason: 'target-seat-unavailable',
|
||||
taskId: created.task.id,
|
||||
targetLabel: labelOf(targetSeatId),
|
||||
error: `目标部门「${labelOf(targetSeatId)}」未开启,无法派工:${message}`,
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
delivered: false,
|
||||
reason: 'delivery-failed',
|
||||
taskId: created.task.id,
|
||||
targetLabel: labelOf(targetSeatId),
|
||||
error: `任务投递失败:${message}`,
|
||||
}
|
||||
}
|
||||
const result = okTask(dispatched.task)
|
||||
if (!dispatched.delivered) {
|
||||
return {
|
||||
...result,
|
||||
ok: false,
|
||||
delivered: false,
|
||||
reason: 'delivery-failed',
|
||||
taskId: created.task.id,
|
||||
targetLabel: labelOf(targetSeatId),
|
||||
error: dispatched.task.note || '任务投递失败,未送达部门会话',
|
||||
}
|
||||
}
|
||||
const result = await service.requirementPublish(located.project.id, text(args.requirementId), {
|
||||
expectedRevision: args.expectedRevision,
|
||||
command: lastUserCommand(exec),
|
||||
}, actorOf(located))
|
||||
return result
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_requirement_approve',
|
||||
description: '丞相专用:门下审核通过后向用户展示方案并等待用户明确「批准执行 R-001」。只有检测到最后一条用户消息明确批准时,宿主才生成批准凭证并把任务交给尚书省调度;否则保持等待用户。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
requirementId: { type: 'string', description: '需求 id,如 R-001' },
|
||||
expectedRevision: { type: 'number', description: '当前需求 revision' },
|
||||
},
|
||||
required: ['requirementId', 'expectedRevision'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
if (located.seatId !== 'lead') return { ok: false, reason: 'forbidden', error: '只有丞相可以提交用户批准' }
|
||||
try {
|
||||
return await service.requirementApprove(located.project.id, text(args.requirementId), {
|
||||
expectedRevision: args.expectedRevision,
|
||||
command: lastUserCommand(exec),
|
||||
}, actorOf(located))
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_workflow_submit',
|
||||
description: '中书省专用:把拟案提交门下省审核。拟案阶段只能只读调查,不能修改工程、不能向六部派工。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
taskId: { type: 'string', description: '流程任务 id' },
|
||||
draft: { type: 'string', description: '完整拟案:目标、范围、非目标、验收标准、风险、执行步骤' },
|
||||
},
|
||||
required: ['taskId', 'draft'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
try {
|
||||
return await service.workflowSubmitDraft(located.project.id, text(args.taskId), { draft: text(args.draft) }, actorOf(located))
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_workflow_review',
|
||||
description: '门下省专用:审核中书拟案。approve 通过后交丞相等待用户明确批准执行;return 退回中书修订。不得直接向六部派工。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
taskId: { type: 'string', description: '流程任务 id' },
|
||||
action: { type: 'string', enum: ['approve', 'return'], description: '通过或退回' },
|
||||
note: { type: 'string', description: '审核意见;退回必填' },
|
||||
},
|
||||
required: ['taskId', 'action'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
try {
|
||||
return await service.workflowReview(located.project.id, text(args.taskId), { action: text(args.action), note: text(args.note) }, actorOf(located))
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_workflow_dispatch',
|
||||
description: '尚书省专用:仅当用户已明确批准执行、且批准版本与需求当前版本一致时,才可把获批任务分派给六部。只能分派给六部(吏/户/礼/兵/刑/工),不能给中书、门下或丞相。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
taskId: { type: 'string', description: '流程任务 id' },
|
||||
assignments: {
|
||||
type: 'array',
|
||||
description: '六部任务列表',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
seatId: { type: 'string', enum: ['libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu'] },
|
||||
title: { type: 'string', description: '任务标题' },
|
||||
goal: { type: 'string', description: '任务说明/验收目标' },
|
||||
},
|
||||
required: ['seatId', 'title'],
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['taskId', 'assignments'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
try {
|
||||
return await service.workflowDispatch(located.project.id, text(args.taskId), { assignments: args.assignments }, actorOf(located))
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_workflow_summarize',
|
||||
description: '尚书省专用:所有六部执行任务结束后,汇总真实结果并提交门下验收。必须区分完成、失败与未完成,不能把已派工当成完成。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
taskId: { type: 'string', description: '流程任务 id' },
|
||||
summary: { type: 'string', description: '汇总内容;省略时由宿主根据六部真实结果生成' },
|
||||
},
|
||||
required: ['taskId'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
try {
|
||||
return await service.workflowSummarize(located.project.id, text(args.taskId), { summary: text(args.summary) }, actorOf(located))
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_workflow_accept',
|
||||
description: '门下省专用:验收尚书汇总。accept 后交丞相交付;reject 退回尚书省重新调度。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
taskId: { type: 'string', description: '流程任务 id' },
|
||||
action: { type: 'string', enum: ['accept', 'reject'], description: '通过或退回' },
|
||||
note: { type: 'string', description: '验收意见;退回必填' },
|
||||
},
|
||||
required: ['taskId', 'action'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
try {
|
||||
return await service.workflowAccept(located.project.id, text(args.taskId), { action: text(args.action), note: text(args.note) }, actorOf(located))
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_workflow_deliver',
|
||||
description: '丞相专用:向用户交付已通过门下验收的真实结果。不得代替六部伪造或改写执行结果。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
taskId: { type: 'string', description: '流程任务 id' },
|
||||
delivery: { type: 'string', description: '给用户的交付说明,必须引用真实执行结果和结果会话' },
|
||||
},
|
||||
required: ['taskId', 'delivery'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
try {
|
||||
return await service.workflowDeliver(located.project.id, text(args.taskId), { delivery: text(args.delivery) }, actorOf(located))
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_dispatch_task',
|
||||
description: '已停用:直接派工违反需求门控。丞相必须使用 sansheng_requirement_upsert / sansheng_requirement_publish,经中书拟案、门下审核、用户批准后才由尚书调度六部。本工具只返回拒绝,不产生任何副作用。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
targetSeatId: { type: 'string', description: '旧参数,任意目标都会被拒绝' },
|
||||
title: { type: 'string', description: '旧参数' },
|
||||
},
|
||||
},
|
||||
async execute(_args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
return {
|
||||
...result,
|
||||
ok: true,
|
||||
delivered: true,
|
||||
taskId: created.task.id,
|
||||
sessionId: dispatched.task.sessionId,
|
||||
targetLabel: labelOf(targetSeatId),
|
||||
ok: false,
|
||||
delivered: false,
|
||||
reason: 'workflow-required',
|
||||
error: located.seatId === 'lead'
|
||||
? '直接派工已停用。请先整理需求清单并等待用户明确发布;需求只能发布给中书省,经门下审核和用户批准后才由尚书调度六部。未创建任务、未写入共识、未投递任何会话。'
|
||||
: '部门不能自行派工或改派;请只执行已获批且由尚书分派给本席的任务。',
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_task_list',
|
||||
description: '查看当前项目真实任务列表,包含状态、主责部门、是否已投递、结果和结果来源会话。',
|
||||
description: '查看当前项目真实任务列表,包含状态、主责部门、流程阶段、是否已投递、结果和结果来源会话。',
|
||||
parameters: { type: 'object', properties: {} },
|
||||
async execute(_args = {}, exec) {
|
||||
const { project } = await locateSeat(service, exec)
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
const { project } = located
|
||||
const tasks = (project.tasks ?? []).map(task => ({ ...task, targetLabel: labelOf(task.ownerSeatId) }))
|
||||
return { ok: true, projectId: project.id, tasks }
|
||||
},
|
||||
|
|
@ -173,63 +366,29 @@ function seatToolDefinitions({ store, service }) {
|
|||
required: ['taskId'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
const { project } = await locateSeat(service, exec)
|
||||
const task = (await service.taskGet(project.id, text(args.taskId))).task
|
||||
return { ok: true, task: { ...task, targetLabel: labelOf(task.ownerSeatId) } }
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
try {
|
||||
const task = (await service.taskGet(located.project.id, text(args.taskId))).task
|
||||
return { ok: true, task: { ...task, targetLabel: labelOf(task.ownerSeatId) } }
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_task_revise',
|
||||
description: '丞相专用:用户改口或补充要求时,先更新项目共识,再按新要求重新投递到原部门会话。不能只口头说“已通知”。已完成或已取消的任务不能改历史结果,需用 sansheng_dispatch_task 新建任务。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
taskId: { type: 'string', description: '任务 id' },
|
||||
goal: { type: 'string', description: '新的任务说明' },
|
||||
requirement: { type: 'string', description: '新的用户要求(尽量保留原话)' },
|
||||
sourceText: { type: 'string', description: '用户改口原文,用于写入项目共识来源' },
|
||||
},
|
||||
required: ['taskId'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
const { project, seatId } = await locateSeat(service, exec)
|
||||
if (seatId !== 'lead') throw new Error('只有丞相可以修改要求并重投')
|
||||
const taskId = text(args.taskId)
|
||||
const goal = text(args.goal)
|
||||
const requirement = text(args.requirement)
|
||||
const sourceText = text(args.sourceText)
|
||||
if (!goal && !requirement) throw new Error('修改要求需要提供新的 goal 或 requirement')
|
||||
const existing = (await service.taskGet(project.id, taskId)).task
|
||||
if (existing.status === 'done' || existing.status === 'cancelled') {
|
||||
throw new Error('任务已完成或已取消,不能原地修改;请用 sansheng_dispatch_task 新建任务,保留历史结果')
|
||||
}
|
||||
if (requirement || sourceText) {
|
||||
await service.memoryUpdate(project.id, {
|
||||
decisions: [{ type: 'user', status: 'active', text: sourceText || requirement }],
|
||||
sources: [{ type: 'user', excerpt: sourceText || requirement, at: Date.now() }],
|
||||
})
|
||||
}
|
||||
await service.taskRevise(project.id, taskId, { goal: goal || undefined, requirement: requirement || undefined })
|
||||
const dispatched = await service.taskDispatch(project.id, taskId, { force: true })
|
||||
const result = okTask(dispatched.task)
|
||||
if (!dispatched.delivered) {
|
||||
return { ...result, ok: false, delivered: false, error: dispatched.task.note || '改要求后投递失败,未送达部门会话' }
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
ok: true,
|
||||
delivered: true,
|
||||
sessionId: dispatched.task.sessionId,
|
||||
requirement: dispatched.task.requirement ?? '',
|
||||
contextRevision: dispatched.task.contextRevision ?? null,
|
||||
}
|
||||
description: '已停用:需求变更必须更新需求清单 revision,旧发布和旧批准会自动失效,重新走发布/审核/批准流程。本工具只返回拒绝,不产生任何副作用。',
|
||||
parameters: { type: 'object', properties: {} },
|
||||
async execute(_args = {}, exec) {
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
return { ok: false, reason: 'workflow-required', error: '任务改派/改要求已停用。请用 sansheng_requirement_upsert 更新原需求(revision 自动增加),旧发布命令和旧批准会立即失效。' }
|
||||
},
|
||||
})
|
||||
|
||||
definitions.push({
|
||||
name: 'sansheng_task_report',
|
||||
description: '部门专用:向当前项目的任务回报 running(执行中)、done(完成,必须附真实结果)或 failed(失败)。丞相不能代替部门报告,结果会关联真实部门 session。',
|
||||
description: '部门专用:向当前项目的任务回报 running(执行中)、done(完成,必须附真实结果)或 failed(失败)。六部执行任务必须带有效 approvalId、需求 revision 和批准范围;丞相不能代替部门报告。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
|
|
@ -241,16 +400,20 @@ function seatToolDefinitions({ store, service }) {
|
|||
required: ['taskId', 'status'],
|
||||
},
|
||||
async execute(args = {}, exec) {
|
||||
const { project, seatId, sessionId } = await locateSeat(service, exec)
|
||||
if (seatId === 'lead') throw new Error('丞相不能代替部门报告,必须由实际执行部门回报')
|
||||
const reported = await service.taskReport(project.id, text(args.taskId), {
|
||||
status: text(args.status),
|
||||
result: text(args.result),
|
||||
note: text(args.note),
|
||||
seatId,
|
||||
sessionId,
|
||||
})
|
||||
return { ok: true, task: reported.task, late: Boolean(reported.late) }
|
||||
let located
|
||||
try { located = await locateSeat(service, exec) } catch (error) { return failure(error, { reason: 'tool-not-ready' }) }
|
||||
const { project, seatId, sessionId } = located
|
||||
if (seatId === 'lead') return { ok: false, reason: 'forbidden', error: '丞相不能代替部门报告,必须由实际执行部门回报' }
|
||||
try {
|
||||
const reported = await service.taskReport(project.id, text(args.taskId), {
|
||||
status: text(args.status),
|
||||
result: text(args.result),
|
||||
note: text(args.note),
|
||||
seatId,
|
||||
sessionId,
|
||||
})
|
||||
return { ok: true, task: reported.task, late: Boolean(reported.late) }
|
||||
} catch (error) { return failure(error) }
|
||||
},
|
||||
})
|
||||
|
||||
|
|
@ -262,6 +425,76 @@ export function createSeatToolDefinitions(options) {
|
|||
return seatToolDefinitions(options)
|
||||
}
|
||||
|
||||
|
||||
// 通用工具守卫:需求门控不能只拦 sansheng_* 工具,还要拦住各席位的通用文件/命令工具与子代理旁路。
|
||||
// 这是宿主 ctx.tools.guard 的系统级 deny,不依赖模型是否遵守提示词。
|
||||
const MUTATING_TOOL_NAMES = new Set([
|
||||
'pwsh', 'bash', 'terminal', 'shell', 'exec',
|
||||
'write', 'edit', 'apply_patch', 'str_replace_editor', 'str-replace-editor',
|
||||
'create_file', 'delete_file', 'move_file',
|
||||
])
|
||||
const BYPASS_AGENT_TOOLS = new Set([
|
||||
'subagent', 'subagent_fork', 'send_message', 'interrupt_agent',
|
||||
'task_board_create', 'task_board_run', 'schedule_create',
|
||||
])
|
||||
const PLANNING_SEATS = new Set(['lead', 'zhongshu', 'shangshu', 'menxia'])
|
||||
|
||||
function labelOfSeat(seatId) {
|
||||
return SEATS[seatId]?.label ?? seatId
|
||||
}
|
||||
|
||||
// 六部只有在“真实已批准、revision/范围一致、且派给了本会话”的执行子任务里才允许写。
|
||||
function approvedExecutionForSeat(project, seatId, sessionId) {
|
||||
const tasks = Array.isArray(project?.tasks) ? project.tasks : []
|
||||
const requirements = Array.isArray(project?.requirements) ? project.requirements : []
|
||||
const approvals = Array.isArray(project?.approvals) ? project.approvals : []
|
||||
for (const task of tasks) {
|
||||
if (task?.kind !== 'execution') continue
|
||||
if (task.ownerSeatId !== seatId) continue
|
||||
if (task.sessionId && task.sessionId !== sessionId) continue
|
||||
if (!['draft', 'prepared', 'dispatched', 'running'].includes(task.status)) continue
|
||||
if (!task.approvalId || !task.requirementId) continue
|
||||
const approval = approvals.find(item => item.id === task.approvalId)
|
||||
const requirement = requirements.find(item => item.id === task.requirementId)
|
||||
if (!approval || approval.status !== 'approved') continue
|
||||
if (!requirement || requirement.revision !== approval.requirementRevision) continue
|
||||
if (task.requirementRevision !== requirement.revision) continue
|
||||
if ((task.approvalScope ?? '') !== (approval.scope ?? '')) continue
|
||||
return task
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function seatProject(store, sessionId) {
|
||||
for (const project of Object.values(store.state?.projects ?? {})) {
|
||||
for (const seatId of SEAT_IDS) {
|
||||
if (project?.seats?.[seatId]?.sessionId === sessionId) return { project, seatId }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function buildSeatToolGuard(store, sessionId) {
|
||||
return execution => {
|
||||
const name = typeof execution?.name === 'string' ? execution.name : ''
|
||||
if (!MUTATING_TOOL_NAMES.has(name) && !BYPASS_AGENT_TOOLS.has(name)) return undefined
|
||||
const found = seatProject(store, sessionId)
|
||||
if (!found) return '需求门控模式:当前会话不是三省六部席位,不能使用此工具。'
|
||||
const { project, seatId } = found
|
||||
if (BYPASS_AGENT_TOOLS.has(name)) {
|
||||
return `需求门控模式:${labelOfSeat(seatId)}不能使用 ${name} 绕过席位派工或审批流程。`
|
||||
}
|
||||
if (PLANNING_SEATS.has(seatId)) {
|
||||
return `需求门控模式:${labelOfSeat(seatId)}在拟案、审核、调度阶段只能只读调查,不能使用 ${name} 修改文件或执行工程操作。`
|
||||
}
|
||||
if (SEAT_GROUPS.liubu.includes(seatId)) {
|
||||
if (approvedExecutionForSeat(project, seatId, sessionId)) return undefined
|
||||
return `需求门控模式:${labelOfSeat(seatId)}当前没有有效的已批准执行任务,不能使用 ${name} 修改文件或执行工程操作。`
|
||||
}
|
||||
return '需求门控模式:当前席位没有执行批准,不能修改文件或执行工程操作。'
|
||||
}
|
||||
}
|
||||
|
||||
export function installSeatTools(ctx, { store, service, provisioner }) {
|
||||
const defs = createSeatToolDefinitions({ store, service })
|
||||
// sessionId -> { agent, disposers: Map<name, dispose>, registered: Set<name> }
|
||||
|
|
@ -282,6 +515,9 @@ export function installSeatTools(ctx, { store, service, provisioner }) {
|
|||
}
|
||||
record.disposers.clear()
|
||||
record.registered.clear()
|
||||
try { record.guardDispose?.() } catch {}
|
||||
record.guardDispose = null
|
||||
record.guardMounted = false
|
||||
}
|
||||
|
||||
const findSeat = sessionId => {
|
||||
|
|
@ -310,11 +546,24 @@ export function installSeatTools(ctx, { store, service, provisioner }) {
|
|||
disposeFor(sessionId)
|
||||
record = undefined
|
||||
}
|
||||
const mountGuard = () => {
|
||||
if (!record || record.guardMounted || typeof agentTools.guard !== 'function') return
|
||||
record.guardMounted = true
|
||||
try {
|
||||
const dispose = agentTools.guard(buildSeatToolGuard(store, sessionId))
|
||||
record.guardDispose = typeof dispose === 'function' ? dispose : null
|
||||
} catch (error) {
|
||||
record.guardMounted = false
|
||||
console.warn(`sansheng: register tool guard failed: ${error?.message ?? error}`)
|
||||
}
|
||||
}
|
||||
mountGuard()
|
||||
if (record && record.registered.size === defs.length) return true
|
||||
if (!record) {
|
||||
record = { agent, disposers: new Map(), registered: new Set() }
|
||||
record = { agent, disposers: new Map(), registered: new Set(), guardDispose: null, guardMounted: false }
|
||||
installs.set(sessionId, record)
|
||||
}
|
||||
mountGuard()
|
||||
for (const def of defs) {
|
||||
if (record.registered.has(def.name)) continue
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -7,8 +7,12 @@ export const STATE_VERSION = 1
|
|||
|
||||
export const SEAT_STATUS = Object.freeze(['pending', 'creating', 'bound', 'failed', 'missing'])
|
||||
export const PROJECT_STATUS = Object.freeze(['pending', 'provisioning', 'ready', 'error'])
|
||||
// 任务:草稿 → 已派工/待执行 → 完成 / 取消 / 失败
|
||||
export const TASK_STATUS = Object.freeze(['draft', 'dispatched', 'running', 'prepared', 'done', 'cancelled', 'failed'])
|
||||
// 任务:草稿 → 已派工/待执行 → 完成 / 取消 / 失败;需求门控增加等待用户、退回、待重确认。
|
||||
export const TASK_STATUS = Object.freeze(['draft', 'dispatched', 'running', 'prepared', 'done', 'cancelled', 'failed', 'waiting_user', 'returned', 'reconfirm'])
|
||||
// 需求清单:商讨中 / 待发布 / 已发布 / 已退回 / 已取消。
|
||||
export const REQUIREMENT_STATUS = Object.freeze(['discussing', 'ready', 'published', 'returned', 'cancelled'])
|
||||
// 流程阶段:只由宿主服务推进,模型不能跳阶段。
|
||||
export const WORKFLOW_STAGE = Object.freeze(['zhongshu_draft', 'menxia_review', 'awaiting_execution_approval', 'shangshu_dispatch', 'department_exec', 'shangshu_summary', 'menxia_acceptance', 'lead_delivery', 'delivered', 'reconfirm'])
|
||||
|
||||
const SEAT_STATUS_SET = new Set(SEAT_STATUS)
|
||||
const PROJECT_STATUS_SET = new Set(PROJECT_STATUS)
|
||||
|
|
@ -48,8 +52,12 @@ export function emptyProject({ id, name, workspaceId = null, path = null, now =
|
|||
// 任务与交付成果:按项目隔离保存;旧数据没有这两个字段时按空数组处理。
|
||||
tasks: [],
|
||||
artifacts: [],
|
||||
requirements: [],
|
||||
approvals: [],
|
||||
taskSeq: 0,
|
||||
artifactSeq: 0,
|
||||
requirementSeq: 0,
|
||||
approvalSeq: 0,
|
||||
// 项目共识(本地临时存储;Mnemon Documents 适配后迁移)。
|
||||
memory: emptyProjectMemory(id),
|
||||
revision: 0,
|
||||
|
|
@ -58,9 +66,11 @@ export function emptyProject({ id, name, workspaceId = null, path = null, now =
|
|||
}
|
||||
}
|
||||
|
||||
export function emptyTask({ id, title = '', goal = '', requirement = '', ownerSeatId = 'lead', now = Date.now() }) {
|
||||
export function emptyTask({ id, title = '', goal = '', requirement = '', ownerSeatId = 'lead', now = Date.now(), kind = 'legacy', requirementId = null, requirementRevision = null, approvalId = null, parentTaskId = null, stage = null }) {
|
||||
return {
|
||||
id, title, goal, requirement, ownerSeatId, status: 'draft', note: '', sessionId: null,
|
||||
kind, requirementId, requirementRevision, approvalId, parentTaskId, stage,
|
||||
blockedReason: '', draft: '', reviewNote: '', summary: '', deliveryNote: '',
|
||||
createdAt: now, updatedAt: now, dispatchedAt: null,
|
||||
contextRevision: 0, contextHash: '', decisionIds: [], sourceRefs: [],
|
||||
deliveryId: null, deliveryState: 'none', contextSyncState: 'none',
|
||||
|
|
@ -68,6 +78,15 @@ export function emptyTask({ id, title = '', goal = '', requirement = '', ownerSe
|
|||
}
|
||||
}
|
||||
|
||||
export function emptyRequirement({ id, title = '', summary = '', originalText = '', now = Date.now() }) {
|
||||
return {
|
||||
id, title, summary, originalText, judgement: 'needs_discussion', judgementReason: '',
|
||||
scope: '', nonGoals: '', acceptanceCriteria: '', risks: '', dependencies: '', missingInfo: '',
|
||||
revision: 1, status: 'discussing', blockedReason: '等待与用户商讨并补全发布信息',
|
||||
createdAt: now, updatedAt: now, publishedRevision: null, publishedAt: null, cancelledAt: null,
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyArtifact({ id, title = '', path = '', summary = '', taskId = null, now = Date.now() }) {
|
||||
return { id, title, path, summary, taskId, createdAt: now }
|
||||
}
|
||||
|
|
@ -117,6 +136,19 @@ function projectProblem(project, id) {
|
|||
const problem = seatProblem(project.seats[seatId], seatId, id)
|
||||
if (problem) return problem
|
||||
}
|
||||
if (project.requirements !== undefined && !Array.isArray(project.requirements)) return `项目 ${id} 的 requirements 不是数组`
|
||||
for (const [index, req] of (project.requirements ?? []).entries()) {
|
||||
if (!isObject(req)) return `项目 ${id} 的 requirements[${index}] 不是对象`
|
||||
if (!isStr(req.id)) return `项目 ${id} 的 requirements[${index}] 缺少 id`
|
||||
if (!REQUIREMENT_STATUS.includes(req.status)) return `项目 ${id} 的需求 ${req.id} 状态非法:${String(req.status)}`
|
||||
if (!Number.isFinite(req.revision)) return `项目 ${id} 的需求 ${req.id} 的 revision 非法`
|
||||
}
|
||||
if (project.approvals !== undefined && !Array.isArray(project.approvals)) return `项目 ${id} 的 approvals 不是数组`
|
||||
for (const [index, approval] of (project.approvals ?? []).entries()) {
|
||||
if (!isObject(approval)) return `项目 ${id} 的 approvals[${index}] 不是对象`
|
||||
if (!isStr(approval.id)) return `项目 ${id} 的 approvals[${index}] 缺少 id`
|
||||
if (!['approved', 'invalidated'].includes(approval.status)) return `项目 ${id} 的批准 ${approval.id} 状态非法`
|
||||
}
|
||||
if (project.tasks !== undefined && !Array.isArray(project.tasks)) return `项目 ${id} 的 tasks 不是数组`
|
||||
for (const [index, task] of (project.tasks ?? []).entries()) {
|
||||
if (!isObject(task)) return `项目 ${id} 的 tasks[${index}] 不是对象`
|
||||
|
|
|
|||
|
|
@ -37,6 +37,9 @@ export function createFakeHost(opts = {}) {
|
|||
agent = {
|
||||
id: sessionId,
|
||||
_selection: null,
|
||||
_messages: [],
|
||||
deriveMessages() { return agent._messages },
|
||||
session: { id: sessionId, deriveMessages() { return agent._messages } },
|
||||
model: {
|
||||
current() { return agent._selection },
|
||||
select(selection) { agent._selection = selection; calls.agentSelect.push({ sessionId, selection }) },
|
||||
|
|
@ -113,5 +116,6 @@ export function createFakeHost(opts = {}) {
|
|||
addWorkspace(id, name, path) { workspaces.set(id, { id, name, path }) },
|
||||
// 预置一个已存在的会话(用于“已存在不重建”测试)
|
||||
addSession(sessionId) { return agentFor(sessionId) },
|
||||
say(sessionId, text) { const agent = agentFor(sessionId); agent._messages.push({ role: 'user', content: [{ type: 'text', text }] }); return agent },
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,315 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
import { createSeatToolDefinitions } from '../src/host/tools.js'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { SanshengStore } from '../src/host/store.js'
|
||||
import { SanshengService } from '../src/host/service.js'
|
||||
|
||||
async function setupGate() {
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/requirement-gate', name: '需求门控项目' })
|
||||
env.projectId = opened.project.id
|
||||
env.seatSessions = {}
|
||||
for (const seatId of ['lead', 'zhongshu', 'menxia', 'shangshu', 'gongbu', 'libu']) {
|
||||
const view = await env.service.enableSeat(env.projectId, seatId)
|
||||
env.seatSessions[seatId] = seatById(view, seatId).sessionId
|
||||
}
|
||||
env.tools = Object.fromEntries(createSeatToolDefinitions({ store: env.store, service: env.service }).map(def => [def.name, def]))
|
||||
return env
|
||||
}
|
||||
|
||||
function execOf(env, seatId) {
|
||||
return { agent: env.fake.sessions.get(env.seatSessions[seatId]) }
|
||||
}
|
||||
|
||||
function run(env, name, args, seatId) {
|
||||
return env.tools[name].execute(args, execOf(env, seatId))
|
||||
}
|
||||
|
||||
async function readyRequirement(env, overrides = {}) {
|
||||
const out = await run(env, 'sansheng_requirement_upsert', {
|
||||
title: '多语言实验台',
|
||||
summary: '做一个本地多语言 Hello World 展示页',
|
||||
originalText: '我要一个本地多语言 Hello World 展示页,标题 QQ主人的多语言实验台,页脚青竹试航。',
|
||||
judgement: 'can_do',
|
||||
judgementReason: '范围明确,本机现有运行环境即可完成',
|
||||
scope: '本地静态页面 + 三种可运行语言示例',
|
||||
nonGoals: '不部署公网,不引入构建依赖',
|
||||
acceptanceCriteria: '三种语言均可真实运行;窄屏可用;可重跑;成功和失败有区分',
|
||||
risks: '浏览器兼容性',
|
||||
dependencies: '本机 Python / Node / 浏览器',
|
||||
missingInfo: '无',
|
||||
...overrides,
|
||||
}, 'lead')
|
||||
assert.equal(out.ok, true, out.error)
|
||||
return out.requirement
|
||||
}
|
||||
|
||||
async function publishRequirement(env, req) {
|
||||
env.fake.say(env.seatSessions.lead, `发布 ${req.id} 给中书`)
|
||||
const out = await run(env, 'sansheng_requirement_publish', {
|
||||
requirementId: req.id,
|
||||
expectedRevision: req.revision,
|
||||
targetSeatId: 'zhongshu',
|
||||
}, 'lead')
|
||||
assert.equal(out.ok, true, out.error)
|
||||
return out
|
||||
}
|
||||
|
||||
async function produceReviewedPlan(env) {
|
||||
const req = await readyRequirement(env)
|
||||
const published = await publishRequirement(env, req)
|
||||
const draft = await run(env, 'sansheng_workflow_submit', {
|
||||
taskId: published.taskId,
|
||||
draft: '拟案:先做静态页面,再由工部执行三种语言示例,最后门下验收。',
|
||||
}, 'zhongshu')
|
||||
assert.equal(draft.ok, true, draft.error)
|
||||
const review = await run(env, 'sansheng_workflow_review', {
|
||||
taskId: published.taskId,
|
||||
action: 'approve',
|
||||
note: '方案可执行',
|
||||
}, 'menxia')
|
||||
assert.equal(review.ok, true, review.error)
|
||||
return { req, taskId: published.taskId }
|
||||
}
|
||||
|
||||
test('1. 用户第一次提出想法:只整理需求清单,不创建执行任务、不派工、不改工程', async () => {
|
||||
const env = await setupGate()
|
||||
const req = await readyRequirement(env)
|
||||
const tasks = await env.service.tasks(env.projectId)
|
||||
assert.equal(tasks.tasks.length, 0, '需求清单不是任务')
|
||||
assert.equal(env.fake.calls.prompt.length, 0, '不能自动投递任何部门会话')
|
||||
assert.equal(req.status, 'ready')
|
||||
assert.equal(req.id, 'R-001')
|
||||
})
|
||||
|
||||
test('2. 丞相尝试直接派给工部:系统拒绝且无任务/共识/投递副作用', async () => {
|
||||
const env = await setupGate()
|
||||
const req = await readyRequirement(env)
|
||||
const memoryBefore = (await env.service.memory(env.projectId)).memory.revision
|
||||
const promptBefore = env.fake.calls.prompt.length
|
||||
const out = await run(env, 'sansheng_dispatch_task', { targetSeatId: 'gongbu', title: '写页面', goal: '完成页面' }, 'lead')
|
||||
assert.equal(out.ok, false)
|
||||
assert.equal(out.reason, 'workflow-required')
|
||||
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
|
||||
assert.equal((await env.service.memory(env.projectId)).memory.revision, memoryBefore)
|
||||
assert.equal(env.fake.calls.prompt.length, promptBefore)
|
||||
const reqs = await env.service.requirements(env.projectId)
|
||||
assert.equal(reqs.requirements[0].status, req.status, '需求状态也不能被直接派工改变')
|
||||
})
|
||||
|
||||
test('3. 未发布需求不能进入中书', async () => {
|
||||
const env = await setupGate()
|
||||
const req = await readyRequirement(env, { scope: '', acceptanceCriteria: '' })
|
||||
env.fake.say(env.seatSessions.lead, `发布 ${req.id} 给中书`)
|
||||
const out = await run(env, 'sansheng_requirement_publish', {
|
||||
requirementId: req.id,
|
||||
expectedRevision: req.revision,
|
||||
targetSeatId: 'zhongshu',
|
||||
}, 'lead')
|
||||
assert.equal(out.ok, false)
|
||||
assert.match(String(out.error), /待发布|不可发布|范围/)
|
||||
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0)
|
||||
})
|
||||
|
||||
test('4. 明确发布后只进入中书,不能直接进尚书/六部', async () => {
|
||||
const env = await setupGate()
|
||||
const req = await readyRequirement(env)
|
||||
env.fake.say(env.seatSessions.lead, `发布 ${req.id} 给中书`)
|
||||
const bad = await run(env, 'sansheng_requirement_publish', {
|
||||
requirementId: req.id,
|
||||
expectedRevision: req.revision,
|
||||
targetSeatId: 'gongbu',
|
||||
}, 'lead')
|
||||
assert.equal(bad.ok, false)
|
||||
assert.equal(bad.reason, 'workflow-route-forbidden')
|
||||
assert.equal((await env.service.tasks(env.projectId)).tasks.length, 0, '被拒绝的发布不能产生任务')
|
||||
|
||||
const good = await run(env, 'sansheng_requirement_publish', {
|
||||
requirementId: req.id,
|
||||
expectedRevision: req.revision,
|
||||
targetSeatId: 'zhongshu',
|
||||
}, 'lead')
|
||||
assert.equal(good.ok, true, good.error)
|
||||
const tasks = (await env.service.tasks(env.projectId)).tasks
|
||||
assert.equal(tasks.length, 1)
|
||||
assert.equal(tasks[0].ownerSeatId, 'zhongshu')
|
||||
assert.equal(tasks[0].kind, 'workflow')
|
||||
assert.equal(tasks[0].stage, 'zhongshu_draft')
|
||||
assert.equal(env.fake.calls.prompt.at(-1).sessionId, env.seatSessions.zhongshu)
|
||||
})
|
||||
|
||||
test('5. 中书不能直接派六部', async () => {
|
||||
const env = await setupGate()
|
||||
const req = await readyRequirement(env)
|
||||
const published = await publishRequirement(env, req)
|
||||
const before = (await env.service.tasks(env.projectId)).tasks.length
|
||||
const out = await run(env, 'sansheng_workflow_dispatch', {
|
||||
taskId: published.taskId,
|
||||
assignments: [{ seatId: 'gongbu', title: '直接开工' }],
|
||||
}, 'zhongshu')
|
||||
assert.equal(out.ok, false)
|
||||
assert.equal(out.reason, 'sansheng/forbidden')
|
||||
assert.equal((await env.service.tasks(env.projectId)).tasks.length, before, '中书不能创建六部执行任务')
|
||||
})
|
||||
|
||||
test('6. 门下审核后、用户未批准前,尚书不能派工六部', async () => {
|
||||
const env = await setupGate()
|
||||
const { req, taskId } = await produceReviewedPlan(env)
|
||||
const before = (await env.service.tasks(env.projectId)).tasks.length
|
||||
const promptBefore = env.fake.calls.prompt.length
|
||||
const out = await run(env, 'sansheng_workflow_dispatch', {
|
||||
taskId,
|
||||
assignments: [{ seatId: 'gongbu', title: '开始施工' }],
|
||||
}, 'shangshu')
|
||||
assert.equal(out.ok, false)
|
||||
assert.equal(out.reason, 'sansheng/stage-forbidden')
|
||||
assert.equal((await env.service.tasks(env.projectId)).tasks.length, before)
|
||||
assert.equal(env.fake.calls.prompt.length, promptBefore)
|
||||
const task = (await env.service.taskGet(env.projectId, taskId)).task
|
||||
assert.equal(task.status, 'waiting_user')
|
||||
assert.equal(task.stage, 'awaiting_execution_approval')
|
||||
const reqs = await env.service.requirements(env.projectId)
|
||||
assert.equal(reqs.requirements[0].status, 'published')
|
||||
})
|
||||
|
||||
test('7. 用户明确批准后,尚书才能向六部派工', async () => {
|
||||
const env = await setupGate()
|
||||
const { req, taskId } = await produceReviewedPlan(env)
|
||||
env.fake.say(env.seatSessions.lead, `批准执行 ${req.id}`)
|
||||
const approved = await run(env, 'sansheng_requirement_approve', {
|
||||
requirementId: req.id,
|
||||
expectedRevision: req.revision,
|
||||
}, 'lead')
|
||||
assert.equal(approved.ok, true, approved.error)
|
||||
const approvals = (await env.service.requirements(env.projectId)).approvals
|
||||
assert.equal(approvals.length, 1)
|
||||
assert.equal(approvals[0].status, 'approved')
|
||||
const out = await run(env, 'sansheng_workflow_dispatch', {
|
||||
taskId,
|
||||
assignments: [{ seatId: 'gongbu', title: '实现多语言页面', goal: '真实运行三种语言示例' }],
|
||||
}, 'shangshu')
|
||||
assert.equal(out.ok, true, out.error)
|
||||
const tasks = (await env.service.tasks(env.projectId)).tasks
|
||||
const child = tasks.find(task => task.parentTaskId === taskId && task.kind === 'execution')
|
||||
assert.ok(child)
|
||||
assert.equal(child.ownerSeatId, 'gongbu')
|
||||
assert.equal(child.approvalId, approvals[0].id)
|
||||
assert.equal(env.fake.calls.prompt.at(-1).sessionId, env.seatSessions.gongbu)
|
||||
})
|
||||
|
||||
test('8. 用户直接对六部聊天也不能绕过批准执行', async () => {
|
||||
const env = await setupGate()
|
||||
const before = (await env.service.tasks(env.projectId)).tasks.length
|
||||
const dispatch = await run(env, 'sansheng_dispatch_task', { targetSeatId: 'gongbu', title: '我自己开工' }, 'gongbu')
|
||||
assert.equal(dispatch.ok, false)
|
||||
assert.equal(dispatch.reason, 'workflow-required')
|
||||
const workflow = await run(env, 'sansheng_workflow_dispatch', {
|
||||
taskId: 'task-1',
|
||||
assignments: [{ seatId: 'gongbu', title: '偷偷施工' }],
|
||||
}, 'gongbu')
|
||||
assert.equal(workflow.ok, false)
|
||||
assert.equal((await env.service.tasks(env.projectId)).tasks.length, before)
|
||||
assert.equal(env.fake.calls.prompt.length, 0)
|
||||
})
|
||||
|
||||
test('9. 需求 revision 变化后旧批准立即失效,旧任务不能再报告完成', async () => {
|
||||
const env = await setupGate()
|
||||
const { req, taskId } = await produceReviewedPlan(env)
|
||||
env.fake.say(env.seatSessions.lead, `批准执行 ${req.id}`)
|
||||
const approved = await run(env, 'sansheng_requirement_approve', { requirementId: req.id, expectedRevision: req.revision }, 'lead')
|
||||
assert.equal(approved.ok, true, approved.error)
|
||||
const dispatched = await run(env, 'sansheng_workflow_dispatch', {
|
||||
taskId,
|
||||
assignments: [{ seatId: 'gongbu', title: '实现页面' }],
|
||||
}, 'shangshu')
|
||||
assert.equal(dispatched.ok, true, dispatched.error)
|
||||
const child = (await env.service.tasks(env.projectId)).tasks.find(task => task.parentTaskId === taskId && task.kind === 'execution')
|
||||
|
||||
const updated = await run(env, 'sansheng_requirement_upsert', {
|
||||
id: req.id,
|
||||
expectedRevision: req.revision,
|
||||
acceptanceCriteria: '新增要求:必须额外支持第四种语言',
|
||||
}, 'lead')
|
||||
assert.equal(updated.ok, true, updated.error)
|
||||
assert.equal(updated.requirement.revision, req.revision + 1)
|
||||
const approvals = (await env.service.requirements(env.projectId)).approvals
|
||||
assert.equal(approvals[0].status, 'invalidated')
|
||||
const oldTask = (await env.service.taskGet(env.projectId, taskId)).task
|
||||
assert.equal(oldTask.status, 'reconfirm')
|
||||
const report = await run(env, 'sansheng_task_report', {
|
||||
taskId: child.id,
|
||||
status: 'done',
|
||||
result: '旧批准下完成的结果',
|
||||
}, 'gongbu')
|
||||
assert.equal(report.ok, false)
|
||||
assert.equal(report.reason, 'sansheng/approval-invalid')
|
||||
})
|
||||
|
||||
test('10. 等待用户批准状态在会话恢复后仍然阻塞', async () => {
|
||||
const env = await setupGate()
|
||||
const { taskId } = await produceReviewedPlan(env)
|
||||
const store2 = new SanshengStore(env.file)
|
||||
await store2.load()
|
||||
const service2 = new SanshengService({ store: store2, host: env.fake.host, provisioner: env.provisioner })
|
||||
const task = (await service2.taskGet(env.projectId, taskId)).task
|
||||
assert.equal(task.status, 'waiting_user')
|
||||
assert.equal(task.stage, 'awaiting_execution_approval')
|
||||
assert.match(task.blockedReason, /等待用户明确批准执行/)
|
||||
await assert.rejects(
|
||||
() => service2.workflowDispatch(env.projectId, taskId, { assignments: [{ seatId: 'gongbu', title: '恢复后偷跑' }] }, { seatId: 'shangshu', sessionId: env.seatSessions.shangshu }),
|
||||
error => error.code === 'sansheng/stage-forbidden',
|
||||
)
|
||||
})
|
||||
|
||||
test('11. 工作台需求清单显示条目、判断、版本、阻塞与流转任务', async () => {
|
||||
const env = await setupGate()
|
||||
const req = await readyRequirement(env)
|
||||
const requirements = await env.service.requirements(env.projectId)
|
||||
assert.equal(requirements.requirements.length, 1)
|
||||
const view = requirements.requirements[0]
|
||||
for (const key of ['id', 'title', 'summary', 'originalText', 'judgement', 'judgementReason', 'scope', 'nonGoals', 'acceptanceCriteria', 'risks', 'dependencies', 'missingInfo', 'revision', 'status', 'blockedReason']) {
|
||||
assert.ok(Object.hasOwn(view, key), `需求清单缺少字段 ${key}`)
|
||||
}
|
||||
const workbenchSource = await readFile(new URL('../src/client/workbench-v2.js', import.meta.url), 'utf8')
|
||||
assert.match(workbenchSource, /需求清单/)
|
||||
})
|
||||
|
||||
test('12. 最终结果追溯到真实执行部门会话(工部收到 != 工部完成)', async () => {
|
||||
const env = await setupGate()
|
||||
const { req, taskId } = await produceReviewedPlan(env)
|
||||
env.fake.say(env.seatSessions.lead, `批准执行 ${req.id}`)
|
||||
assert.equal((await run(env, 'sansheng_requirement_approve', { requirementId: req.id, expectedRevision: req.revision }, 'lead')).ok, true)
|
||||
const dispatched = await run(env, 'sansheng_workflow_dispatch', {
|
||||
taskId,
|
||||
assignments: [{ seatId: 'gongbu', title: '实现多语言页面', goal: '真实运行三种语言示例' }],
|
||||
}, 'shangshu')
|
||||
assert.equal(dispatched.ok, true, dispatched.error)
|
||||
const child = (await env.service.tasks(env.projectId)).tasks.find(task => task.parentTaskId === taskId && task.kind === 'execution')
|
||||
const beforeReport = (await env.service.taskGet(env.projectId, child.id)).task
|
||||
assert.equal(beforeReport.status, 'dispatched', '已派工只代表工部收到,不代表完成')
|
||||
assert.equal(beforeReport.result, null)
|
||||
|
||||
const report = await run(env, 'sansheng_task_report', {
|
||||
taskId: child.id,
|
||||
status: 'done',
|
||||
result: '真实结果:三种语言均执行成功,文件在 /workspace/index.html,验证输出 PASS。',
|
||||
}, 'gongbu')
|
||||
assert.equal(report.ok, true, report.error)
|
||||
const doneChild = (await env.service.taskGet(env.projectId, child.id)).task
|
||||
assert.equal(doneChild.status, 'done')
|
||||
assert.equal(doneChild.resultSessionId, env.seatSessions.gongbu, '结果必须追溯到工部真实会话')
|
||||
|
||||
const summary = await run(env, 'sansheng_workflow_summarize', { taskId, summary: '工部已完成三种语言页面并验证通过。' }, 'shangshu')
|
||||
assert.equal(summary.ok, true, summary.error)
|
||||
const accept = await run(env, 'sansheng_workflow_accept', { taskId, action: 'accept', note: '验收通过' }, 'menxia')
|
||||
assert.equal(accept.ok, true, accept.error)
|
||||
const deliver = await run(env, 'sansheng_workflow_deliver', { taskId, delivery: '交付:多语言实验台已完成,附工部真实输出。' }, 'lead')
|
||||
assert.equal(deliver.ok, true, deliver.error)
|
||||
const finalTask = (await env.service.taskGet(env.projectId, taskId)).task
|
||||
assert.equal(finalTask.status, 'done')
|
||||
assert.equal(finalTask.stage, 'delivered')
|
||||
assert.match(finalTask.summary, /工部已完成/)
|
||||
assert.equal((await env.service.taskGet(env.projectId, child.id)).task.resultSessionId, env.seatSessions.gongbu)
|
||||
})
|
||||
|
|
@ -1,33 +1,23 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
import { createSeatToolDefinitions } from '../src/host/tools.js'
|
||||
import { createApiHandler } from '../src/host/api.js'
|
||||
|
||||
function toolsOf(env) {
|
||||
const defs = createSeatToolDefinitions({ store: env.store, service: env.service })
|
||||
return Object.fromEntries(defs.map(def => [def.name, def]))
|
||||
}
|
||||
|
||||
test('尚书汇总:丞相直派不被拦截,汇总请求发送到尚书真实会话', async () => {
|
||||
test('尚书汇总:只读真实任务,不重派任务,汇总请求发送到尚书真实会话', async () => {
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/shangshu-summary', name: '尚书汇总项目' })
|
||||
const id = opened.project.id
|
||||
const leadView = await env.service.enableSeat(id, 'lead')
|
||||
const gongView = await env.service.enableSeat(id, 'gongbu')
|
||||
const leadSessionId = seatById(leadView, 'lead').sessionId
|
||||
const gongSessionId = seatById(gongView, 'gongbu').sessionId
|
||||
const leadExec = { agent: env.fake.sessions.get(leadSessionId) }
|
||||
|
||||
const dispatched = await toolsOf(env).sansheng_dispatch_task.execute({
|
||||
targetSeatId: 'gongbu',
|
||||
assert.ok(seatById(leadView, 'lead').sessionId)
|
||||
assert.ok(seatById(gongView, 'gongbu').sessionId)
|
||||
const created = await env.service.taskCreate(id, {
|
||||
title: '写页面',
|
||||
goal: '完成页面',
|
||||
requirement: '保留标题',
|
||||
}, leadExec)
|
||||
assert.equal(dispatched.ok, true, '丞相直派仍然成功')
|
||||
assert.equal(dispatched.sessionId, gongSessionId)
|
||||
assert.equal(dispatched.targetLabel, '工部')
|
||||
ownerSeatId: 'gongbu',
|
||||
})
|
||||
await env.service.taskDispatch(id, created.task.id, { force: true })
|
||||
|
||||
const before = await env.service.tasks(id)
|
||||
const result = await env.service.shangshuSummary(id)
|
||||
|
|
@ -47,7 +37,7 @@ test('尚书汇总:丞相直派不被拦截,汇总请求发送到尚书真
|
|||
assert.match(text, /【尚书汇总】/)
|
||||
assert.match(text, /写页面/)
|
||||
assert.match(text, /已派工/)
|
||||
assert.match(text, /不拦截丞相直接派工/)
|
||||
assert.match(text, /不重派任务/)
|
||||
})
|
||||
|
||||
test('尚书汇总 API 返回尚书会话和真实任务汇总', async () => {
|
||||
|
|
|
|||
|
|
@ -3,11 +3,11 @@ import assert from 'node:assert/strict'
|
|||
import { setupService, seatById } from './helpers.js'
|
||||
import { createSeatToolDefinitions, installSeatTools } from '../src/host/tools.js'
|
||||
|
||||
// 构造一个带事件总线、且能模拟“创建事件先于绑定保存”的 ctx。
|
||||
function makeEventedCtx(env) {
|
||||
const listeners = new Map()
|
||||
const registered = []
|
||||
const disposed = []
|
||||
const guards = []
|
||||
const emit = (event, payload) => {
|
||||
for (const fn of [...(listeners.get(event) ?? [])]) fn(payload)
|
||||
}
|
||||
|
|
@ -22,10 +22,13 @@ function makeEventedCtx(env) {
|
|||
registered.push({ sessionId: res.sessionId, name: def.name })
|
||||
return () => disposed.push({ sessionId: res.sessionId, name: def.name })
|
||||
},
|
||||
guard(fn) {
|
||||
guards.push({ sessionId: res.sessionId, guard: fn })
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
// 真实宿主:create() 内部先触发 agent/created,此时席位绑定还没保存。
|
||||
emit('agent/created', { agent })
|
||||
return res
|
||||
}
|
||||
|
|
@ -37,10 +40,12 @@ function makeEventedCtx(env) {
|
|||
return () => listeners.get(event)?.delete(fn)
|
||||
},
|
||||
}
|
||||
return { ctx, registered, disposed, emit }
|
||||
return { ctx, registered, disposed, guards, emit }
|
||||
}
|
||||
|
||||
test('回归:创建事件先到、绑定后保存时,绑定成功即补装派工工具(无需重扫)', async () => {
|
||||
const TOOL_COUNT = 15
|
||||
|
||||
test('回归:创建事件先到、绑定后保存时,绑定成功即补装部门工具(无需重扫)', async () => {
|
||||
const env = await setupService({ prompt: true })
|
||||
const { ctx, registered } = makeEventedCtx(env)
|
||||
const teardown = installSeatTools(ctx, { store: env.store, service: env.service, provisioner: env.provisioner })
|
||||
|
|
@ -50,8 +55,9 @@ test('回归:创建事件先到、绑定后保存时,绑定成功即补装
|
|||
await env.service.enableSeat(id, 'lead')
|
||||
const leadSessionId = seatById(await env.service.project(id), 'lead').sessionId
|
||||
const forLead = registered.filter(item => item.sessionId === leadSessionId)
|
||||
assert.equal(forLead.length, 5, '绑定保存后应立即安装 5 个部门工具')
|
||||
assert.ok(forLead.some(item => item.name === 'sansheng_dispatch_task'), '丞相必须拿到 sansheng_dispatch_task')
|
||||
assert.equal(forLead.length, TOOL_COUNT, '绑定保存后应立即安装全部部门工具')
|
||||
assert.ok(forLead.some(item => item.name === 'sansheng_requirement_upsert'), '丞相必须拿到需求工具')
|
||||
assert.ok(forLead.some(item => item.name === 'sansheng_workflow_deliver'), '丞相必须拿到交付工具')
|
||||
} finally {
|
||||
teardown()
|
||||
}
|
||||
|
|
@ -67,11 +73,10 @@ test('回归:同一活跃会话实例反复打开只注册一次', async () =>
|
|||
await env.service.enableSeat(id, 'lead')
|
||||
const leadSessionId = seatById(await env.service.project(id), 'lead').sessionId
|
||||
const agent = env.fake.sessions.get(leadSessionId)
|
||||
assert.equal(registered.filter(item => item.sessionId === leadSessionId).length, 5)
|
||||
// 同一 agent 实例再触发两次创建/打开事件,不应重复注册。
|
||||
assert.equal(registered.filter(item => item.sessionId === leadSessionId).length, TOOL_COUNT)
|
||||
emit('agent/created', { agent })
|
||||
emit('agent/created', { agent })
|
||||
assert.equal(registered.filter(item => item.sessionId === leadSessionId).length, 5, '同一实例只注册一次')
|
||||
assert.equal(registered.filter(item => item.sessionId === leadSessionId).length, TOOL_COUNT, '同一实例只注册一次')
|
||||
} finally {
|
||||
teardown()
|
||||
}
|
||||
|
|
@ -86,9 +91,8 @@ test('回归:重绑后旧会话失去该席工具、新会话注册工具,
|
|||
const id = opened.project.id
|
||||
const leadView = await env.service.enableSeat(id, 'lead')
|
||||
const oldSessionId = seatById(leadView, 'lead').sessionId
|
||||
assert.equal(registered.filter(item => item.sessionId === oldSessionId).length, 5)
|
||||
assert.equal(registered.filter(item => item.sessionId === oldSessionId).length, TOOL_COUNT)
|
||||
|
||||
// 模拟宿主会话被删除,再重建到新会话。
|
||||
env.fake.sessions.delete(oldSessionId)
|
||||
await assert.rejects(() => env.service.openSeat(id, 'lead'), error => error.code === 'sansheng/session-missing')
|
||||
const rebuilt = await env.service.rebuildSeat(id, 'lead', { expectedSessionId: oldSessionId })
|
||||
|
|
@ -97,128 +101,72 @@ test('回归:重绑后旧会话失去该席工具、新会话注册工具,
|
|||
const seat = seatById(await env.service.project(id), 'lead')
|
||||
assert.equal(seat.sessionId, newSessionId, '重绑后会话 ID 应稳定为新 ID')
|
||||
assert.deepEqual(seat.previousSessionIds, [oldSessionId])
|
||||
assert.equal(registered.filter(item => item.sessionId === newSessionId).length, 5, '新会话应注册 5 个工具')
|
||||
assert.equal(disposed.filter(item => item.sessionId === oldSessionId).length, 5, '旧会话的工具授权应被撤销')
|
||||
assert.equal(registered.filter(item => item.sessionId === newSessionId).length, TOOL_COUNT, '新会话应注册全部工具')
|
||||
assert.equal(disposed.filter(item => item.sessionId === oldSessionId).length, TOOL_COUNT, '旧会话的工具授权应被撤销')
|
||||
} finally {
|
||||
teardown()
|
||||
}
|
||||
})
|
||||
|
||||
function toolsOf(env) {
|
||||
const defs = createSeatToolDefinitions({ store: env.store, service: env.service })
|
||||
return Object.fromEntries(defs.map(def => [def.name, def]))
|
||||
}
|
||||
|
||||
test('派工失败区分:本席工具未就绪 / 目标部门未开启 / 投递失败', async () => {
|
||||
// 1) 本席工具未就绪:普通会话调用派工
|
||||
{
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/fail-ready', name: '就绪项目' })
|
||||
await env.service.enableSeat(opened.project.id, 'lead')
|
||||
const res = await toolsOf(env).sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: 'x' }, { agent: { id: 'ordinary-x' } })
|
||||
assert.equal(res.ok, false)
|
||||
assert.equal(res.reason, 'tool-not-ready')
|
||||
}
|
||||
// 2) 目标部门未开启:工部创建会话失败
|
||||
{
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/fail-target', name: '未开启项目' })
|
||||
const leadView = await env.service.enableSeat(opened.project.id, 'lead')
|
||||
const leadExec = { agent: env.fake.sessions.get(seatById(leadView, 'lead').sessionId) }
|
||||
env.fake.control.failCreateOrder = env.fake.calls.create.length + 1
|
||||
const res = await toolsOf(env).sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: '写代码' }, leadExec)
|
||||
assert.equal(res.ok, false)
|
||||
assert.equal(res.reason, 'target-seat-unavailable')
|
||||
assert.match(res.error, /工部/)
|
||||
}
|
||||
// 3) 投递失败:工部已绑定,但宿主 prompt 抛错
|
||||
{
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/fail-deliver', name: '投递失败项目' })
|
||||
const leadView = await env.service.enableSeat(opened.project.id, 'lead')
|
||||
await env.service.enableSeat(opened.project.id, 'gongbu')
|
||||
const leadExec = { agent: env.fake.sessions.get(seatById(leadView, 'lead').sessionId) }
|
||||
env.fake.host.sessionController.prompt = async () => { throw new Error('模拟投递失败') }
|
||||
const res = await toolsOf(env).sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: '写代码' }, leadExec)
|
||||
assert.equal(res.ok, false)
|
||||
assert.equal(res.reason, 'delivery-failed')
|
||||
}
|
||||
test('回归:直接派工工具已停用,本席未就绪时仍返回 tool-not-ready', async () => {
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/reg-direct', name: '直接派工项目' })
|
||||
await env.service.enableSeat(opened.project.id, 'lead')
|
||||
const defs = Object.fromEntries(createSeatToolDefinitions({ store: env.store, service: env.service }).map(def => [def.name, def]))
|
||||
const ordinary = await defs.sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: 'x' }, { agent: { id: 'ordinary-x' } })
|
||||
assert.equal(ordinary.ok, false)
|
||||
assert.equal(ordinary.reason, 'tool-not-ready')
|
||||
const leadSessionId = seatById(await env.service.project(opened.project.id), 'lead').sessionId
|
||||
const lead = await defs.sansheng_dispatch_task.execute({ targetSeatId: 'gongbu', title: 'x' }, { agent: env.fake.sessions.get(leadSessionId) })
|
||||
assert.equal(lead.ok, false)
|
||||
assert.equal(lead.reason, 'workflow-required')
|
||||
assert.equal((await env.service.tasks(opened.project.id)).tasks.length, 0)
|
||||
})
|
||||
|
||||
test('端到端:丞相派工落真实工部会话,任务记录/投递会话一致,并区分“收到”与“完成”', async () => {
|
||||
test('回归:通用文件/命令工具受需求门控,六部只在有效批准执行任务中放行', async () => {
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/e2e', name: '端到端项目' })
|
||||
const id = opened.project.id
|
||||
const leadView = await env.service.enableSeat(id, 'lead')
|
||||
const gongView = await env.service.enableSeat(id, 'gongbu')
|
||||
const leadSessionId = seatById(leadView, 'lead').sessionId
|
||||
const gongSessionId = seatById(gongView, 'gongbu').sessionId
|
||||
const tools = toolsOf(env)
|
||||
const leadExec = { agent: env.fake.sessions.get(leadSessionId) }
|
||||
const gongExec = { agent: env.fake.sessions.get(gongSessionId) }
|
||||
|
||||
const res = await tools.sansheng_dispatch_task.execute({
|
||||
targetSeatId: 'gongbu', title: '生成 hello', goal: '生成 hello.txt', requirement: '工部生成 hello.txt 并回真实路径',
|
||||
}, leadExec)
|
||||
assert.equal(res.ok, true)
|
||||
assert.equal(res.delivered, true)
|
||||
assert.equal(res.sessionId, gongSessionId, '派工返回的会话必须是工部绑定会话')
|
||||
|
||||
const task = (await env.service.taskGet(id, res.taskId)).task
|
||||
assert.equal(task.ownerSeatId, 'gongbu')
|
||||
assert.equal(task.sessionId, gongSessionId, '任务记录的目标会话 ID 必须与工部绑定 ID 一致')
|
||||
assert.equal(task.status, 'dispatched', '刚派工只代表“已收到/已投递”,不是完成')
|
||||
|
||||
const delivery = env.fake.calls.prompt.at(-1)
|
||||
assert.equal(delivery.sessionId, gongSessionId, '任务必须投递进工部会话')
|
||||
assert.match(delivery.content[0].text, /生成 hello/)
|
||||
|
||||
// 工部回报完成
|
||||
await tools.sansheng_task_report.execute({
|
||||
taskId: res.taskId, status: 'done', result: 'D:/out/hello.txt 已生成',
|
||||
}, gongExec)
|
||||
const done = (await env.service.taskGet(id, res.taskId)).task
|
||||
assert.equal(done.status, 'done')
|
||||
assert.equal(done.resultSessionId, gongSessionId, '完成结果必须来自工部真实会话')
|
||||
assert.match(done.result, /hello\.txt/)
|
||||
})
|
||||
|
||||
test('回归:注册失败可重试,后续事件补齐缺失工具', async () => {
|
||||
const env = await setupService({ prompt: true })
|
||||
const opened = await env.service.open({ path: '/reg-retry', name: '重试项目' })
|
||||
const leadView = await env.service.enableSeat(opened.project.id, 'lead')
|
||||
const leadSessionId = seatById(leadView, 'lead').sessionId
|
||||
const agent = env.fake.sessions.get(leadSessionId)
|
||||
const registered = []
|
||||
let remainingFailures = 2
|
||||
agent.ctx = {
|
||||
tools: {
|
||||
register(def) {
|
||||
if (def.name === 'sansheng_task_report' && remainingFailures > 0) {
|
||||
remainingFailures -= 1
|
||||
throw new Error('模拟注册失败')
|
||||
}
|
||||
registered.push(def.name)
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
}
|
||||
const listeners = new Map()
|
||||
const ctx = {
|
||||
agents: { list: () => [...env.fake.sessions.values()], get: id => env.fake.sessions.get(id) },
|
||||
on(event, fn) {
|
||||
if (!listeners.has(event)) listeners.set(event, new Set())
|
||||
listeners.get(event).add(fn)
|
||||
return () => listeners.get(event)?.delete(fn)
|
||||
},
|
||||
}
|
||||
const { ctx, guards } = makeEventedCtx(env)
|
||||
const teardown = installSeatTools(ctx, { store: env.store, service: env.service, provisioner: env.provisioner })
|
||||
try {
|
||||
assert.equal(registered.length, 4, '首轮 1 个注册失败,应只装 4 个')
|
||||
// 再触发一次创建事件,缺失的工具应被重试补装
|
||||
for (const fn of [...(listeners.get('agent/created') ?? [])]) fn({ agent })
|
||||
assert.equal(registered.length, 5, '重试后应补齐到 5 个')
|
||||
assert.ok(registered.includes('sansheng_task_report'))
|
||||
const opened = await env.service.open({ path: '/reg-guard', name: '守卫项目' })
|
||||
const id = opened.project.id
|
||||
const leadView = await env.service.enableSeat(id, 'lead')
|
||||
const gongbuView = await env.service.enableSeat(id, 'gongbu')
|
||||
const leadSessionId = seatById(leadView, 'lead').sessionId
|
||||
const gongbuSessionId = seatById(gongbuView, 'gongbu').sessionId
|
||||
const leadGuard = guards.find(item => item.sessionId === leadSessionId)?.guard
|
||||
const gongbuGuard = guards.find(item => item.sessionId === gongbuSessionId)?.guard
|
||||
assert.ok(leadGuard, '丞相会话应安装系统级工具守卫')
|
||||
assert.ok(gongbuGuard, '工部会话应安装系统级工具守卫')
|
||||
assert.match(leadGuard({ name: 'write', arguments: {} }), /丞相.*不能使用 write/)
|
||||
assert.equal(leadGuard({ name: 'read', arguments: {} }), undefined)
|
||||
assert.match(leadGuard({ name: 'subagent', arguments: {} }), /不能使用 subagent/)
|
||||
assert.match(gongbuGuard({ name: 'pwsh', arguments: {} }), /工部当前没有有效的已批准执行任务/)
|
||||
|
||||
await env.store.mutate(state => {
|
||||
const project = state.projects[id]
|
||||
project.requirements.push({
|
||||
id: 'R-900', title: '守卫测试', status: 'published', revision: 1,
|
||||
judgement: 'ready', createdAt: Date.now(), updatedAt: Date.now(),
|
||||
})
|
||||
project.approvals.push({
|
||||
id: 'AP-900', requirementId: 'R-900', requirementRevision: 1,
|
||||
status: 'approved', scope: '创建 guard.txt', approvedBy: 'user', approvedAt: Date.now(),
|
||||
})
|
||||
project.tasks.push({
|
||||
id: 'task-guard-1', kind: 'execution', requirementId: 'R-900', requirementRevision: 1,
|
||||
approvalId: 'AP-900', approvalScope: '创建 guard.txt', ownerSeatId: 'gongbu',
|
||||
sessionId: gongbuSessionId, status: 'dispatched', title: 'guard 测试', stage: 'department_exec',
|
||||
})
|
||||
})
|
||||
assert.equal(gongbuGuard({ name: 'pwsh', arguments: {} }), undefined, '有效批准任务应允许工部执行')
|
||||
assert.equal(gongbuGuard({ name: 'write', arguments: {} }), undefined, '有效批准任务应允许工部写文件')
|
||||
|
||||
await env.store.mutate(state => {
|
||||
const task = state.projects[id].tasks.find(item => item.id === 'task-guard-1')
|
||||
task.status = 'done'
|
||||
})
|
||||
assert.match(gongbuGuard({ name: 'pwsh', arguments: {} }), /工部当前没有有效的已批准执行任务/)
|
||||
} finally {
|
||||
teardown()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { setupService, seatById } from './helpers.js'
|
||||
import { createSeatToolDefinitions, installSeatTools } from '../src/host/tools.js'
|
||||
import { createSeatToolDefinitions } from '../src/host/tools.js'
|
||||
|
||||
async function setupToolProject(opts = {}) {
|
||||
const env = await setupService({ prompt: true, ...opts })
|
||||
|
|
@ -33,245 +33,89 @@ async function setupToolProject(opts = {}) {
|
|||
}
|
||||
}
|
||||
|
||||
test('部门工具:丞相派工落到真实工部会话,原话与共识一起送达', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-dispatch', name: '派工工具项目' })
|
||||
const beforePrompts = env.fake.calls.prompt.length
|
||||
const result = await env.tool('sansheng_dispatch_task').execute({
|
||||
targetSeatId: 'gongbu',
|
||||
title: '生成 Hello World',
|
||||
goal: '创建一个可验证的 Hello World 文件',
|
||||
requirement: '以后称呼我为陛下;工部生成 Hello World,并回真实文件路径',
|
||||
sourceText: '用户原话:以后称呼我为陛下;工部生成 Hello World,并回真实文件路径',
|
||||
}, env.leadExec)
|
||||
|
||||
assert.equal(result.ok, true)
|
||||
assert.equal(result.delivered, true)
|
||||
assert.equal(result.status, 'dispatched')
|
||||
assert.equal(result.sessionId, env.gongSessionId)
|
||||
assert.equal(result.targetLabel, '工部')
|
||||
|
||||
const memory = (await env.service.memory(env.projectId)).memory
|
||||
assert.equal(memory.revision, 2)
|
||||
assert.match(memory.decisions.at(-1).text, /陛下/)
|
||||
assert.equal(memory.decisions.at(-1).type, 'user')
|
||||
assert.ok(memory.sources.some(source => /陛下/.test(source.excerpt)))
|
||||
|
||||
const task = (await env.service.taskGet(env.projectId, result.taskId)).task
|
||||
assert.equal(task.ownerSeatId, 'gongbu')
|
||||
assert.match(task.requirement, /陛下/)
|
||||
assert.equal(task.contextRevision, 2)
|
||||
|
||||
assert.equal(env.fake.calls.prompt.length, beforePrompts + 1)
|
||||
const delivery = env.fake.calls.prompt.at(-1)
|
||||
assert.equal(delivery.sessionId, env.gongSessionId)
|
||||
const text = delivery.content[0].text
|
||||
assert.match(text, /项目共识 v2/)
|
||||
assert.match(text, /不能改动生产数据/)
|
||||
assert.match(text, /用户原话:以后称呼我为陛下/)
|
||||
assert.match(text, /生成 Hello World/)
|
||||
})
|
||||
async function createLegacyTask(env, title = '内部兼容任务') {
|
||||
const created = await env.service.taskCreate(env.projectId, {
|
||||
title,
|
||||
goal: '验证兼容路径',
|
||||
requirement: '由内部流程创建的历史任务',
|
||||
ownerSeatId: 'gongbu',
|
||||
})
|
||||
await env.service.taskDispatch(env.projectId, created.task.id, { force: true })
|
||||
return created.task
|
||||
}
|
||||
|
||||
test('部门工具:真实回报 running/done 可见,丞相不能代替部门报告', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-report', name: '回报工具项目' })
|
||||
const dispatched = await env.tool('sansheng_dispatch_task').execute({
|
||||
targetSeatId: 'gongbu',
|
||||
title: '写 Hello World',
|
||||
goal: '输出文件并验证',
|
||||
requirement: '写一个 Hello World 文件',
|
||||
}, env.leadExec)
|
||||
|
||||
await assert.rejects(
|
||||
() => env.tool('sansheng_task_report').execute({ taskId: dispatched.taskId, status: 'done', result: '丞相代写' }, env.leadExec),
|
||||
/丞相不能代替部门/,
|
||||
)
|
||||
|
||||
const running = await env.tool('sansheng_task_report').execute({ taskId: dispatched.taskId, status: 'running', note: '开始执行' }, env.gongExec)
|
||||
const task = await createLegacyTask(env, '写 Hello World')
|
||||
const leadReport = await env.tool('sansheng_task_report').execute({ taskId: task.id, status: 'done', result: '丞相代写' }, env.leadExec)
|
||||
assert.equal(leadReport.ok, false)
|
||||
assert.equal(leadReport.reason, 'forbidden')
|
||||
assert.match(leadReport.error, /丞相不能代替部门/)
|
||||
const running = await env.tool('sansheng_task_report').execute({ taskId: task.id, status: 'running', note: '开始执行' }, env.gongExec)
|
||||
assert.equal(running.ok, true)
|
||||
assert.equal(running.task.status, 'running')
|
||||
assert.equal(running.task.reportStatus, 'running')
|
||||
|
||||
const done = await env.tool('sansheng_task_report').execute({
|
||||
taskId: dispatched.taskId,
|
||||
taskId: task.id,
|
||||
status: 'done',
|
||||
result: '已生成 D:/out/hello.txt,内容为 Hello World',
|
||||
}, env.gongExec)
|
||||
assert.equal(done.task.status, 'done')
|
||||
assert.match(done.task.result, /D:\/out\/hello\.txt/)
|
||||
assert.ok(done.task.result.includes('D:/out/hello.txt'))
|
||||
assert.equal(done.task.resultSessionId, env.gongSessionId)
|
||||
|
||||
const leadRead = await env.tool('sansheng_task_result').execute({ taskId: dispatched.taskId }, env.leadExec)
|
||||
const leadRead = await env.tool('sansheng_task_result').execute({ taskId: task.id }, env.leadExec)
|
||||
assert.equal(leadRead.task.status, 'done')
|
||||
assert.match(leadRead.task.result, /Hello World/)
|
||||
assert.equal(leadRead.task.resultSessionId, env.gongSessionId)
|
||||
})
|
||||
|
||||
test('部门工具:修改要求会写入最新共识并重新投递到原部门会话', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-revise', name: '改要求项目' })
|
||||
const dispatched = await env.tool('sansheng_dispatch_task').execute({
|
||||
targetSeatId: 'gongbu',
|
||||
title: '生成报告',
|
||||
goal: '第一版',
|
||||
requirement: '叫工部生成第一版报告',
|
||||
}, env.leadExec)
|
||||
|
||||
await env.service.memoryUpdate(env.projectId, { constraints: ['不能改动生产数据', '必须使用新模板'] })
|
||||
const revised = await env.tool('sansheng_task_revise').execute({
|
||||
taskId: dispatched.taskId,
|
||||
goal: '第二版,按新模板',
|
||||
requirement: '不要叫工部了,称呼我为殿下;按新模板重做报告',
|
||||
sourceText: '用户改口:称呼我为殿下;按新模板重做报告',
|
||||
}, env.leadExec)
|
||||
|
||||
assert.equal(revised.ok, true)
|
||||
assert.equal(revised.delivered, true)
|
||||
assert.equal(revised.sessionId, env.gongSessionId)
|
||||
assert.equal(revised.contextRevision, 4)
|
||||
assert.match(revised.requirement, /殿下/)
|
||||
const memory = (await env.service.memory(env.projectId)).memory
|
||||
assert.equal(memory.revision, 4)
|
||||
assert.match(memory.decisions.at(-1).text, /殿下/)
|
||||
|
||||
const delivery = env.fake.calls.prompt.at(-1)
|
||||
assert.equal(delivery.sessionId, env.gongSessionId)
|
||||
assert.match(delivery.content[0].text, /项目共识 v4/)
|
||||
assert.match(delivery.content[0].text, /必须使用新模板/)
|
||||
assert.match(delivery.content[0].text, /称呼我为殿下/)
|
||||
})
|
||||
|
||||
test('部门工具:严格项目隔离,普通会话不能使用', async () => {
|
||||
const a = await setupToolProject({ path: '/tools-a', name: 'A 项目' })
|
||||
const b = await setupToolProject({ path: '/tools-b', name: 'B 项目' })
|
||||
const dispatched = await a.tool('sansheng_dispatch_task').execute({
|
||||
targetSeatId: 'gongbu',
|
||||
title: 'A 项目机密任务',
|
||||
requirement: 'A 项目的要求,不能出现在 B 项目',
|
||||
}, a.leadExec)
|
||||
|
||||
const bList = await b.tool('sansheng_task_list').execute({}, b.leadExec)
|
||||
assert.equal(bList.tasks.length, 0)
|
||||
const bMemory = (await b.service.memory(b.projectId)).memory
|
||||
assert.equal(bMemory.decisions.length, 0)
|
||||
assert.ok(!bMemory.constraints.some(item => /A 项目/.test(item)))
|
||||
|
||||
await assert.rejects(
|
||||
() => b.tool('sansheng_task_result').execute({ taskId: dispatched.taskId }, b.leadExec),
|
||||
/不存在/,
|
||||
)
|
||||
const aList = await a.tool('sansheng_task_list').execute({}, a.leadExec)
|
||||
assert.equal(aList.tasks.length, 1)
|
||||
|
||||
const ordinary = { agent: { id: 'ordinary-session' } }
|
||||
await assert.rejects(
|
||||
() => a.tool('sansheng_task_list').execute({}, ordinary),
|
||||
/十席会话/,
|
||||
)
|
||||
const env = await setupToolProject({ path: '/tools-isolation-a', name: 'A 项目' })
|
||||
const other = await env.service.open({ path: '/tools-isolation-b', name: 'B 项目' })
|
||||
const otherView = await env.service.enableSeat(other.project.id, 'gongbu')
|
||||
const otherSessionId = seatById(otherView, 'gongbu').sessionId
|
||||
const otherExec = { agent: env.fake.sessions.get(otherSessionId) }
|
||||
await createLegacyTask(env, 'A 项目任务')
|
||||
const aList = await env.tool('sansheng_task_list').execute({}, env.gongExec)
|
||||
assert.ok(aList.tasks.every(item => item.title !== 'B 项目任务'))
|
||||
const bList = await env.tool('sansheng_task_list').execute({}, otherExec)
|
||||
assert.equal(bList.tasks.length, 0, 'B 项目看不到 A 项目任务')
|
||||
const ordinary = await env.tool('sansheng_task_list').execute({}, { agent: { id: 'ordinary-session' } })
|
||||
assert.equal(ordinary.ok, false)
|
||||
assert.equal(ordinary.reason, 'tool-not-ready')
|
||||
})
|
||||
|
||||
test('部门工具:取消后的迟到结果保留为 late,不篡改取消状态', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-late', name: '迟到项目' })
|
||||
const dispatched = await env.tool('sansheng_dispatch_task').execute({
|
||||
targetSeatId: 'gongbu',
|
||||
title: '可能迟到的任务',
|
||||
requirement: '做一件事',
|
||||
}, env.leadExec)
|
||||
await env.service.taskCancel(env.projectId, dispatched.taskId)
|
||||
const lateRunning = await env.tool('sansheng_task_report').execute({
|
||||
taskId: dispatched.taskId,
|
||||
status: 'running',
|
||||
note: '取消后还在跑',
|
||||
}, env.gongExec)
|
||||
assert.equal(lateRunning.task.status, 'cancelled')
|
||||
assert.equal(lateRunning.task.reportStatus, 'late')
|
||||
const task = await createLegacyTask(env, '会被取消的任务')
|
||||
await env.service.taskCancel(env.projectId, task.id)
|
||||
const late = await env.tool('sansheng_task_report').execute({
|
||||
taskId: dispatched.taskId,
|
||||
taskId: task.id,
|
||||
status: 'done',
|
||||
result: '取消后仍完成了,结果保留',
|
||||
result: '取消后才返回的真实结果',
|
||||
}, env.gongExec)
|
||||
assert.equal(late.ok, true)
|
||||
assert.equal(late.late, true)
|
||||
assert.equal(late.task.status, 'cancelled')
|
||||
assert.match(late.task.result, /取消后才返回/)
|
||||
assert.equal(late.task.reportStatus, 'late')
|
||||
assert.match(late.task.result, /取消后仍完成/)
|
||||
const leadRead = await env.tool('sansheng_task_result').execute({ taskId: dispatched.taskId }, env.leadExec)
|
||||
assert.equal(leadRead.task.reportStatus, 'late')
|
||||
})
|
||||
|
||||
test('部门工具:只注册到已绑定席位,新席创建后按需补装', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-register', name: '注册项目' })
|
||||
const registered = []
|
||||
const listeners = {}
|
||||
const attach = agent => {
|
||||
if (!agent) return
|
||||
agent.ctx = { tools: { register(def) { registered.push({ sessionId: agent.id, name: def.name }); return () => {} } } }
|
||||
}
|
||||
attach(env.fake.sessions.get(env.leadSessionId))
|
||||
attach(env.fake.sessions.get(env.gongSessionId))
|
||||
const ordinary = env.fake.addSession('ordinary-register')
|
||||
attach(ordinary)
|
||||
const ctx = {
|
||||
agents: { list: () => [...env.fake.sessions.values()] },
|
||||
on(event, fn) { listeners[event] = fn; return () => {} },
|
||||
}
|
||||
installSeatTools(ctx, { store: env.store, service: env.service })
|
||||
assert.equal(registered.filter(item => item.sessionId === env.leadSessionId).length, 5)
|
||||
assert.equal(registered.filter(item => item.sessionId === env.gongSessionId).length, 5)
|
||||
assert.equal(registered.filter(item => item.sessionId === 'ordinary-register').length, 0)
|
||||
|
||||
const libuView = await env.service.enableSeat(env.projectId, 'libu')
|
||||
const libuSessionId = seatById(libuView, 'libu').sessionId
|
||||
const libuAgent = env.fake.sessions.get(libuSessionId)
|
||||
attach(libuAgent)
|
||||
listeners['agent/created']({ agent: libuAgent })
|
||||
assert.equal(registered.filter(item => item.sessionId === libuSessionId).length, 5)
|
||||
test('部门工具:任务改要求已停用,不能绕过需求 revision 流程', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-revise', name: '改要求项目' })
|
||||
const task = await createLegacyTask(env, '不能被改要求的任务')
|
||||
const before = (await env.service.memory(env.projectId)).memory.revision
|
||||
const out = await env.tool('sansheng_task_revise').execute({ taskId: task.id, requirement: '第二版要求', sourceText: '用户改口' }, env.leadExec)
|
||||
assert.equal(out.ok, false)
|
||||
assert.equal(out.reason, 'workflow-required')
|
||||
const after = (await env.service.memory(env.projectId)).memory.revision
|
||||
assert.equal(after, before)
|
||||
assert.equal((await env.service.taskGet(env.projectId, task.id)).task.requirement, '由内部流程创建的历史任务')
|
||||
})
|
||||
|
||||
test('部门工具:按 agent.session.id 匹配席位,不按 agent.id 误判', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-session-id', name: '会话标识项目' })
|
||||
const registered = []
|
||||
const runtimeAgent = {
|
||||
id: 'agent-runtime-lead',
|
||||
session: { id: env.leadSessionId },
|
||||
ctx: {
|
||||
tools: {
|
||||
register(def) {
|
||||
registered.push(def.name)
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
const ctx = { agents: { list: () => [runtimeAgent] }, on() { return () => {} } }
|
||||
installSeatTools(ctx, { store: env.store, service: env.service })
|
||||
assert.equal(registered.length, 5)
|
||||
})
|
||||
|
||||
test('部门工具:执行时优先用 agent.session.id 定位席位', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-exec-session', name: '执行标识项目' })
|
||||
const exec = { agent: { id: 'runtime-agent-lead', session: { id: env.leadSessionId } } }
|
||||
const list = await env.tool('sansheng_task_list').execute({}, exec)
|
||||
assert.equal(list.ok, true)
|
||||
assert.equal(list.tasks.length, 0)
|
||||
})
|
||||
|
||||
test('部门工具:已完成任务不能原地改要求,应新建任务', async () => {
|
||||
const env = await setupToolProject({ path: '/tools-revise-done', name: '完成改要求项目' })
|
||||
const dispatched = await env.tool('sansheng_dispatch_task').execute({
|
||||
targetSeatId: 'gongbu',
|
||||
title: '已完成的交付',
|
||||
requirement: '第一版要求',
|
||||
}, env.leadExec)
|
||||
await env.tool('sansheng_task_report').execute({
|
||||
taskId: dispatched.taskId,
|
||||
status: 'done',
|
||||
result: '真实结果:文件已生成',
|
||||
}, env.gongExec)
|
||||
const before = (await env.service.memory(env.projectId)).memory.revision
|
||||
await assert.rejects(
|
||||
() => env.tool('sansheng_task_revise').execute({ taskId: dispatched.taskId, requirement: '第二版要求', sourceText: '用户改口:第二版要求' }, env.leadExec),
|
||||
/新建任务/,
|
||||
)
|
||||
const after = (await env.service.memory(env.projectId)).memory.revision
|
||||
assert.equal(after, before)
|
||||
const task = (await env.service.taskGet(env.projectId, dispatched.taskId)).task
|
||||
assert.equal(task.status, 'done')
|
||||
assert.match(task.result, /真实结果/)
|
||||
const env = await setupToolProject({ path: '/tools-session-id', name: '会话匹配项目' })
|
||||
const fakeAgent = { id: 'not-a-seat', session: { id: env.gongSessionId, deriveMessages: () => [] } }
|
||||
const out = await env.tool('sansheng_task_list').execute({}, { agent: fakeAgent })
|
||||
assert.equal(out.ok, true)
|
||||
assert.equal(out.projectId, env.projectId)
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in New Issue