Package-root snapshot for v1.1.0 (216a750)

This commit is contained in:
qyh15 2026-11-25 19:15:23 +08:00
parent b464496f72
commit 3b3c8fe75d
23 changed files with 6300 additions and 2281 deletions

View File

@ -1,4 +1,4 @@
# 三省六部(dsh-sansheng)· v1.0.0
# 三省六部(dsh-sansheng)· v1.1.0
在 DSH 里为每个项目提供固定的十席角色(丞相、中书、门下、尚书、吏部、户部、礼部、兵部、刑部、工部),
每席绑定一个独立的原生 root Session,模型与补充说明按项目独立保存。中间复用宿主原生会话,不替换聊天引擎。
@ -14,9 +14,16 @@
- 派工工具随席位绑定即时注册:新建、恢复、重建后同一次 DSH 启动内即可派工;重新绑定后旧会话失去该席位工具权限。
- 派工失败明确区分「本席派工工具未就绪」「目标部门未开启」「任务投递失败」,以项目真实席位绑定和会话 ID 为准。
- 尚书可按需汇总项目真实任务与结果,明确区分「已派工/已收到」和「已完成」,不拦截丞相直接派工。
- 丞相需求澄清(Grill Me):仅在存在关键歧义、冲突或缺失时自动加载 `grilling` skill 追问;代码解释、状态查询、普通讨论和已足够明确的需求不触发。追问结果回写原 `R-xxx` 并递增 revision,保留 `missingInfo`;不创建任务、不派工、不生成批准凭证。
**本包尚未安装到用户的日常 DSH profile,也未改动日常 DSH 配置。**
## Grill Me 技能依赖
- 丞相自动追问使用 `grilling` skill;`grill-me` 是用户手动入口,正文只转调 `grilling`。
- 上游 `grill-me` 带 `disable-model-invocation: true`,DSH 会把它从模型目录和 `skill` 工具中排除,所以模型侧自动加载的是 `grilling`,不是 `grill-me`。
- 本仓库根目录 `.dsh/skills/` 保留两份技能副本(MIT,来源:mattpocock/skills);用户级 `~/.dsh/skills/` 已安装扁平文件 `grilling.md` 与 `grill-me.md`,供所有项目加载。技能缺失时丞相必须明确报告,不得伪造调用。
## 目录
- `index.js` — 宿主插件入口(`name` / `inject` / `apply`)。

3357
client.js

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "dsh-sansheng-liubu",
"version": "1.0.0",
"version": "1.1.0",
"description": "三省六部:每个项目固定十席角色与独立会话的 DSH 插件(第一版)。",
"keywords": [
"dsh-plugin",

File diff suppressed because it is too large Load Diff

View File

@ -1,136 +1,723 @@
// 三省六部工作台样式:白蓝主题,自带深色适配。
// 所有选择器以 .ssw- 前缀隔离,避免污染宿主样式;变量参考 preview/index.html。
// 不依赖任何构建工具,作为普通字符串导出,由入口注入 <style>。
// 三省六部工作台样式(v2):设计稿配色 / 排版 + 宿主接线样式。
// 由 preview/workbench-v2.html 的设计 CSS 生成,使用原生 CSS 嵌套把整张表限制在 .ssv2 作用域内。
export const CSS = `
.ssw-scope{--ssw-bg:#ffffff;--ssw-side:#f8f9fa;--ssw-rail:#f8fafc;--ssw-card:#ffffff;--ssw-line:#e3e8ef;--ssw-strong:#c7d8f5;--ssw-ink:#0f172a;--ssw-muted:#667085;--ssw-faint:#98a2b3;--ssw-blue:#4263eb;--ssw-wash:#eef2ff;--ssw-frame:#3b82f6;--ssw-wire:#c9d6ea;--ssw-danger:#dc2626;--ssw-ok:#16a34a;box-sizing:border-box;color:var(--ssw-ink);font-family:Inter,"Segoe UI","Microsoft YaHei",sans-serif;font-size:13px;line-height:1.5}
.ssw-scope *,.ssw-scope *::before,.ssw-scope *::after{box-sizing:border-box}
.ssw-scope :where(button){font:inherit;color:inherit;background:transparent;border:0;cursor:pointer}
.ssw-scope button:disabled{cursor:default;opacity:.55}
.ssw-scope :focus-visible{outline:2px solid var(--ssw-blue);outline-offset:2px}
body[data-ds-dark-theme] .ssw-scope,html[data-theme=dark] .ssw-scope,.ssw-scope[data-ssw-theme=dark]{--ssw-bg:#14171c;--ssw-side:#171b21;--ssw-rail:#161a20;--ssw-card:#1e232b;--ssw-line:#2c333d;--ssw-strong:#3b4a63;--ssw-frame:#6ea8ff;--ssw-ink:#e6ebf2;--ssw-muted:#a9b4c2;--ssw-faint:#7b8797;--ssw-blue:#6ea8ff;--ssw-wash:#1d2b40;--ssw-wire:#3a4350;--ssw-danger:#f87171;--ssw-ok:#4ade80}
.ssw-float{position:fixed;right:14px;bottom:70px;z-index:2147483000;width:min(374px,calc(100vw - 28px));max-height:calc(100vh - 96px);display:flex;flex-direction:column;background:#ffffff;border:1px solid #e3e8ef;border-radius:12px;box-shadow:0 18px 50px -12px rgba(16,24,40,.28),0 4px 12px -2px rgba(16,24,40,.12);overflow:hidden}
body[data-ds-dark-theme] .ssw-float,html[data-theme=dark] .ssw-float{background:#161a20;border-color:#2c333d}
.ssw-root{container-type:inline-size;display:flex;flex-direction:column;min-height:0;height:100%;overflow:auto;background:var(--ssw-rail);color:var(--ssw-ink)}
.ssw-head{flex:none;height:52px;display:flex;align-items:center;gap:8px;padding:0 16px;border-bottom:1px solid var(--ssw-line);background:var(--ssw-card)}
.ssw-head svg{width:18px;height:18px;color:var(--ssw-muted)}
.ssw-head-title{font-size:13px;font-weight:600}
.ssw-icon-btn{margin-left:auto;display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:6px;color:var(--ssw-muted)}
.ssw-icon-btn:hover{background:var(--ssw-wash);color:var(--ssw-blue)}
.ssw-project{padding:22px 20px 0}
.ssw-project-line{display:flex;align-items:center;justify-content:space-between;margin-bottom:5px}
.ssw-eyebrow{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--ssw-muted)}
.ssw-eyebrow svg{width:14px;height:14px}
.ssw-count{font-size:10px;color:var(--ssw-faint)}
.ssw-project-title{font-size:21px;font-weight:650;letter-spacing:.5px;margin:4px 0 16px}
.ssw-enable{margin:0 16px 4px;padding:12px;border:1px solid var(--ssw-strong);background:var(--ssw-wash);border-radius:10px}
.ssw-enable-note{margin:0 0 10px;font-size:12px;color:var(--ssw-muted);line-height:1.7}
.ssw-primary{min-height:36px;background:var(--ssw-blue);color:#ffffff;border-radius:7px;padding:8px 13px;font-size:12px;font-weight:500}
.ssw-primary:hover{filter:brightness(1.05)}
.ssw-tree{padding:24px 20px 4px;position:relative}
.ssw-lead{width:168px;margin:0 auto;position:relative}
.ssw-lead::after{content:none}
.ssw-sansheng{position:relative;margin-top:24px}
.ssw-trio{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px}
.ssw-seat{position:relative;width:100%;display:flex;flex-direction:column;gap:6px;padding:14px 12px 12px;border:1px solid var(--ssw-line);border-radius:12px;background:var(--ssw-card);text-align:left;min-height:80px;box-shadow:0 1px 2px rgba(16,24,40,.04);transition:border-color .15s,box-shadow .15s,transform .15s}
.ssw-seat:hover{border-color:var(--ssw-blue);transform:translateY(-1px);box-shadow:0 3px 8px rgba(16,24,40,.06)}
.ssw-seat[aria-pressed=true]{border-color:var(--ssw-blue);background:var(--ssw-wash);box-shadow:0 0 0 2px rgba(59,130,246,.12)}
.ssw-lead .ssw-seat{min-height:84px}
.ssw-role-top{display:flex;align-items:center;justify-content:space-between;gap:6px}
.ssw-role-name{font-size:14px;font-weight:600;letter-spacing:2px}
.ssw-role-duty{font-size:11px;color:var(--ssw-muted);line-height:1.5}
.ssw-dot{flex:none;width:6px;height:6px;border-radius:50%;border:1px solid var(--ssw-faint);background:transparent}
.ssw-dot[data-status=bound]{background:var(--ssw-ok);border-color:var(--ssw-ok)}
.ssw-dot[data-status=failed],.ssw-dot[data-status=missing]{background:var(--ssw-danger);border-color:var(--ssw-danger)}
.ssw-dot[data-status=creating]{background:var(--ssw-blue);border-color:var(--ssw-blue)}
.ssw-ministries{position:relative;margin-top:18px}
.ssw-group-label{display:flex;align-items:center;gap:10px;margin:0 2px 8px;font-size:11px;font-weight:600;letter-spacing:.5px;color:var(--ssw-muted)}
.ssw-six{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
.ssw-six .ssw-seat{min-height:76px;padding:12px}
.ssw-report{padding:0 20px;margin-top:4px}
.ssw-report-toggle{font-size:12px;color:var(--ssw-blue);padding:7px 2px;font-weight:500}
.ssw-report-list{display:flex;flex-direction:column;gap:8px;margin-top:4px}
.ssw-report-item{border:1px solid var(--ssw-line);border-radius:9px;padding:9px 11px;background:var(--ssw-card)}
.ssw-report-head{display:flex;gap:8px;align-items:baseline}
.ssw-report-head strong{font-size:13px;letter-spacing:1px}
.ssw-report-head span{font-size:10px;color:var(--ssw-muted)}
.ssw-report-model{margin:4px 0 0;font-size:11px;color:var(--ssw-blue);letter-spacing:.2px}
.ssw-report-text{margin:4px 0 0;font-size:12px;line-height:1.7;color:var(--ssw-muted)}
.ssw-current{margin:14px 20px 0;padding:16px;border:1px solid var(--ssw-line);border-radius:11px;background:var(--ssw-card)}
.ssw-current-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:9px}
.ssw-current-name{font-size:13px;font-weight:600}
.ssw-current-label{font-size:10px;color:var(--ssw-faint)}
.ssw-current-text{margin:0;font-size:12px;line-height:1.8;color:var(--ssw-muted)}
.ssw-config{margin:10px 20px 20px;border:1px solid var(--ssw-line);border-radius:10px;background:var(--ssw-card);overflow:hidden}
.ssw-config-toggle{display:flex;align-items:center;gap:8px;width:100%;padding:12px 13px;font-size:12px;color:var(--ssw-ink)}
.ssw-config-toggle svg{width:15px;height:15px;color:var(--ssw-muted)}
.ssw-chevron{margin-left:auto;transition:transform .2s}
.ssw-config-toggle[aria-expanded=true] .ssw-chevron{transform:rotate(180deg)}
.ssw-config-body{padding:0 13px 14px}
.ssw-label{display:block;font-size:11px;color:var(--ssw-muted);margin:12px 0 6px}
.ssw-field{width:100%;border:1px solid var(--ssw-line);background:var(--ssw-bg);color:var(--ssw-ink);border-radius:6px;padding:8px;font-size:12px;line-height:1.5}
.ssw-textarea{resize:vertical;min-height:84px;font-family:inherit}
.ssw-scope-note{margin:10px 0;font-size:10px;line-height:1.6;color:var(--ssw-faint)}
.ssw-save-row{display:flex;align-items:center;gap:10px}
.ssw-save-status{font-size:10px;color:var(--ssw-muted)}
.ssw-notice{margin:12px 16px 16px;font-size:11px;color:var(--ssw-muted)}
.ssw-error{margin:12px 16px 16px;font-size:11px;color:var(--ssw-danger)}
.ssw-loading,.ssw-empty{padding:36px 20px;text-align:center;font-size:12px;color:var(--ssw-muted)}
.ssw-empty .ssw-primary{margin-top:12px}
/* 导航行图标:尺寸/颜色全部跟随宿主导航行,不自己画背景,避免比同类导航项突兀。 */
.ssw-nav-hit{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;color:inherit;cursor:pointer}
.ssw-nav-hit svg{width:16px;height:16px;flex:none;display:block}
.ssw-hint{margin:6px 0 0;font-size:11px;color:var(--ssw-faint)}
.ssw-current-actions{margin-top:10px;display:flex;gap:8px}
.ssw-inline-bar{flex:none;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 12px;border-bottom:1px solid var(--ssw-line);background:var(--ssw-card);font-size:12px;color:var(--ssw-muted)}
.ssw-link{color:var(--ssw-blue);font-size:12px;padding:2px 4px}
@media (prefers-reduced-motion:reduce){.ssw-scope *{transition:none!important}}
.ssw-tabs{display:flex;gap:6px;margin:0 20px;padding:4px;border:1px solid var(--ssw-line);border-radius:12px;background:var(--ssw-side)}
.ssw-tab{flex:1;display:flex;align-items:center;justify-content:center;gap:6px;padding:7px 6px;border-radius:6px;font-size:12px;color:var(--ssw-muted)}
.ssw-tab.is-active{background:var(--ssw-card);color:var(--ssw-blue);font-weight:600;box-shadow:0 1px 2px rgba(16,24,40,.06)}
.ssw-tab-count{font-size:10px;color:var(--ssw-faint)}
.ssw-page{padding:12px 16px 0}
.ssw-page-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
.ssw-page-head strong{font-size:13px}
.ssw-list{display:flex;flex-direction:column;gap:8px}
.ssw-row{border:1px solid var(--ssw-line);border-radius:9px;padding:9px 11px;background:var(--ssw-card)}
.ssw-row-top{display:flex;align-items:center;justify-content:space-between;gap:8px}
.ssw-row-title{font-size:13px}
.ssw-row-meta{margin:4px 0 0;font-size:11px;color:var(--ssw-muted)}
.ssw-row-note{margin:4px 0 0;font-size:10px;color:var(--ssw-faint)}
.ssw-row-result{margin:4px 0 0;font-size:11px;color:var(--ssw-ok);word-break:break-word}
.ssw-row-actions{display:flex;gap:10px;margin-top:6px}
.ssw-link{color:var(--ssw-blue);font-size:12px;padding:2px 2px}
.ssw-link-muted{color:var(--ssw-muted)}
.ssw-badge{font-size:10px;padding:2px 6px;border-radius:999px;background:var(--ssw-wash);color:var(--ssw-blue)}
.ssw-badge[data-status=running]{background:rgba(37,99,235,.12);color:var(--ssw-blue)}
.ssw-badge[data-status=done]{background:rgba(22,163,74,.12);color:var(--ssw-ok)}
.ssw-badge[data-status=cancelled]{background:rgba(107,114,128,.14);color:var(--ssw-muted)}
.ssw-badge[data-status=failed]{background:rgba(220,38,38,.12);color:var(--ssw-danger)}
.ssw-form{margin-bottom:12px;padding:10px;border:1px solid var(--ssw-line);border-radius:9px;background:var(--ssw-side)}
.ssw-empty-line{margin:10px 0;font-size:12px;color:var(--ssw-faint)}
.ssw-project-line{align-items:baseline;margin-bottom:10px}
.ssw-project-title{margin:0}
.ssw-tab-body{height:100%;min-height:0;display:flex;flex-direction:column}
.ssw-tab-body .ssw-root{flex:1;min-height:0}
.ssw-tab-title{font-size:13px}
.ssw-group-label::after{content:"";height:1px;background:var(--ssw-line);flex:1}
.ssw-role-top{width:100%}
.ssw-tab-count{padding:1px 5px;border-radius:5px;background:var(--ssw-rail)}
.ssw-current-name{font-size:15px;letter-spacing:1px}
.ssw-current-label{padding:3px 7px;border-radius:5px;background:var(--ssw-side)}
.ssw-config-toggle:hover{background:var(--ssw-side)}
/* 按工作台本身的宽度适配:宽屏居中,右侧窄栏保持紧凑。 */
.ssw-root > :is(.ssw-project,.ssw-tree,.ssw-report,.ssw-page){width:100%;max-width:720px;align-self:center;flex-shrink:0}
.ssw-root > :is(.ssw-tabs,.ssw-current,.ssw-config,.ssw-enable,.ssw-notice,.ssw-error){width:calc(100% - 40px);max-width:680px;margin-left:auto;margin-right:auto;flex-shrink:0}
.ssw-enable{margin-top:12px}
@container(max-width:380px){.ssw-root > :is(.ssw-tabs,.ssw-current,.ssw-config,.ssw-enable,.ssw-notice,.ssw-error){width:calc(100% - 24px);margin-left:auto;margin-right:auto}
.ssw-project{padding:16px 12px 0}.ssw-tabs{margin:0 12px}.ssw-tree{padding:20px 12px 4px}.ssw-current{margin:12px 12px 0}.ssw-config{margin:10px 12px 16px}.ssw-report{padding:0 12px}.ssw-trio,.ssw-six{gap:6px}.ssw-seat,.ssw-six .ssw-seat{padding:10px 8px}.ssw-role-duty{font-size:10px}}
/* 窄栏隐藏职责小字,避免被卡片宽度截断 */
@container (max-width:420px){
.ssw-role-duty{display:none}
.ssw-seat{min-height:52px;padding:10px 9px;gap:0}
.ssw-six{grid-template-columns:repeat(2,minmax(0,1fr))}
.ssw-six .ssw-seat{min-height:50px;padding:10px 9px}
export const CSS = `.ssv2{
/* ============ shadcn 式干净后台:平整、利落、高对比 ============
侧边栏 + 统计卡 + 表格的标准后台骨架,全页统一平整处理:
白/浅灰底、1px 细边框、小圆角、无凸凹阴影、无拟物。
钴蓝只给选中态、主按钮与关键数字,其余用中性灰阶分层。 */
& {
color-scheme: light dark;
--bg: #ffffff;
--sidebar-bg: #fafafa;
--panel: #ffffff;
--panel-line: #e4e4e7;
--muted-bg: #f4f4f5;
--ink: #09090b;
--ink-2: #3f3f46;
--muted: #71717a;
--cobalt: #1e40d8;
--cobalt-ink: #17319f;
--cobalt-soft: rgba(30, 64, 216, .08);
--on-accent: #ffffff;
--ok: #2e7d4f;
--warn: #b06a12;
--bad: #b3372c;
--radius-panel: 8px;
--radius-control: 8px;
--font-ui: "Noto Sans SC", "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
--font-seat: "Noto Serif SC", "Songti SC", serif;
--font-num: "IBM Plex Mono", ui-monospace, "SF Mono", monospace;
}
`
@media (prefers-color-scheme: dark) {
& {
--bg: #09090b;
--sidebar-bg: #0c0c0e;
--panel: #18181b;
--panel-line: #27272a;
--muted-bg: #27272a;
--ink: #fafafa;
--ink-2: #d4d4d8;
--muted: #a1a1aa;
--cobalt: #829cff;
--cobalt-ink: #a9bcff;
--cobalt-soft: rgba(130, 156, 255, .13);
--on-accent: #141a38;
--ok: #5cb582;
--warn: #d99a45;
--bad: #e0705f;
}
}
* { box-sizing: border-box; }
& { height: 100%; }
& {
margin: 0;
background: var(--bg);
color: var(--ink);
font-family: var(--font-ui);
font-size: 14px;
line-height: 1.55;
-webkit-font-smoothing: antialiased;
}
button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
button, [role="button"], select, summary, input:not([type="checkbox"], [type="radio"]) { min-height: 2.25rem; }
:focus-visible { outline: 2px solid var(--cobalt); outline-offset: 2px; }
.num { font-family: var(--font-num); font-variant-numeric: tabular-nums; }
/* ================= 布局:工作台占满整页(无文件树栏) ================= */
.shell { display: block; min-height: 100vh; }
/* ---------- 面板头部与横向标签页(都在内容区同一平面上) ---------- */
.panel-top { display: flex; align-items: center; gap: 18px; flex-wrap: wrap; }
.brand { display: flex; align-items: baseline; gap: 9px; }
.brand .seal {
font-family: var(--font-seat); font-weight: 900; font-size: 21px; letter-spacing: .06em;
}
.brand .sub { font-size: 11px; color: var(--muted); letter-spacing: .14em; }
.proj {
margin-left: auto; text-align: left;
display: flex; align-items: center; gap: 10px;
padding: 8px 12px; border-radius: var(--radius-control);
background: var(--panel); border: 1px solid var(--panel-line);
}
.proj:hover { background: var(--muted-bg); }
.proj .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ok); flex: 0 0 auto; }
.proj .name { font-weight: 700; font-size: 13.5px; }
.proj .meta { font-size: 11.5px; color: var(--muted); }
.proj svg { margin-left: 4px; color: var(--muted); flex: 0 0 auto; }
/* 横向标签页:灰槽轨道 + 白色选中块,与分段控件同一语言 */
.tabs {
margin-top: 18px; display: flex; flex-wrap: wrap; gap: 2px; padding: 3px;
border-radius: var(--radius-control); background: var(--muted-bg);
width: fit-content; max-width: 100%;
}
.tabs a {
display: inline-flex; align-items: center; gap: 8px;
padding: 6px 15px; border-radius: 6px;
color: var(--ink-2); text-decoration: none; font-weight: 500; font-size: 13.5px;
min-height: 36px; white-space: nowrap;
}
.tabs a svg { flex: 0 0 auto; opacity: .75; }
.tabs a:hover { color: var(--ink); }
.tabs a.on {
color: var(--cobalt-ink); font-weight: 700;
background: var(--panel); border: 1px solid var(--panel-line); padding: 5px 14px;
}
.tabs a.on svg { opacity: 1; color: var(--cobalt); }
/* ---------- 主区 ---------- */
.main { min-width: 0; padding: 24px 28px 40px; width: 100%; }
/* ---------- 页签页面:一次只显示一页 ---------- */
.page[hidden] { display: none; }
.page > .topbar { margin-top: 20px; }
tbody tr.clickable { cursor: pointer; }
.settings-stack { display: flex; flex-direction: column; gap: 20px; margin-top: 20px; }
.topbar { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
.topbar h1 { font-size: 22px; margin: 0; font-weight: 700; letter-spacing: .01em; }
.topbar .date { color: var(--muted); font-size: 13px; }
.topbar .spacer { flex: 1; }
.search {
display: flex; align-items: center; gap: 8px;
border-radius: var(--radius-control); border: 1px solid var(--panel-line); background: var(--panel);
padding: 0 12px; flex: 0 1 250px; min-width: 0;
}
.search:focus-within { border-color: var(--cobalt); }
.search svg { color: var(--muted); flex: 0 0 auto; }
.search input { border: 0; background: none; outline: none; width: 100%; color: var(--ink); font: inherit; font-size: 13.5px; }
.search input::placeholder { color: var(--muted); }
.btn {
display: inline-flex; align-items: center; gap: 7px;
padding: 8px 16px; border-radius: var(--radius-control); font-weight: 500;
background: var(--panel); border: 1px solid var(--panel-line);
white-space: nowrap;
}
.btn:hover { background: var(--muted-bg); }
.btn.primary { background: var(--cobalt); border-color: var(--cobalt); color: var(--on-accent); font-weight: 700; }
.btn.primary:hover { background: var(--cobalt-ink); border-color: var(--cobalt-ink); }
/* 页头主按钮位:丞相(派工经丞相下达,点开即向丞相交代任务) */
.btn-cx { gap: 9px; }
.btn-cx .cx-name { font-family: var(--font-seat); font-weight: 900; font-size: 16px; letter-spacing: .05em; line-height: 1; }
.btn-cx .cx-dot { width: 8px; height: 8px; border-radius: 50%; background: #4ade80; box-shadow: 0 0 0 3px rgba(255,255,255,.22); flex: 0 0 auto; }
.btn-cx .cx-dot.idle { background: #d4d4d8; box-shadow: none; }
.btn-cx .cx-state { font-size: 12px; font-weight: 500; opacity: .88; }
.btn-cx.selected { box-shadow: 0 0 0 2px var(--bg), 0 0 0 4px var(--cobalt); }
.ws-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-top: 16px; }
.ws-actions .btn { padding: 7px 16px; }
.modal input[type="text"] {
width: 100%; border: 1px solid var(--panel-line); border-radius: var(--radius-control);
background: var(--panel); color: var(--ink); font: inherit; font-size: 13.5px;
padding: 8px 10px;
}
.modal input[type="text"]:focus { border-color: var(--cobalt); outline: none; }
/* ---------- 统计卡(骨架:平、脆、白) ---------- */
.stats {
display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1.25fr); gap: 16px;
margin-top: 22px;
}
.stat {
background: var(--panel); border: 1px solid var(--panel-line);
border-radius: var(--radius-panel); padding: 16px 18px 14px;
}
.stat-link { display: block; width: 100%; text-align: left; font: inherit; color: inherit; cursor: pointer; }
.stat-link:hover { border-color: var(--cobalt); background: var(--cobalt-soft); }
.stat-link:focus-visible { outline: 2px solid var(--cobalt); outline-offset: 2px; }
.stat .label { font-size: 12.5px; color: var(--muted); display: flex; align-items: center; gap: 7px; }
.stat .big { font-family: var(--font-num); font-size: 30px; font-weight: 600; line-height: 1.25; margin-top: 2px; }
.stat .big .unit { font-size: 14px; color: var(--muted); font-weight: 400; }
.stat .big em { font-style: normal; color: var(--cobalt); }
.stat .foot { font-size: 12px; color: var(--muted); margin-top: 2px; }
.stat .foot b { color: var(--ink-2); font-weight: 500; }
.spark { display: block; margin-top: 6px; }
/* ---------- 内容网格 ---------- */
.grid {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 368px); gap: 20px;
margin-top: 20px; align-items: start;
}
.panel-head { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 14px; }
.panel-head h2 { font-size: 16px; margin: 0; font-weight: 700; }
.panel-head .hint { font-size: 12.5px; color: var(--muted); }
/* 分段控件:平底灰槽 + 白色选中块 */
.seg {
margin-left: auto; display: inline-flex; gap: 2px; padding: 3px;
border-radius: var(--radius-control); background: var(--muted-bg);
}
.seg button { padding: 5px 14px; border-radius: 6px; font-size: 13px; color: var(--ink-2); min-height: 32px; }
.seg button:hover { color: var(--ink); }
.seg button.on { background: var(--panel); border: 1px solid var(--panel-line); color: var(--ink); font-weight: 700; padding: 4px 13px; }
/* ---------- 席位谱系:紧凑对齐 · 宽3排 / 中4排 / 窄5排 ----------
三省与六部共用一个整宽块:不再居中定宽 760px(宽屏下两边大片留白),
改为撑满内容区、与上方统计卡和下方表格左右齐平,两排总宽仍相等、上下对齐成块。
所有列宽一律 minmax(0, 1fr):可随容器一路流式收缩。
三省恒为一排:尚书居中,中书、门下贴其两侧;六部宽屏 6 列、中屏 3×2、窄屏 2×3。 */
.org-rows {
--tree-line: #c6c6cd; padding-top: 2px;
--ss-gap: 14px;
--lb-gap: 10px;
max-width: none; margin: 0; width: 100%; min-width: 0;
/* 谱系块自身成为容器:六部排数按本块的实际宽度决定(容器查询),
不再只看视口——外壳/分栏让呈现宽度与视口不一致时,视口断点永远等不到。 */
container-type: inline-size;
container-name: orgtree;
}
@media (prefers-color-scheme: dark) { .org-rows { --tree-line: #3d3d44; } }
.org-row { display: grid; gap: var(--lb-gap); min-width: 0; }
.org-row-1 { grid-template-columns: minmax(0, 1fr); }
.org-row-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--ss-gap); }
.org-row-6 { grid-template-columns: repeat(6, minmax(0, 1fr)); }
.org-cell { display: flex; justify-content: center; min-width: 0; }
.org-row-1 .node { width: min(248px, 100%); }
.org-row-3 .node { width: 100%; max-width: none; padding: 15px 18px 13px; }
.org-row-3 .node-name { font-size: 24px; }
.org-row-3 .node-role { font-size: 12.5px; }
.org-row-3 .node-task { font-size: 13px; }
.org-row-3 .node-model { font-size: 12.5px; }
.org-row-6 .node { width: 100%; max-width: none; }
/* 六部节点:撑满整宽后每席约 200px+,字号回到正常档,文字不再截断 */
.org-row-6 .node { padding: 12px 14px 11px; }
.org-row-6 .node-top { gap: 4px 6px; flex-wrap: wrap; }
.org-row-6 .node-name { font-size: 20px; }
.org-row-6 .status { font-size: 12px; gap: 5px; }
.org-row-6 .node-role { font-size: 12px; margin-top: 3px; }
.org-row-6 .node-task { font-size: 12.5px; margin-top: 6px; }
.org-row-6 .node-model { font-size: 12px; margin-top: 6px; }
.org-row-6 .node-foot { margin-top: 8px; }
/* 排间连线层:竖线对准每列中心,横线贯通,全部横平竖直;高度收紧到 22px */
.org-wires { position: relative; height: 22px; }
.org-wires .wire-v { position: absolute; width: 1px; background: var(--tree-line); }
.org-wires .wire-h { position: absolute; height: 1px; background: var(--tree-line); }
/* ===== 六部换行:触发依据是谱系块自身的宽度,不是视口 =====
根因(旧版):排数只由 @media (max-width:1080px/640px) 两条视口断点控制。
在应用外壳里,页面呈现宽度(分栏/嵌入)与视口宽并不总是一致,窗口缩到
视口断点之前就停住时,两条断点永远等不到,六张卡只能一味变小、挤在一排。
根治:三路同阈值(按谱系块宽:>1180 一排 6 张;≤1180 → 3×2;≤700 → 2×3)——
① JS ResizeObserver 实测 .org-rows 宽度写入 data-cols(主路,见脚本);
② @container 容器查询(CSS 原生同义路);③ @media 视口断点(兜底,数值已
按主区左右内边距 56px 换算对齐)。三省在任何档位恒为一排。 */
/* 中档:六部 3 列 × 2 排,每排总宽仍与三省排同宽对齐 */
.org-rows[data-cols="3"] { --ss-gap: 10px; --lb-gap: 10px; }
.org-rows[data-cols="3"] .org-row-6 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.org-rows[data-cols="3"] .org-wires-2 .wire-h { left: 16.6667% !important; right: 16.6667% !important; }
.org-rows[data-cols="3"] .org-wires-2 .w2-b1 { left: 16.6667% !important; }
.org-rows[data-cols="3"] .org-wires-2 .w2-b2 { left: 50% !important; }
.org-rows[data-cols="3"] .org-wires-2 .w2-b3 { left: 83.3333% !important; }
.org-rows[data-cols="3"] .org-wires-2 .w2-b4,
.org-rows[data-cols="3"] .org-wires-2 .w2-b5,
.org-rows[data-cols="3"] .org-wires-2 .w2-b6 { display: none; }
@container orgtree (max-width: 1180px) {
.org-row-6 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.org-wires-2 .wire-h { left: 16.6667% !important; right: 16.6667% !important; }
.org-wires-2 .w2-b1 { left: 16.6667% !important; }
.org-wires-2 .w2-b2 { left: 50% !important; }
.org-wires-2 .w2-b3 { left: 83.3333% !important; }
.org-wires-2 .w2-b4, .org-wires-2 .w2-b5, .org-wires-2 .w2-b6 { display: none; }
}
@media (max-width: 1240px) {
.org-row-6 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.org-wires-2 .wire-h { left: 16.6667% !important; right: 16.6667% !important; }
.org-wires-2 .w2-b1 { left: 16.6667% !important; }
.org-wires-2 .w2-b2 { left: 50% !important; }
.org-wires-2 .w2-b3 { left: 83.3333% !important; }
.org-wires-2 .w2-b4, .org-wires-2 .w2-b5, .org-wires-2 .w2-b6 { display: none; }
}
/* 窄档:六部 2 列 × 3 排;三省仍一排;卡片上的「主任模型」行隐藏(配置面板不受影响) */
.org-rows[data-cols="2"] { --ss-gap: 8px; --lb-gap: 8px; }
.org-rows[data-cols="2"] .org-row-6 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.org-rows[data-cols="2"] .node-model { display: none; }
.org-rows[data-cols="2"] .org-wires-2 .wire-h { left: 25% !important; right: 25% !important; }
.org-rows[data-cols="2"] .org-wires-2 .w2-b1 { left: 25% !important; }
.org-rows[data-cols="2"] .org-wires-2 .w2-b2 { left: 75% !important; }
.org-rows[data-cols="2"] .org-wires-2 .w2-b3,
.org-rows[data-cols="2"] .org-wires-2 .w2-b4,
.org-rows[data-cols="2"] .org-wires-2 .w2-b5,
.org-rows[data-cols="2"] .org-wires-2 .w2-b6 { display: none; }
.org-rows[data-cols="2"] .org-row .node { padding: 9px 9px 8px; }
.org-rows[data-cols="2"] .org-row-3 .node-name { font-size: 18px; }
.org-rows[data-cols="2"] .org-row-6 .node-name { font-size: 17px; }
.org-rows[data-cols="2"] .org-row .status { font-size: 11px; gap: 4px; }
.org-rows[data-cols="2"] .org-row .node-top { gap: 5px; flex-wrap: wrap; }
@container orgtree (max-width: 700px) {
.org-row-6 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.node-model { display: none; }
.org-wires-2 .wire-h { left: 25% !important; right: 25% !important; }
.org-wires-2 .w2-b1 { left: 25% !important; }
.org-wires-2 .w2-b2 { left: 75% !important; }
.org-wires-2 .w2-b3, .org-wires-2 .w2-b4, .org-wires-2 .w2-b5, .org-wires-2 .w2-b6 { display: none; }
.org-row .node { padding: 9px 9px 8px; }
.org-row-3 .node-name { font-size: 18px; }
.org-row-6 .node-name { font-size: 17px; }
.org-row .status { font-size: 11px; gap: 4px; }
}
@media (max-width: 760px) {
.node-model { display: none !important; }
.org-row-6 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.org-wires-2 .wire-h { left: 25% !important; right: 25% !important; }
.org-wires-2 .w2-b1 { left: 25% !important; }
.org-wires-2 .w2-b2 { left: 75% !important; }
.org-wires-2 .w2-b3, .org-wires-2 .w2-b4, .org-wires-2 .w2-b5, .org-wires-2 .w2-b6 { display: none; }
.org-row .node { padding: 9px 9px 8px; }
.org-row-3 .node-name { font-size: 18px; }
.org-row-6 .node-name { font-size: 17px; }
.org-row .status { font-size: 11px; gap: 4px; }
.org-row .node-top { gap: 5px; flex-wrap: wrap; }
}
.node {
width: 158px; min-width: 0;
border-radius: var(--radius-panel); background: var(--panel);
border: 1px solid var(--panel-line); padding: 11px 13px 10px;
position: relative; z-index: 1;
}
.node-main { min-width: 0; }
.node-role, .node-task { overflow-wrap: break-word; }
.node-model .num { overflow-wrap: anywhere; }
.node:hover { border-color: var(--muted); }
.node.selected { border-color: var(--cobalt); background: var(--cobalt-soft); }
.node.dim { opacity: .28; }
.node-main { display: block; width: 100%; text-align: left; padding: 0; min-height: 0; }
.node-role, .node-task, .node-model { display: block; }
.node-top { display: flex; align-items: center; gap: 8px; }
.node-name { font-family: var(--font-seat); font-weight: 900; font-size: 21px; line-height: 1.1; letter-spacing: .04em; }
.node.selected .node-name { color: var(--cobalt); }
.node.root { width: min(248px, 100%); }
.node.root .node-name { font-size: 25px; }
@media (max-width: 1400px) {
.node { width: 136px; }
.node.root { width: min(248px, 100%); }
}
.node-role { font-size: 11.5px; color: var(--muted); margin-top: 3px; }
.node-task { margin-top: 7px; font-size: 12px; color: var(--ink-2); }
.node-task .t-label { color: var(--muted); font-size: 11px; display: block; }
.node-model { margin-top: 6px; font-size: 11.5px; color: var(--muted); }
.node-model .num { font-size: 11px; }
.node-foot { margin-top: 9px; display: flex; align-items: center; gap: 8px; }
.status { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ink-2); white-space: nowrap; }
.status i { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); flex: 0 0 auto; }
.status.run i { background: var(--ok); box-shadow: 0 0 0 3px rgba(46,125,79,.16); }
.status.review i { background: var(--warn); box-shadow: 0 0 0 3px rgba(176,106,18,.16); }
.status.idle i { background: var(--muted); }
.elapsed { font-size: 12px; color: var(--muted); }
/* ---------- 节点纵向骨架:内容区撑满,已耗时一行钉在卡底 ---------- */
.node { display: flex; flex-direction: column; }
.node-main { flex: 1 1 auto; display: flex; flex-direction: column; }
.node-foot { margin-top: auto; }
.node-task .task-text { display: block; }
/* ---------- 席位详情头:标题 + 开始对话主按钮 ---------- */
.detail-head { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 4px; flex-wrap: wrap; }
.detail-head h3 { flex: 1 1 auto; min-width: 140px; margin: 0; overflow-wrap: anywhere; }
.detail-head .btn { flex: 0 0 auto; padding: 7px 16px; }
/* ---------- 会话弹窗:与该席对话 ---------- */
.chat-log { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
.chat-msg {
max-width: 88%; padding: 9px 12px; border-radius: 8px;
font-size: 13.5px; line-height: 1.6; overflow-wrap: anywhere;
}
.chat-msg.seat { background: var(--muted-bg); color: var(--ink-2); align-self: flex-start; }
.chat-msg.me { background: var(--cobalt); color: var(--on-accent); align-self: flex-end; }
.chat-compose { display: flex; gap: 10px; margin-top: 16px; align-items: flex-end; }
.chat-compose textarea {
flex: 1; min-height: 44px; resize: vertical;
border: 1px solid var(--panel-line); border-radius: var(--radius-control);
background: var(--panel); color: var(--ink); font: inherit; font-size: 13.5px;
padding: 8px 10px;
}
.chat-compose textarea:focus { border-color: var(--cobalt); outline: none; }
.chat-compose .btn { flex: 0 0 auto; padding: 8px 18px; }
.chat-card { margin-top: 20px; }
.chat-card .chat-log { margin-top: 0; min-height: 260px; }
.chat-card .m-decided { margin: 12px 0 0; font-size: 13px; color: var(--muted); }
/* ---------- 六部:六张等高卡,每段单行固定高,卡底已耗时齐平 ---------- */
.org-row-6 .node { height: 100%; padding: 12px 14px; }
.org-row-6 .node-top { flex-wrap: nowrap; height: 30px; overflow: hidden; }
.org-row-6 .node-name { flex: 0 0 auto; }
.org-row-6 .status { flex: 0 0 auto; }
.org-row-6 .node-role {
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
height: 20px; line-height: 20px; margin-top: 4px;
}
.org-row-6 .node-task { margin-top: 8px; }
.org-row-6 .node-task .t-label { height: 16px; line-height: 16px; }
.org-row-6 .node-task .task-text {
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
height: 20px; line-height: 20px;
}
.org-row-6 .node-model {
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
height: 20px; line-height: 20px; margin-top: 6px;
}
.org-row-6 .node-foot { margin-top: auto; padding-top: 9px; }
.org-row-6 .elapsed {
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
height: 20px; line-height: 20px; display: block;
}
/* ---------- 右列:详情 + 复核(骨架面板) ---------- */
.rail { display: flex; flex-direction: column; gap: 20px; }
.detail-col { display: flex; flex-direction: column; gap: 20px; min-width: 0; }
.card {
background: var(--panel); border: 1px solid var(--panel-line);
border-radius: var(--radius-panel); padding: 18px;
}
.card h3 { margin: 0 0 4px; font-size: 14.5px; font-weight: 700; display: flex; align-items: center; gap: 8px; }
.card h3 .count {
font-family: var(--font-num); font-size: 11.5px; background: var(--cobalt); color: var(--on-accent);
border-radius: 999px; padding: 0 8px; line-height: 19px;
}
.detail-name { font-family: var(--font-seat); font-weight: 900; font-size: 30px; color: var(--cobalt); line-height: 1.15; }
.detail-role { color: var(--muted); font-size: 12.5px; margin-bottom: 12px; }
.kv { display: grid; grid-template-columns: 74px 1fr; row-gap: 8px; font-size: 13px; }
.kv dt { color: var(--muted); }
.kv dd { margin: 0; color: var(--ink); }
.kv dd .sub { color: var(--muted); font-size: 12px; }
.excerpt {
margin-top: 14px; border-top: 1px dashed var(--panel-line); padding-top: 12px;
font-size: 13px; color: var(--ink-2);
}
.excerpt .t-label { color: var(--muted); font-size: 11.5px; display: block; margin-bottom: 4px; }
/* ---------- 部门配置面板:平表单 + 圆点文字标状态 ---------- */
.card h3 .seat-tag { color: var(--cobalt); font-family: var(--font-seat); font-weight: 900; font-size: 16px; }
.cfg-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px 16px; margin-top: 10px; }
.cfg-row { display: flex; flex-direction: column; gap: 5px; font-size: 12px; color: var(--muted); }
.cfg-row select {
border: 1px solid var(--panel-line); border-radius: var(--radius-control);
background: var(--panel); color: var(--ink); font: inherit; font-size: 13.5px;
padding: 7px 10px; width: 100%;
}
.cfg-row select:focus { border-color: var(--cobalt); outline: none; }
.cfg-skills { margin-top: 16px; border-top: 1px dashed var(--panel-line); padding-top: 12px; }
.cfg-skills .t-label { color: var(--muted); font-size: 11.5px; display: block; }
.skill-list { list-style: none; margin: 4px 0 0; padding: 0; }
.skill-list li {
display: flex; align-items: center; gap: 10px;
padding: 8px 0; border-top: 1px solid var(--panel-line); font-size: 13px;
}
.skill-list li:first-child { border-top: 0; padding-top: 4px; }
.skill-list .skill-name { flex: 1; min-width: 0; }
.skill-list .skill-state { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ink-2); white-space: nowrap; }
.skill-list .skill-state i { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); flex: 0 0 auto; }
.skill-list .skill-state.bound { color: var(--ink); }
.skill-list .skill-state.bound i { background: var(--ok); box-shadow: 0 0 0 3px rgba(46,125,79,.16); }
.skill-toggle {
border: 1px solid var(--panel-line); border-radius: var(--radius-control);
background: var(--panel); padding: 4px 13px; font-size: 12.5px; min-height: 32px; white-space: nowrap;
}
.skill-toggle:hover { background: var(--muted-bg); }
@media (max-width: 640px) { .cfg-grid { grid-template-columns: 1fr; } }
/* ---------- 工作区条目:一条一卡(门下审核 / 中书方案 / 尚书调度共用同一套) ---------- */
.review-list { display: flex; flex-direction: column; gap: 12px; margin-top: 12px; }
.review-card {
background: var(--panel); border: 1px solid var(--panel-line);
border-radius: var(--radius-panel); padding: 14px 16px 12px;
}
.review-card.decided { opacity: .55; }
.rc-head { display: flex; align-items: center; gap: 10px; }
.rc-title {
flex: 1; min-width: 0; font-weight: 700; font-size: 14.5px; color: var(--ink);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.rc-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ink-2); white-space: nowrap; flex: 0 0 auto; }
.rc-status i { width: 8px; height: 8px; border-radius: 50%; background: var(--warn); box-shadow: 0 0 0 3px rgba(176,106,18,.16); flex: 0 0 auto; }
.rc-status.pass i { background: var(--ok); box-shadow: 0 0 0 3px rgba(46,125,79,.16); }
.rc-status.reject i { background: var(--bad); box-shadow: 0 0 0 3px rgba(179,55,44,.14); }
.rc-status.run i { background: var(--cobalt); box-shadow: 0 0 0 3px var(--cobalt-soft); }
.rc-status.idle i { background: var(--muted); box-shadow: none; }
.rc-meta-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 8px; }
.rc-from {
font-size: 11.5px; font-weight: 500; color: var(--ink-2);
background: var(--muted-bg); border-radius: 999px; padding: 1px 9px; line-height: 19px;
white-space: nowrap;
}
.rc-meta { font-size: 12px; color: var(--muted); }
.rc-excerpt {
margin-top: 10px; background: var(--muted-bg); border-radius: 6px;
padding: 9px 11px; font-size: 12.5px; color: var(--ink-2); line-height: 1.6;
display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;
}
.rc-excerpt.expanded { display: block; -webkit-line-clamp: unset; }
/* 定夺后记在卡上的批复理由 / 批语(回传提交席位照此修改) */
.rc-reason {
margin-top: 10px; background: var(--muted-bg); border-radius: 6px;
padding: 8px 11px; font-size: 12.5px; color: var(--ink-2); line-height: 1.6;
overflow-wrap: anywhere;
}
.rc-actions { display: flex; align-items: center; gap: 10px; margin-top: 12px; }
.rc-actions .spacer { flex: 1; }
.rc-actions .btn { padding: 5px 14px; font-size: 13px; min-height: 34px; }
.rc-actions .btn.pass { color: var(--cobalt-ink); font-weight: 700; }
.rc-actions .btn:disabled { opacity: .5; cursor: default; }
.rc-actions .btn:disabled:hover { background: var(--panel); }
.r-open {
display: inline-flex; align-items: center; gap: 4px;
font-size: 13px; font-weight: 500; color: var(--cobalt); padding: 5px 6px; min-height: 34px;
}
.r-open:hover { color: var(--cobalt-ink); text-decoration: underline; }
.empty-note { font-size: 13px; color: var(--muted); padding: 10px 0 2px; }
/* ---------- 席位工作区:随选中席位切换内容 ---------- */
.w-kind {
font-size: 11.5px; font-weight: 500; color: var(--cobalt-ink);
background: var(--cobalt-soft); border-radius: 999px; padding: 1px 9px; line-height: 19px;
}
.ws-sec { margin-top: 14px; }
.ws-sec:first-child { margin-top: 6px; }
.ws-sec .t-label { color: var(--muted); font-size: 11.5px; display: block; margin-bottom: 4px; }
.ws-sec p { margin: 0; font-size: 13.5px; color: var(--ink-2); }
/* 方案 / 调度 / 审核条目样式见上方「工作区条目:一条一卡」 */
/* ---------- 右列里的配置面板:字段上下排 ---------- */
.rail .cfg-grid { grid-template-columns: minmax(0, 1fr); }
/* ---------- 复核弹窗:看清待准奏内容再定夺 ---------- */
.modal-backdrop {
position: fixed; inset: 0; z-index: 60;
background: rgba(9, 9, 11, .48);
display: flex; align-items: center; justify-content: center;
padding: 18px;
}
.modal-backdrop[hidden] { display: none; }
.modal {
background: var(--panel); color: var(--ink);
border: 1px solid var(--panel-line); border-radius: 12px;
width: min(580px, 100%); max-height: calc(100vh - 36px); overflow-y: auto;
padding: 20px 22px 18px;
}
.modal.wide { width: min(760px, 100%); }
.modal-head { display: flex; align-items: flex-start; gap: 12px; }
.modal-head h3 { margin: 0; font-size: 17px; font-weight: 700; flex: 1; min-width: 0; }
.modal-close {
flex: 0 0 auto; width: 32px; height: 32px; min-height: 32px;
border: 1px solid var(--panel-line); border-radius: var(--radius-control);
display: inline-flex; align-items: center; justify-content: center; font-size: 15px;
}
.modal-close:hover { background: var(--muted-bg); }
.modal .m-from { font-size: 12.5px; color: var(--muted); margin-top: 3px; }
.modal .m-sec { margin-top: 15px; }
.modal .m-sec .t-label { color: var(--muted); font-size: 11.5px; display: block; margin-bottom: 4px; }
.modal .m-sec p { margin: 0; font-size: 13.5px; color: var(--ink-2); }
.modal .m-doubts { list-style: none; margin: 0; padding: 0; }
.modal .m-doubts li { padding: 6px 0 6px 16px; border-top: 1px solid var(--panel-line); font-size: 13.5px; color: var(--ink-2); position: relative; }
.modal .m-doubts li:first-child { border-top: 0; }
.modal .m-doubts li::before { content: ""; position: absolute; left: 2px; top: 14px; width: 5px; height: 5px; border-radius: 50%; background: var(--warn); }
.modal .m-source {
background: var(--muted-bg); border-radius: var(--radius-panel);
padding: 10px 12px; font-size: 13px; color: var(--ink-2);
}
.modal-actions { display: flex; gap: 10px; margin-top: 18px; }
.modal-actions .btn { padding: 7px 18px; }
.modal-actions .btn.pass { color: var(--cobalt-ink); font-weight: 700; }
.modal .m-decided { margin-top: 16px; font-size: 13px; color: var(--muted); }
.modal textarea {
width: 100%; border: 1px solid var(--panel-line); border-radius: var(--radius-control);
background: var(--panel); color: var(--ink); font: inherit; font-size: 13.5px;
padding: 8px 10px; resize: vertical; min-height: 64px;
}
.modal textarea:focus { border-color: var(--cobalt); outline: none; }
.modal .m-err { color: var(--bad); font-size: 12.5px; margin: 6px 0 0; }
.modal .m-err[hidden] { display: none; }
/* ---------- 表格(骨架:干脆、高对比、无拟物) ---------- */
.table-card {
margin-top: 20px; background: var(--panel); border: 1px solid var(--panel-line);
border-radius: var(--radius-panel); padding: 18px 18px 8px;
}
.table-scroll { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
thead th {
text-align: left; font-size: 12px; color: var(--muted); font-weight: 500;
padding: 8px 12px; border-bottom: 1px solid var(--panel-line); white-space: nowrap;
}
tbody td { padding: 11px 12px; border-bottom: 1px solid var(--panel-line); vertical-align: middle; }
tbody tr:last-child td { border-bottom: 0; }
tbody tr:hover td { background: var(--cobalt-soft); }
td .task-name { font-weight: 500; }
td .task-id { font-family: var(--font-num); font-size: 11.5px; color: var(--muted); }
.pill {
display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 500;
border: 1px solid var(--panel-line); border-radius: 999px; padding: 2px 10px; white-space: nowrap;
background: var(--panel);
}
.pill i { width: 6px; height: 6px; border-radius: 50%; background: var(--muted); }
.pill.done i { background: var(--ok); }
.pill.run i { background: var(--cobalt); }
.pill.review i { background: var(--warn); }
.pill.fail i { background: var(--bad); }
td.time, td.dur { font-family: var(--font-num); font-size: 12.5px; color: var(--ink-2); white-space: nowrap; }
td.result-cell { max-width: 260px; min-width: 160px; color: var(--ink-2); font-size: 12.5px; line-height: 1.5; overflow-wrap: anywhere; }
.foot-note { margin-top: 16px; font-size: 12px; color: var(--muted); }
/* ---------- 窄屏回落:按工作台自身宽度判断,避免右栏 600px 仍套宽屏网格 ---------- */
@container ssv2 (max-width: 1180px) {
.grid { grid-template-columns: 1fr; }
.rail { flex-direction: row; align-items: stretch; }
.rail .card { flex: 1; }
.stats { grid-template-columns: repeat(2, 1fr); }
}
@container ssv2 (max-width: 860px) {
.proj { margin-left: 0; }
.tabs { width: 100%; }
.tabs a { flex: 1 1 auto; justify-content: center; }
.rail { flex-direction: column; }
.search { width: 100%; order: 5; }
.stats { grid-template-columns: 1fr 1fr; gap: 10px; }
}
@container ssv2 (max-width: 640px) {
/* 窄栏表格收成四列:藏「耗时」「派发时间」两列,单元格允许换行,不横滚 */
thead th:nth-child(5), tbody td:nth-child(5),
thead th:nth-child(6), tbody td:nth-child(6) { display: none; }
thead th, tbody td { padding-left: 8px; padding-right: 8px; }
thead th { white-space: normal; }
td .task-name, td .task-id { overflow-wrap: anywhere; }
.pill { padding: 2px 7px; font-size: 11.5px; white-space: normal; }
td.time { white-space: normal; }
}
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; }
}
}
body[data-ds-dark-theme] .ssv2,html[data-theme=dark] .ssv2,.ssv2[data-ssv-theme=dark]{--bg:#09090b;--sidebar-bg:#0c0c0e;--panel:#18181b;--panel-line:#27272a;--muted-bg:#27272a;--ink:#fafafa;--ink-2:#d4d4d8;--muted:#a1a1aa;--cobalt:#829cff;--cobalt-ink:#a9bcff;--cobalt-soft:rgba(130,156,255,.13);--on-accent:#141a38;--ok:#5cb582;--warn:#d99a45;--bad:#e0705f}
/* ---------- 宿主接线:右栏 / 浮动面板 / 内嵌条 ---------- */
.ssw-tab-body{height:100%;min-height:0;display:flex;flex-direction:column;overflow:hidden}
.ssw-tab-title{font-size:12px;font-weight:600}
.ssw-inline-bar{flex:none;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 14px;background:var(--muted-bg);border-bottom:1px solid var(--panel-line);font-size:12px;color:var(--muted)}
.ssw-link{color:var(--cobalt-ink);font-size:12px;font-weight:500;padding:4px 6px;border-radius:6px}
.ssw-link:hover{background:var(--cobalt-soft)}
.ssw-nav-hit{display:inline-flex;align-items:center;justify-content:center;color:inherit;width:100%;height:100%}
.ssw-float{position:fixed;right:14px;bottom:70px;z-index:2147483000;width:min(760px,calc(100vw - 28px));max-height:calc(100vh - 96px);display:flex;flex-direction:column;background:var(--panel,#fff);border:1px solid var(--panel-line,#e4e4e7);border-radius:12px;box-shadow:0 18px 50px -12px rgba(16,24,40,.28),0 4px 12px -2px rgba(16,24,40,.12);overflow:hidden}
.ssw-float>.ssv2{height:100%;min-height:0;overflow:auto}
/* ---------- 工作台 v2 工具样式 ---------- */
.ssv2{height:100%;min-height:0;overflow:auto;background:var(--bg);color:var(--ink);font-family:var(--font-ui)}
.ssv2 .main{min-height:100%;min-width:600px;container-type:inline-size;container-name:ssv2;display:flex;flex-direction:column}
.ssv2 .page{min-height:0;flex:1 0 auto}
.ssv2 .topbar-title{display:flex;align-items:center;gap:12px;min-width:0;flex-wrap:wrap}
.ssv2 .topbar-icons{display:flex;align-items:center;gap:6px}
.ssv2 .icon-btn{width:32px;height:32px;display:inline-flex;align-items:center;justify-content:center;border:1px solid transparent;border-radius:var(--radius-control);background:transparent;color:var(--muted);cursor:pointer;padding:0}
.ssv2 .icon-btn:hover{background:var(--muted-bg);color:var(--ink);border-color:var(--panel-line)}
.ssv2 .icon-btn:focus-visible{outline:2px solid var(--cobalt);outline-offset:2px}
.ssv2 .project-dock{display:flex;justify-content:flex-end;margin-top:auto;padding-top:22px}
.ssv2 .project-dock .proj{margin-left:0}
.ssv-banner{margin:12px 0 0;padding:9px 12px;border-radius:8px;font-size:12.5px;line-height:1.5;border:1px solid var(--panel-line);background:var(--muted-bg);color:var(--ink-2)}
.ssv-banner.is-error{color:var(--bad);background:color-mix(in srgb, var(--bad) 8%, var(--panel));border-color:color-mix(in srgb, var(--bad) 24%, var(--panel-line))}
.ssv-banner.is-notice{color:var(--cobalt-ink);background:var(--cobalt-soft);border-color:color-mix(in srgb, var(--cobalt) 20%, var(--panel-line))}
.ssv-textarea{width:100%;box-sizing:border-box;border:1px solid var(--panel-line);border-radius:var(--radius-control);background:var(--panel);color:var(--ink);font:inherit;font-size:13px;line-height:1.55;padding:7px 10px;resize:vertical}
.ssv-textarea:focus{border-color:var(--cobalt);outline:none}
.ssv-select{width:100%;border:1px solid var(--panel-line);border-radius:var(--radius-control);background:var(--panel);color:var(--ink);font:inherit;font-size:13.5px;padding:7px 10px}
.ssv-select:focus{border-color:var(--cobalt);outline:none}
.ssv-check{display:flex;align-items:center;gap:8px;margin-top:12px;font-size:13px;color:var(--ink-2);cursor:pointer}
.ssv-check input{accent-color:var(--cobalt);width:15px;height:15px}
.ssv-proj-caret{font-size:15px;color:var(--muted);margin-left:2px}
.ssv2 .ws-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}
.ssv2 .ws-actions .btn{min-height:34px;padding:5px 12px;font-size:13px}
.ssv2 .skill-list li{gap:8px}
.ssv2 .skill-list .skill-toggle{flex:none}
.ssv2 .card h3 .count{font-family:var(--font-num)}
/* ---------- 结果摘要 / 展开详情 ---------- */
.ssv2 .result-summary{margin-top:10px;min-width:0;max-width:100%}
.ssv2 .rs-line{display:flex;flex-direction:column;gap:3px;min-width:0}
.ssv2 .rs-summary{font-size:13px;color:var(--ink);line-height:1.6;overflow-wrap:anywhere;word-break:break-word}
.ssv2 .rs-points{margin:6px 0 0;padding-left:18px;font-size:12.5px;color:var(--ink-2);line-height:1.65}
.ssv2 .rs-points li{margin:2px 0;overflow-wrap:anywhere}
.ssv2 .rs-toggle{margin-top:5px;padding:0;color:var(--cobalt);font-size:12.5px;font-weight:500;min-height:24px;text-align:left}
.ssv2 .rs-detail{margin-top:10px;border-top:1px dashed var(--panel-line);padding-top:10px;font-size:13px;color:var(--ink-2);max-width:100%;overflow:hidden}
.ssv2 .rs-detail p,.ssv2 .rs-detail li,.ssv2 .rs-detail code,.ssv2 .rs-detail pre{overflow-wrap:anywhere;word-break:break-word;white-space:pre-wrap;max-width:100%}
.ssv2 .rs-heading{margin:10px 0 4px;font-size:13px;color:var(--ink);font-weight:700}
.ssv2 .rs-list{margin:4px 0 8px;padding-left:18px}
.ssv2 .rs-code{margin:6px 0;padding:8px 10px;border-radius:6px;background:var(--muted-bg);border:1px solid var(--panel-line);white-space:pre-wrap;overflow-wrap:anywhere}
.ssv2 .rs-path{display:inline-block;padding:1px 4px;border-radius:4px;background:var(--muted-bg);font-family:var(--font-num);font-size:12px}
.ssv2 .result-summary.is-empty{color:var(--muted);font-size:12.5px}
.ssv2 .rs-empty{margin-left:6px;color:var(--muted)}
.ssv2 .ws-hint{margin-top:8px}
/* ---------- 可折叠卡片(部门配置 / 记忆编辑) ---------- */
.ssv2 details.card>summary{display:flex;align-items:center;gap:8px;cursor:pointer;font-weight:700;font-size:14.5px;list-style:none;min-height:28px}
.ssv2 details.card>summary::-webkit-details-marker{display:none}
.ssv2 details.card>summary::after{content:'⌄';margin-left:auto;color:var(--muted);transition:transform .15s}
.ssv2 details.card[open]>summary::after{transform:rotate(180deg)}
.ssv2 details.card[open]>summary{margin-bottom:8px}
.ssv2 .dept-config-body{padding-top:2px}
/* ---------- 工作台 v2:顶栏小导航 / 队列与 Token 弹窗 / 卡片摘要 ---------- */
.ssv2 .panel-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.ssv2 .panel-actions .btn{min-height:32px;padding:5px 11px;font-size:12.5px}
.ssv2 .modal-toolbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:16px}
.ssv2 .modal-toolbar .search{flex:1 1 220px}
.ssv2 .queue-table-wrap{margin-top:14px;border-top:1px solid var(--panel-line)}
.ssv2 .queue-table-wrap table{margin-top:4px}
.ssv2 .card-summary{margin-top:8px;min-width:0}
.ssv2 .card-summary .t-label{display:block;color:var(--muted);font-size:11.5px;margin-bottom:3px}
.ssv2 .card-summary-text{margin:0;font-size:12.5px;line-height:1.6;color:var(--ink-2);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;overflow-wrap:anywhere;word-break:break-word}
.ssv2 .card-summary.is-empty .card-summary-text{color:var(--muted)}
.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}
`;

1104
src/client/workbench-v2.js Normal file

File diff suppressed because it is too large Load Diff

55
src/client/workspace.js Normal file
View File

@ -0,0 +1,55 @@
// 工作区解析:把「某个会话属于哪个项目工作区」从宿主快照里算出来。
// 纯函数,便于单测;index.js 只负责把宿主服务快照喂进来。
function samePath(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false
const norm = value => value.replace(/\//g, '\\').replace(/\\+$/g, '').toLowerCase()
return norm(a) === norm(b)
}
function baseName(path) {
if (typeof path !== 'string') return undefined
const parts = path.replace(/\/+$/g, '').split(/[\\/]/).filter(Boolean)
return parts.length ? parts[parts.length - 1] : undefined
}
export function normalizeWorkspaceItem(item) {
if (!item || typeof item !== 'object') return null
const workspaceId = item.workspaceId ?? item.id ?? null
if (typeof workspaceId !== 'string' || !workspaceId) return null
return {
workspaceId,
name: typeof item.name === 'string' ? item.name : (typeof item.title === 'string' ? item.title : undefined),
path: typeof item.path === 'string' ? item.path : undefined,
sessionIds: Array.isArray(item.sessionIds) ? item.sessionIds : undefined,
}
}
export function workspaceItemsFromSnapshot(snapshot) {
const items = Array.isArray(snapshot) ? snapshot : (snapshot && typeof snapshot === 'object' && Array.isArray(snapshot.items) ? snapshot.items : [])
return items.map(normalizeWorkspaceItem).filter(Boolean)
}
export function sessionSummaryFromSnapshot(snapshot, sessionId) {
if (!snapshot || typeof snapshot !== 'object' || typeof sessionId !== 'string' || !sessionId) return null
const byId = snapshot.byId
if (!byId || typeof byId !== 'object') return null
const summary = byId[sessionId]
return summary && typeof summary === 'object' ? summary : null
}
/**
* 按会话解析工作区:优先命中 workspace.sessionIds;否则用会话 cwd 匹配工作区路径;
* 都匹配不到时把 cwd 本身当作可解析路径(host service.open 会按 path resolve/create)。
*/
export function workspaceForSession(items, sessionId, sessionSummary) {
const list = (Array.isArray(items) ? items : []).map(normalizeWorkspaceItem).filter(Boolean)
if (typeof sessionId !== 'string' || !sessionId) return null
const bySession = list.find(item => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId))
if (bySession) return bySession
const cwd = sessionSummary && typeof sessionSummary.cwd === 'string' ? sessionSummary.cwd : ''
if (!cwd) return null
const byPath = list.find(item => item.path && samePath(item.path, cwd))
if (byPath) return byPath
return { workspaceId: null, name: baseName(cwd), path: cwd, sessionIds: [sessionId] }
}

View File

@ -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':

View File

@ -15,18 +15,29 @@ 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 自动增加);旧发布命令和旧批准立即失效,旧任务会停止推进并等待重新确认。',
'Grill Me 需求澄清规则:先判断用户输入是否包含「提出或变更需求」的立项意图。仅在需求存在关键歧义、冲突或缺失时触发:目标有多种合理理解;范围、非目标或验收标准缺失;前后要求存在冲突;关键约束、优先级或使用场景不明确;不同选择会明显影响架构、成本或风险;继续拟案必须依赖猜测。触发时调用 skill({ name: "grilling" }) 并严格按该 skill 的规则追问,不要自行另写一套提问逻辑。代码解释、状态查询、资料阅读、普通讨论、暂不立项的想法交流、已足够明确可直接整理的需求,以及用户明确说「别问了」「直接整理」「保留假设出方案」时不触发。用户主动说「Grill Me」「拷问我」时直接进入追问。',
'Grill Me 追问前先自行查清可自行查明的事实,不询问用户本可自行查到的信息。新需求进入追问时可先建立 discussing 状态的 R-xxx 草稿并保留用户原话;已有需求在原条目上继续,不另建重复条目。',
'Grill Me 追问结束后,必须用 sansheng_requirement_upsert 回写同一个 R-xxx 的 summary、scope、nonGoals、acceptanceCriteria、risks、dependencies、missingInfo、judgement、judgementReason;更新已有需求必须携带 expectedRevision。信息足够才可进入 ready;仍有未决事项保持 discussing,不得为了结束追问强行标记为可发布。',
'Grill Me 只做需求澄清,不创建任务、不派工、不生成批准凭证。停止条件:已足以形成清晰范围与验收标准;skill 自身判断可以结束;用户要求停止或直接整理;用户接受保留部分假设继续。停止时输出:需求编号与 revision、已确认内容、范围与非目标、验收标准、仍需保留的假设或待确认项、当前状态(discussing / ready)、下一步所需用户命令。即使达到 ready,也只能提示「如需进入中书拟案,请明确发送『发布 R-xxx 给中书』」,不得自动发布、批准或派工。',
'grill-me 是用户手动入口;模型侧自动加载的是 grilling。若 skill 加载失败或不可用,必须明确告知未加载成功,不得假装使用 grill-me/grilling,也不得自行复制一套同名提示词冒充。',
)
} 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('只在本项目本席会话内工作;不要修改其他项目或其他席的配置,也不要替用户提升权限。')

View File

@ -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,124 @@ 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] : []
if (Array.isArray(value)) return value.flatMap(item => {
if (typeof item === 'string') return item.trim() ? [item] : []
if (item && typeof item === 'object') {
const id = item.id ?? item.value ?? item.name
return typeof id === 'string' && id.trim() ? [id] : []
}
return []
})
if (typeof value === 'object') {
if (value.efforts !== undefined) return effortValuesOf(value.efforts)
if (value.values !== undefined) return effortValuesOf(value.values)
if (value.options !== undefined) return effortValuesOf(value.options)
return Object.keys(value).filter(key => key !== 'defaultEffort' && key.trim() !== '' && typeof value[key] !== 'object')
}
return []
}
export function normalizeCatalog(catalog) {
const providers = []
const entryFor = provider => {
@ -60,8 +178,9 @@ export function normalizeCatalog(catalog) {
if (!provider || !modelId) continue
const entry = entryFor(provider)
if (entry.models.some(x => x.model === modelId)) continue
const effort = typeof m === 'object' ? (m.reasoningEffort ?? m.reasoning) : undefined
entry.models.push(effort ? { model: modelId, reasoningEffort: effort } : { model: modelId })
const effort = typeof m === 'object' ? (m.reasoningEfforts ?? m.reasoningEffort ?? m.reasoning) : undefined
const effortValues = effortValuesOf(effort)
entry.models.push(effortValues.length > 0 ? { model: modelId, reasoningEffort: effortValues } : { model: modelId })
}
}
}
@ -311,7 +430,7 @@ export class SanshengService {
'汇总要求:',
'1. 按已完成 / 执行中 / 已派工 / 待执行 / 失败或取消分组汇总,列出任务 ID、主责部门、当前状态和关键结果。',
'2. 明确区分「已派工/已收到」和「已完成」,不要把已派工当成完成。',
'3. 只做汇总,不重派任务,不拦截丞相直接派工;指出仍未完成或需要复核的事项。',
'3. 只做汇总,不重派任务;按需求门控流程报告真实阻塞、完成与待复核事项。',
].join('\n')
const requestId = randomUUID()
try {
@ -327,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} 不存在`)
@ -338,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()
@ -374,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()
@ -398,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()
@ -434,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'

View File

@ -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

View File

@ -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)) {
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 {
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 || '任务投递失败,未送达部门会话',
}
}
return {
...result,
ok: true,
delivered: true,
taskId: created.task.id,
sessionId: dispatched.task.sessionId,
targetLabel: labelOf(targetSeatId),
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
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,8 +400,11 @@ 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('丞相不能代替部门报告,必须由实际执行部门回报')
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),
@ -251,6 +413,7 @@ function seatToolDefinitions({ store, service }) {
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 {

View File

@ -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}] 不是对象`

View File

@ -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 },
}
}

112
test/grill-me.test.js Normal file
View File

@ -0,0 +1,112 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { installPromptSection } from '../src/host/prompt.js'
import { setupService, seatById } from './helpers.js'
import { createSeatToolDefinitions } from '../src/host/tools.js'
async function setupGrill() {
const env = await setupService({ prompt: true })
const opened = await env.service.open({ path: '/grill-me', name: 'Grill Me 项目' })
env.projectId = opened.project.id
await env.service.enable(env.projectId)
const view = await env.service.project(env.projectId)
env.leadSession = seatById(view, 'lead').sessionId
env.tools = Object.fromEntries(
createSeatToolDefinitions({ store: env.store, service: env.service }).map(def => [def.name, def]),
)
return env
}
function run(env, name, args) {
return env.tools[name].execute(args, { agent: env.fake.sessions.get(env.leadSession) })
}
test('Grill Me 规则只注入丞相,且写明触发、停止与授权边界', async () => {
const env = await setupGrill()
installPromptSection(env.fake.ctx, { store: env.store })
const section = env.fake.getPromptSection()
const view = await env.service.project(env.projectId)
const lead = section.text({ agent: { id: seatById(view, 'lead').sessionId } })
for (const keyword of ['关键歧义', '代码解释', '别问了', 'Grill Me', '拷问我', 'expectedRevision', 'discussing', 'ready', '不得自动发布、批准或派工', 'skill 加载失败']) {
assert.ok(lead.includes(keyword), `丞相提示缺少关键词:${keyword}`)
}
const other = section.text({ agent: { id: seatById(view, 'gongbu').sessionId } })
assert.ok(!other.includes('Grill Me 需求澄清规则'))
assert.ok(!other.includes('skill({ name: "grilling" })'))
})
test('Grill 结果回写同一个需求:revision 递增且不产生任务副作用', async () => {
const env = await setupGrill()
const created = await run(env, 'sansheng_requirement_upsert', {
title: '做一个有用的东西',
originalText: '帮我做点有用的东西,具体你看着办',
summary: '待澄清',
judgement: 'needs_discussion',
judgementReason: '目标、范围、验收标准都不明确',
missingInfo: '目标场景、范围边界、验收标准',
})
assert.equal(created.ok, true, created.error)
assert.equal(created.created, true)
assert.equal(created.requirement.revision, 1)
assert.equal(created.requirement.status, 'discussing')
const id = created.requirement.id
const updated = await run(env, 'sansheng_requirement_upsert', {
id,
expectedRevision: 1,
summary: '做一个本地多语言 Hello World 展示页',
scope: '本地静态页面 + 三种可运行语言示例',
nonGoals: '不部署公网,不引入构建依赖',
acceptanceCriteria: '三种语言均可真实运行;窄屏可用;可重跑;成功和失败有区分',
risks: '浏览器兼容性',
dependencies: '本机 Python / Node / 浏览器',
missingInfo: '无',
judgement: 'can_do',
judgementReason: '追问后范围与验收标准已明确',
})
assert.equal(updated.ok, true, updated.error)
assert.equal(updated.created, false)
assert.equal(updated.requirement.id, id)
assert.equal(updated.requirement.revision, 2)
assert.equal(updated.requirement.status, 'ready')
const tasks = (await env.service.tasks(env.projectId)).tasks
assert.equal(tasks.length, 0, 'Grill Me 回写需求不得创建任务')
})
test('Grill 期间旧 revision 更新被拒绝,且保留原需求不重复新建', async () => {
const env = await setupGrill()
const first = await run(env, 'sansheng_requirement_upsert', {
title: '改版需求',
originalText: '先按旧方案做',
judgement: 'needs_discussion',
missingInfo: '待确认',
})
assert.equal(first.ok, true, first.error)
const id = first.requirement.id
const second = await run(env, 'sansheng_requirement_upsert', {
id,
expectedRevision: 1,
summary: '第一轮追问后的整理',
judgement: 'needs_discussion',
missingInfo: '验收标准待确认',
})
assert.equal(second.ok, true, second.error)
assert.equal(second.requirement.revision, 2)
const stale = await run(env, 'sansheng_requirement_upsert', {
id,
expectedRevision: 1,
summary: '基于旧版本的覆盖',
})
assert.equal(stale.ok, false)
assert.equal(stale.reason, 'sansheng/requirement-conflict')
const list = await env.service.requirements(env.projectId)
assert.equal(list.requirements.length, 1, '同一需求不能因 Grill Me 产生重复条目')
assert.equal(list.requirements[0].id, id)
assert.equal(list.requirements[0].revision, 2)
})

View File

@ -2,6 +2,7 @@ import test from 'node:test'
import assert from 'node:assert/strict'
import { setupService } from './helpers.js'
import { buildWorkbenchView } from '../src/client/workbench.js'
import { normalizeCatalog } from '../src/host/service.js'
import { buildPanelView } from '../src/native/panel.js'
function childNodes(node) {
@ -21,6 +22,24 @@ function depth(node) {
return 1 + max
}
test('模型目录兼容宿主 reasoningEfforts 映射', () => {
const out = normalizeCatalog({
providers: [{
provider: 'deepseek-account',
models: [
{ id: 'deepseek-v4-pro', reasoningEfforts: { off: 'off', low: 'low', high: 'high' } },
{ id: 'deepseek-flash', reasoningEffort: ['low', 'high'] },
{ id: 'deepseek-fast', reasoningEfforts: { efforts: ['off', 'high'], defaultEffort: 'off' } },
],
}],
})
assert.deepEqual(out.providers[0].models, [
{ model: 'deepseek-v4-pro', reasoningEffort: ['off', 'low', 'high'] },
{ model: 'deepseek-flash', reasoningEffort: ['low', 'high'] },
{ model: 'deepseek-fast', reasoningEffort: ['off', 'high'] },
])
})
test('宿主项目视图可直接喂给 Web 纯视图模型', async () => {
const { service } = await setupService()
const opened = await service.open({ path: '/ui', name: '界面项目' })

View File

@ -15,3 +15,34 @@ test('左侧入口使用 sidebar.panellist,位置在记忆系统与更多之
assert.ok(!source.includes('sidebar.session.action'), '不得再占用新会话右侧槽位')
assert.ok(!source.includes('SanshengSessionAction'), '旧的新会话入口应已删除')
})
test('右侧工作台依赖宿主 sidebarRight,并在会话切换后重新固定', async () => {
const source = await readFile(join(root, 'src/client/index.js'), 'utf8')
assert.match(source, /export const inject = \[[^\]]*'workspaces'[^\]]*'sidebarRightTabs', 'sidebarRight'/)
assert.match(source, /right\.mounted\.subscribe/)
assert.match(source, /right\.openTabs\.getSnapshot/)
assert.match(source, /right\.focus\(row\.tabId\)/)
})
test('右侧栏有可发现的 guide 入口,并把标签会话传给工作台', async () => {
const source = await readFile(join(root, 'src/client/index.js'), 'utf8')
assert.match(source, /guide: \[\{/)
assert.match(source, /const sessionId = props && props\.sessionId/)
assert.match(source, /workspaceForSessionId\(sessionId\)/)
})
test('右栏展开失败会继续重试,guide 打开也会记为固定', async () => {
const source = await readFile(join(root, 'src/client/index.js'), 'utf8')
assert.match(source, /if \(revealRightTab\(sessionId\)\) \{ attempt = 0; return \}/)
assert.match(source, /right\.openTabs\.subscribe\(discoverPinnedTab\)/)
assert.match(source, /if \(existing\) return revealRightTab\(targetSessionId\)/)
assert.match(source, /if \(activeNow !== row\.tabId\) return false/)
})
test('右栏可见性按会话判断,布局列收起时主动展开', async () => {
const source = await readFile(join(root, 'src/client/index.js'), 'utf8')
assert.match(source, /'data-session-id': sessionId/)
assert.match(source, /function workbenchVisible\(sessionId\)/)
assert.match(source, /workbenchVisible\(sessionId\)/)
assert.match(source, /layout\.openRightbar\(true, false\)/)
})

View File

@ -36,3 +36,26 @@ test('补充说明出现在提示里', async () => {
const text = fake.getPromptSection().text({ agent: { id: seatById(p, 'libu').sessionId } })
assert.match(text, /先问清目标/)
})
test('丞相提示包含 Grill Me 规则,其他九席不注入', async () => {
const { service, store, fake } = await setupService()
installPromptSection(fake.ctx, { store })
const opened = await service.open({ path: '/pp3', name: 'Grill 项目' })
await service.enable(opened.project.id)
const p = await service.project(opened.project.id)
const section = fake.getPromptSection()
const leadText = section.text({ agent: { id: seatById(p, 'lead').sessionId } })
assert.match(leadText, /Grill Me 需求澄清规则/)
assert.ok(leadText.includes('skill({ name: "grilling" })'))
assert.match(leadText, /expectedRevision/)
assert.match(leadText, /不创建任务、不派工、不生成批准凭证/)
assert.match(leadText, /不得假装使用 grill-me\/grilling/)
assert.match(leadText, /发布 R-xxx 给中书/)
for (const seatId of ['zhongshu', 'menxia', 'shangshu', 'libu', 'hubu', 'lipu', 'bingbu', 'xingbu', 'gongbu']) {
const text = section.text({ agent: { id: seatById(p, seatId).sessionId } })
assert.doesNotMatch(text, /Grill Me/)
assert.ok(!text.includes('skill({ name: "grilling" })'))
}
})

View File

@ -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)
})

View File

@ -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 () => {

View File

@ -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) 本席工具未就绪:普通会话调用派工
{
test('回归:直接派工工具已停用,本席未就绪时仍返回 tool-not-ready', async () => {
const env = await setupService({ prompt: true })
const opened = await env.service.open({ path: '/fail-ready', name: '就绪项目' })
const opened = await env.service.open({ path: '/reg-direct', 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')
}
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()
}

View File

@ -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)
})

44
test/workspace.test.js Normal file
View File

@ -0,0 +1,44 @@
// 工作区解析纯函数:多工作区下按会话/路径找到正确项目。
import test from 'node:test'
import assert from 'node:assert/strict'
import {
workspaceForSession,
workspaceItemsFromSnapshot,
sessionSummaryFromSnapshot,
} from '../src/client/workspace.js'
const ITEMS = [
{ workspaceId: 'ws-a', title: '甲项目', path: 'C:\\Work\\A', sessionIds: ['s-a'] },
{ workspaceId: 'ws-b', title: '乙项目', path: 'D:/Work/B', sessionIds: ['s-b'] },
]
test('workspaceItemsFromSnapshot 保留会话归属并统一标题字段', () => {
const items = workspaceItemsFromSnapshot({ items: ITEMS })
assert.equal(items.length, 2)
assert.equal(items[0].workspaceId, 'ws-a')
assert.equal(items[0].name, '甲项目')
assert.deepEqual(items[0].sessionIds, ['s-a'])
})
test('workspaceForSession 优先按 sessionIds 命中工作区', () => {
assert.equal(workspaceForSession(ITEMS, 's-b', null).workspaceId, 'ws-b')
})
test('workspaceForSession 在会话归属缺失时按 cwd 大小写/斜杠不敏感匹配', () => {
const loose = { cwd: 'd:\\work\\b\\' }
assert.equal(workspaceForSession(ITEMS, 's-new', loose).workspaceId, 'ws-b')
})
test('workspaceForSession 匹配不到时返回 cwd 作为 path 兜底', () => {
const out = workspaceForSession(ITEMS, 's-new', { cwd: 'E:\\NewPlace' })
assert.equal(out.workspaceId, null)
assert.equal(out.path, 'E:\\NewPlace')
assert.equal(out.name, 'NewPlace')
})
test('sessionSummaryFromSnapshot 按会话 id 读 cwd', () => {
const summary = sessionSummaryFromSnapshot({ byId: { 's-a': { cwd: 'C:/Work/A' } } }, 's-a')
assert.equal(summary.cwd, 'C:/Work/A')
assert.equal(sessionSummaryFromSnapshot({ byId: {} }, 's-a'), null)
assert.equal(workspaceForSession(ITEMS, '', null), null)
})