feat(sansheng): 三省六部工作台 v0.2 实施(WP0-WP7 候选)
- WP0: 版本/接口基线、v3 数据契约与发布路线(docs/verification) - WP1: 原生侧栏底部入口 + 右栏角色页签 + 项目上下文(不接管 main.conversation) - WP2: 项目绑定唯一性、Bot 名去重、模型只影响本项目、ds-bot 投递/记忆项目边界 - WP3: 最新判决门禁、unknown 身份/损坏状态拒绝、跨项目/跨群解析防护 - WP4: 服务端成果快照(Git/manifest)、审查绑定摘要/快照/提交代次 - WP5: prepared/in_flight/confirmed/rejected/unknown 派发状态、requestId 幂等、重启核实 - WP6: 状态投影(phase/attention/currentStage/历史折叠)、断连与过期提示 - WP7: 121 项测试 + 隔离测试 profile 真实宿主冒烟;候选版本,E01-E04 未执行 测试: node --test --test-isolation=none sansheng/test/*.test.js -> 121/121 pass
This commit is contained in:
parent
3f20f89bd5
commit
b955513ec4
|
|
@ -2,6 +2,7 @@
|
|||
.research/
|
||||
node_modules/
|
||||
*.log
|
||||
dist/
|
||||
.stats.html
|
||||
review_results.json
|
||||
# 生图实验残留,不进版本历史;要留下的预览图放 docs/
|
||||
|
|
|
|||
23
README.md
23
README.md
|
|
@ -15,14 +15,19 @@
|
|||
|
||||
| 入口 | 说明 |
|
||||
| --- | --- |
|
||||
| `sansheng_provision` | 创建一个项目:丞相 / 尚书 / 工部三个 Bot + 项目群(尚书是管理员) |
|
||||
| `sansheng_bind` | 把已有群绑成三省六部项目(校验三角色齐全、管理员是尚书) |
|
||||
| `sansheng_status` | 项目、群、角色、模型、目标阶段、返工预算、待核实派发 |
|
||||
| `sansheng_review` | 尚书记阶段通过/驳回,丞相记目标验收;`group_goal` 用它做门禁 |
|
||||
| 项目树右键菜单 | 工作区菜单「三省六部 / 初始化三省六部」;会话菜单「打开三省六部」,复用现有项目树,不新增第二棵树 |
|
||||
| 右栏「角色」页签 | 当前项目的丞相 / 尚书 / 工部三张卡片;点击角色打开真实会话;配置与历史审查默认折叠 |
|
||||
| `sansheng_provision` | 创建项目:三 Bot + 项目群(尚书是管理员);默认名重名时自动加项目后缀,保证全局唯一 |
|
||||
| `sansheng_bind` | 把已有群绑成项目(校验三角色齐全、管理员是尚书、Bot/群唯一) |
|
||||
| `sansheng_status` | 项目、群、角色、模型、目标阶段、返工预算、写租约、成果代次、待核实派发 |
|
||||
| `sansheng_review` | 尚书记阶段通过/驳回,丞相记目标验收;自动生成并绑定成果快照,最新判决与摘要/代次不一致即失效 |
|
||||
| `sansheng_submit` | 提交成果快照(Git / 非 Git manifest),推进提交代次 |
|
||||
| `sansheng_config` | 只改本项目的模型/返工预算/自动返工/交付范围 |
|
||||
| `sansheng_control` | 用户暂停/恢复/停止/取消目标 |
|
||||
| `sansheng_lease` | 项目写租约(第一版每项目最多一个活动写任务) |
|
||||
| `sansheng_reconcile` | 重启后核对"结果未知"的派发(不重发、不假装成功) |
|
||||
| 右栏「角色」页签 | 纵向三张卡片:丞相 / 尚书 / 工部,读 `/sansheng/state`,4 秒刷新 |
|
||||
|
||||
`group_goal` 仍是阶段进度的唯一权威;尚书是唯一操作者,丞相只验收,工部只执行。
|
||||
`group_goal` 仍是阶段进度的唯一权威;尚书是唯一操作者,丞相只验收,工部只执行。项目隔离由服务端治理服务 `sansheng-governance` 落到 ds-bot 的投递与记忆边界,不只靠提示词。
|
||||
|
||||
根目录 `package.json` 只是工作区清单(`workspaces: sansheng, ds-bot`),本身不是 DSH 插件,也不进 `dsh.profile.bundles`。
|
||||
|
||||
|
|
@ -44,11 +49,13 @@
|
|||
## 验证
|
||||
|
||||
```sh
|
||||
cd sansheng && npm test # 56 tests:门禁、指纹、存储、派发回执、返工、状态接口、客户端渲染、provision 流程
|
||||
node --test --test-isolation=none sansheng/test/*.test.js # 121 tests
|
||||
node --check sansheng/client.js && node --check sansheng/index.js
|
||||
```
|
||||
|
||||
Node >= 22。
|
||||
Node >= 22。测试覆盖:门禁最新判决、成果快照、项目隔离、派发幂等/恢复、状态投影、客户端注册与渲染、provision 流程。
|
||||
|
||||
WP0–WP7 的实施与验收状态见 [docs/verification/00-baseline.md](docs/verification/00-baseline.md)、[01-contracts.md](docs/verification/01-contracts.md)、[02-test-matrix.md](docs/verification/02-test-matrix.md)、[03-host-smoke.md](docs/verification/03-host-smoke.md)。当前是**候选版本**:隔离测试 profile 已验证真实宿主加载、右栏入口、初始化项目和角色会话;真实模型 E2E 与日常 profile 升级未执行。
|
||||
|
||||
重启后自检:
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,110 @@
|
|||
# WP0 基线、接口与发布路线
|
||||
|
||||
日期:2026-11-13(Asia/Shanghai)
|
||||
状态:实施前核对记录。后续验证结果按测试 ID 写入本目录其他文件。
|
||||
|
||||
## 1. 仓库基线
|
||||
|
||||
| 项 | 值 |
|
||||
| --- | --- |
|
||||
| 仓库 | `C:\Users\qyh15\三省六部` |
|
||||
| 分支 | `feat/dsbot` |
|
||||
| 基准提交 | `3f20f89`(工作树在开工时仅多出交接方案文档) |
|
||||
| 远端 | `origin https://git.qyhhh.top/newbie/dsh-sansheng-liubu.git` |
|
||||
| 根工作区 | `workspaces: ["sansheng", "ds-bot"]`,根 `package.json` 不是 DSH 插件 |
|
||||
| 治理包 | `sansheng/` = `dsh-sansheng-sansheng@0.2.0`(本次发布候选) |
|
||||
| 团队底座 | `ds-bot/` = `ds-bot@0.3.2-sansheng.1`(上游 `Fei2411/DS-Bot@84c3cb8` + 本地 M-01–M-05) |
|
||||
| Node | v24.21.0(DSH 随附 `~/.dsh/dsh-runtimes/dsh-primary-runtime/dependencies/node/bin/node.exe`) |
|
||||
| 桌面宿主 | DeepSeek Harness 0.2.2-rc.3(`resources/runtime/primary-runtime/runtime.json`) |
|
||||
| 基线测试 | `node --test --test-isolation=none sansheng/test/*.test.js` → 56/56 通过(2026-11-13) |
|
||||
|
||||
## 2. 已安装对象(只读核对,不修改)
|
||||
|
||||
读取位置:`%USERPROFILE%\.dsh\profiles\desktop`。
|
||||
|
||||
| 对象 | 已安装版本 | 状态 |
|
||||
| --- | --- | --- |
|
||||
| `dsh-sansheng-liubu-mode` | 0.14.0 | 旧十席工作台,仍在 `dsh.profile.bundles` |
|
||||
| `workspace-groups-remote` | 1.3.0 | 当前项目树插件,仍在 bundles |
|
||||
| `dsh-better-sidebar` | 0.32.1 | 右栏页签接入 |
|
||||
| `dsh-better-chat` | git 源 | 聊天插件,纳入布局回归观察 |
|
||||
| `ds-bot` | 本仓库 junction(`C:\Users\qyh15\三省六部\ds-bot`) | node_modules 中存在,但 **不在** `dsh.profile.bundles` |
|
||||
| `dsh-sansheng-sansheng` | 未安装 | 本仓库治理包尚未挂进 desktop profile |
|
||||
|
||||
结论:当前桌面运行的是旧十席工作台,不是本仓库新方案。实施只改仓库,不修改 daily profile、node_modules 或代装升级;真实宿主端到端验收需另建测试环境,缺环境时交付候选版本并明确标注。
|
||||
|
||||
## 3. 接口契约(只读核对)
|
||||
|
||||
来源:本机插件源码、`docs/p0/*.md`、archive-manager / workspace-groups-remote 的客户端实现。所有接口均在运行时用 `ctx.get(name, false)` 或 `ctx.<service>` 探测,不做私有 DOM 操作。
|
||||
|
||||
### 3.1 工具拦截与观察
|
||||
|
||||
| 能力 | 契约 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `ctx.tools.guard(fn)` | 同步;`fn(exec) => string \| undefined`。返回字符串即拒绝,工具体不执行,模型收到 `isError:true`。根 ctx 注册对 Bot 群 Session 生效。 | `group_goal` 门禁 |
|
||||
| `ctx.on('tools/execute', (exec, next) => ...)` | 包裹工具执行;`next()` 返回原生结果。 | 派发记录、返工观测 |
|
||||
| `exec.agent.id` | 执行会话 id。经 DS Bot `state.json` 反查 `chatOwners/groupOwners` 得到 Bot 与群。 | 身份判定 |
|
||||
| `rt.isBotSession(sessionId)` | DS Bot 运行时判断某会话是否 Bot 会话。`ctx.get('dsbot-runtime')` 获得(M-01)。 | 区分用户会话 / Bot 会话 / 未知过期身份 |
|
||||
|
||||
### 3.2 项目树(workspace-groups-remote 1.3.0)
|
||||
|
||||
- 项目树注册在 `sidebar.workspaces`;项目 = 宿主 workspace,会话挂在其下。
|
||||
- 没有第三方可用的"项目行动作"槽位;项目/文件夹行菜单是插件内部实现。
|
||||
- 宿主的 **原生上下文菜单服务** `contextMenus.register({ id, target, order, observe, resolve })` 可用(archive-manager 同款):`target: "workspace"` 的 `resolve({ workspaceId, path, displayTitle })` 返回菜单项数组 `{ id, label, icon, run, disabled, separatorBefore }`;`target: "session"` 的 `resolve({ sessionId, displayTitle })` 同构。该服务在 `ctx.get('contextMenus')` 或 `ctx.contextMenus`。
|
||||
- 当前项目推导:`workspaces.list.getSnapshot().items[]` + `sessions.list.getSnapshot().byId`。当前会话取 `retainedBy.mainView > 0` 的唯一会话(旧工作台 0.14.0 已验证的宿主等价事实),再按 `item.sessionIds.includes(sessionId)` 得 `workspaceId`。无明确选择时返回 null,不拿第一个项目冒充。
|
||||
|
||||
### 3.3 会话与右栏
|
||||
|
||||
| 能力 | 契约 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `ctx.uiWorkspace.openSession(sessionId)` | 打开会话页签;失败时退回 `uiWorkspace.selection.set({ sessionId })` | 点击角色打开真实会话 |
|
||||
| `ctx.uiWorkspace.startSession(workspaceId)` | 在空工作区创建并打开会话(旧工作台使用的宿主动作);不存在时给出可读错误 | 项目树入口在无会话项目上打开工作台 |
|
||||
| `ctx.sidebarRightTabs.register({ id, kind, priority, title, keepMounted })` | 注册右栏页签 | 「三省六部」页签 |
|
||||
| `ctx.slots.register({ name: 'sidebar.right.pane.tab', key }, Component)` | 页签内容 | 三卡与配置 |
|
||||
| `ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key }, Component)` | 页签标题 | 角标 |
|
||||
| `ctx.slots.register({ name: 'conversation.session.header.actions', id, order }, Component)` | 会话头按钮 | 「三省」快捷入口 |
|
||||
| `ctx.get('sidebarRight')` / `ctx.get('betterSidebar')` | 旧版右栏打开接口;`openTabIn(sessionId, kind)` / `openTab({type})` | 兼容回退,不虚报成功 |
|
||||
|
||||
### 3.4 DS Bot 运行时(团队底座)
|
||||
|
||||
- 运行时暴露:`ctx.provide('dsbot-runtime', rt)`(M-01),只读状态文件 `$DSH_HOME/bot/state.json`。
|
||||
- 可复用钩子:`createBot/updateBot/deleteBot/createRoom/updateRoom/deleteRoom/applyModel/updateBot/resolveModel`、`deliver`、`goalControl`、`findBot/findRooms/isAdminOf/isMain/selfOf/isBotSession`、`roomOf/roomOfSession`。
|
||||
- `group_goal` 业务拒绝以普通字符串返回,`isError` 不置位;因此派发结果必须结合目标 revision/id 前后快照判定,不能靠英文错误前缀。
|
||||
- 记忆作用域:`own`(每 Bot)、`group`(每群)、`team`(所有 Bot 共享)。Team 作用域是跨项目泄漏点,需治理服务按项目拒绝读写。
|
||||
|
||||
### 3.5 治理服务(本仓库新增,供 ds-bot 补丁调用)
|
||||
|
||||
`sansheng` 启动时 `ctx.provide('sansheng-governance', api)`(若宿主支持):
|
||||
|
||||
```js
|
||||
api = {
|
||||
version: 3,
|
||||
projectOfBot(botId) -> { id, name } | undefined,
|
||||
projectOfRoom(roomId) -> { id, name } | undefined,
|
||||
checkDelivery({ fromId, toId, roomId }) -> { allow: boolean, reason?: string },
|
||||
checkMemoryScope({ botId, scope: 'own'|'group'|'team', roomId }) -> { allow: boolean, reason?: string },
|
||||
}
|
||||
```
|
||||
|
||||
ds-bot 侧只在服务存在时执行检查;不存在时保持上游行为。补丁写入 `ds-bot/PATCHES.md`。
|
||||
|
||||
## 4. 数据兼容
|
||||
|
||||
- `sansheng` 状态文件默认 `$DSH_HOME/sansheng/state.json`。v2 → v3 迁移:保留 `projects/reviews/dispatches/reworks/events`,新增 `artifacts/leases/seq`;旧字段 `digest` 继续作为 `reviewSubjectDigest` 的别名读取。迁移只补字段,不改写历史记录,不删除旧项目。
|
||||
- 旧十席工作台数据(`dsh-sansheng-liubu-mode`)与 DS Bot 的 `state.json` 均不迁移、不写入。旧工作台退出方案仅文档说明:升级顺序为先停旧包再启用新包,避免同时注册入口。
|
||||
- 旧 `ds-bot` 状态文件只读;所有项目绑定保存在 `sansheng` 自己的文件。
|
||||
|
||||
## 5. 发布路线
|
||||
|
||||
1. 仓库分支 `feat/dsbot` 提交 WP0–WP7 变更;按工作包分提交,每个提交附问题、实现、测试与限制。
|
||||
2. 推送至 `origin/feat/dsbot`;用 Gitea PR 审查合并(不按历史 URL 擅自推送其他仓库)。
|
||||
3. 产出两个可安装包的 tarball:`dsh-sansheng-sansheng-<version>.tgz` 与 `ds-bot-<version>.tgz`,附 `docs/verification/` 证据与升级说明。
|
||||
4. 用户自行决定是否更新日常 desktop profile;本次不代装、不重启用户应用。
|
||||
|
||||
## 6. WP0 退出条件核对
|
||||
|
||||
- [x] 唯一实现:`sansheng + ds-bot` 三角色方案;旧十席工作台仅历史参考。
|
||||
- [x] 可构建发布包:两个子包均为 ESM,Node 24 可运行,测试命令已确认。
|
||||
- [x] 项目树入口无公开项目动作 API → 采用宿主原生 `contextMenus` workspace/session 菜单 + 右栏页签;不使用私有 DOM。
|
||||
- [x] 不依赖直接修改宿主才能成立的功能;ds-bot 必要补丁均记录在 PATCHES。
|
||||
- [x] 旧数据保留策略明确,无自动迁移。
|
||||
|
|
@ -0,0 +1,176 @@
|
|||
# 实施契约 v3(内部工作约定)
|
||||
|
||||
本文件是实施期间各模块的唯一接口约定。改动共享契约先改此文件,再改调用者。
|
||||
|
||||
## 1. Store schema v3
|
||||
|
||||
`SanshengStore.peek()`:
|
||||
|
||||
```js
|
||||
{
|
||||
version: 3,
|
||||
seq: 0, // 服务端单调序号:review/dispatch/artifact/event 共用
|
||||
projects: { [projectId]: ProjectBinding },
|
||||
reviews: [Review],
|
||||
dispatches: [DispatchRecord],
|
||||
reworks: [ReworkRecord],
|
||||
artifacts: { [artifactId]: ArtifactSnapshot },
|
||||
leases: { [projectId]: WriteLease },
|
||||
events: [Event],
|
||||
}
|
||||
```
|
||||
|
||||
### ProjectBinding
|
||||
|
||||
```js
|
||||
{
|
||||
id: 'prj-xxxxxxxx',
|
||||
schemaVersion: 3,
|
||||
name, workspaceId, hostWorkspaceId, projectTreeId, workDir,
|
||||
roomId,
|
||||
bots: { lead, shangshu, gongbu },
|
||||
models: { lead?, shangshu?, gongbu? },
|
||||
maxReworks: 3,
|
||||
autoRework: true,
|
||||
delivery: { include: [], exclude: [] }, // ArtifactSnapshot 交付范围
|
||||
submissionSeq: 0, // 成果提交代次(每项目)
|
||||
createdAt, updatedAt
|
||||
}
|
||||
```
|
||||
|
||||
约束(`saveProject` 内校验,抛 `SanshengStoreError`,`code` 见括号):
|
||||
|
||||
- 同一 `roomId` 只能属于一个项目(`room-taken`)。
|
||||
- 三角色 Bot 互不相同(`roles-duplicated`)。
|
||||
- 同一 Bot 只能属于一个项目(`bot-taken`)。
|
||||
- 已有项目升级时保留未提供的字段。
|
||||
|
||||
### Review v3
|
||||
|
||||
```js
|
||||
{
|
||||
id: 'rev-xxxxxxxx', seq: 17,
|
||||
projectId, goalId, goalRevision,
|
||||
kind: 'stage'|'goal',
|
||||
stageIndex: number|null, stageTitle,
|
||||
reviewSubjectDigest: string, // 验收标准+任务范围(digest.js)
|
||||
artifactSnapshotId: string|null,
|
||||
artifactDigest: string|null,
|
||||
submissionSeq: number, // 生成审查时的项目成果代次
|
||||
verdict: 'pass'|'reject',
|
||||
reviewerRole: 'shangshu'|'lead'|'user',
|
||||
reviewerBotId, reviewerSessionId,
|
||||
evidence, reason, at, eventKey
|
||||
}
|
||||
```
|
||||
|
||||
### ArtifactSnapshot
|
||||
|
||||
见 `src/artifact.js` 的 `captureArtifactSnapshot`。必须包含:`id/projectId/goalId/scope/stageIndex/workDir/kind(baseCommit/diffDigest/manifest digest)/files[]/digest/fileCount/totalBytes/truncated/policy/createdAt`。
|
||||
|
||||
### DispatchRecord
|
||||
|
||||
```js
|
||||
{
|
||||
id: 'dsp-xxxx', requestId, payloadDigest,
|
||||
bootId, projectId, roomId, goalId, goalRevision,
|
||||
action, stageIndex, actorBotId, actorRole, actorName, reason,
|
||||
status: 'prepared'|'in_flight'|'confirmed'|'rejected'|'unknown'|'cancelled',
|
||||
revisionAfter, nativeResult: { ok, text }, note,
|
||||
at, sentAt, finishedAt, reconciledBy, reconciledAt, resolvedBy, resolvedAt
|
||||
}
|
||||
```
|
||||
|
||||
- `beginDispatch`:同 `requestId` + 同 `payloadDigest` 返回 `{record, replay:true}`,不再写;同 id 不同 digest 抛 `SanshengStoreError('payload-conflict')`。
|
||||
- `markDispatchInFlight(id)`:发送前落盘。
|
||||
- `finishDispatch(id, patch)`。
|
||||
- `reconcileDispatches(bootId)`:只把 `prepared`/`in_flight` 标 `unknown`;`confirmed`/`rejected` 不动。
|
||||
|
||||
## 2. digest.js
|
||||
|
||||
- `stageDigest(goal, stageIndex)` = 阶段验收范围(stageId/title/acceptance/tasks[id,botId,task]),**不含** status/note,避免纯执行状态变化使审查无意义失效。
|
||||
- `goalDigest(goal)` = objective/acceptance/constraints + 各阶段 stageDigest,**不含** status。
|
||||
- `artifactDigestOf(snapshot)` = snapshot.digest。
|
||||
- 兼容别名:`reviewSubjectDigest(kind, goal, stageIndex)`。
|
||||
|
||||
## 3. gate.js
|
||||
|
||||
`evaluateGoalAction({ action, actor, project, goal, reviews, members, args, reworks, artifact, projectFreshness })`
|
||||
|
||||
- `actor.kind === 'unknown'` → 拒绝(`unknown-actor`)。
|
||||
- `actor.kind !== 'bot'` → 用户放行(用户操作不是 Bot 越权;需服务端另验会话来源)。
|
||||
- Main Bot → 拒绝(`main-bot`)。
|
||||
- 最新判决算法:先按 `projectId/goalId/kind/stageIndex/reviewerRole` 取 `seq` 最大(无 seq 时按数组末尾);**先取最新再审摘要**,最新是 reject 就拒绝,不能跳过 reject 找旧 pass。
|
||||
- 通过校验:`review.goalRevision === goal.revision`(并发前置条件)且 `reviewSubjectDigest === 当前摘要` 且 `artifactDigest === 当前 artifact.digest`(项目有 workDir 时)且 `submissionSeq === project.submissionSeq`。
|
||||
- 阶段 `pass/rework`:用 stage 审查;目标 `complete`:用 goal 审查且 reviewerRole=lead;全部阶段必须 passed。
|
||||
- `projectFreshness` 为 `'missing'|'broken'|'stale'` 时受治理写操作拒绝(`state-unavailable`)。
|
||||
|
||||
## 4. artifact.js
|
||||
|
||||
```js
|
||||
export const DEFAULT_EXCLUDES
|
||||
export function deliveryPolicyOf(project) -> { include, exclude, maxFileBytes, maxFiles }
|
||||
export async function captureArtifactSnapshot({ project, goal, stageIndex=null, scope='stage', policy, now=Date.now() }) -> snapshot
|
||||
export async function verifyArtifactSnapshot({ snapshot, project, policy }) -> { ok, reason?, current }
|
||||
export function summarizeSnapshot(snapshot) -> { digest, kind, fileCount, totalBytes, truncated, baseCommit, diffDigest }
|
||||
```
|
||||
|
||||
- workDir 为空:`kind:'unscoped'`,digest 稳定;`verify` 对 unscoped 返回 ok(向后兼容),但 `sansheng_review` 仍记录。
|
||||
- workDir 不存在:`kind:'missing'`,digest 稳定;verify 只在两者都 missing 时 ok。
|
||||
- Git:`baseCommit` (`git rev-parse HEAD`,可空)、`statusDigest`(`git status --porcelain=v1 -z`)、`diffDigest`(`git diff HEAD --binary` 的 sha256);交付范围内未跟踪文件逐个 hash。
|
||||
- 非 Git:递归 manifest,排除目录/敏感文件,按路径排序,逐文件 sha256(>64MB 记 size+mtime)。
|
||||
- 排除:`.git,node_modules,.venv,venv,__pycache__,dist,build,coverage,.next,.cache,.turbo,target,out,*.log,*.tmp,.env*,.npmrc,.pypirc,*.pem,*.key,*.p12,id_rsa*,credentials*`。
|
||||
- 快照在服务端生成;不接受调用方提供的 hash 作为事实。
|
||||
|
||||
## 5. identity.js
|
||||
|
||||
```js
|
||||
resolveActor({ dsbot, store, sessionId, isBotSession }) -> {
|
||||
kind: 'user'|'bot'|'unknown',
|
||||
trusted: boolean, sessionId, botId?, botName?, isMain?, project?, role?, reason?
|
||||
}
|
||||
```
|
||||
|
||||
- 无 `sessionId` → user(host 直接调用)。
|
||||
- `sessionId` 是 Bot 会话(`isBotSession(sessionId)` 或 state 索引命中)但反查不到 Bot → `unknown`(过期/损坏身份)。
|
||||
- 非 Bot 会话 → user。
|
||||
- Bot 命中多个项目 → `projectConflict: true`,`project` 取唯一命中;多个时 gate 拒绝(`project-conflict`)。
|
||||
|
||||
## 6. Governance service(sansheng → ds-bot)
|
||||
|
||||
见 `docs/verification/00-baseline.md` §3.5。实现于 `src/governance.js`。
|
||||
|
||||
## 7. HTTP 端点(`src/route.js`)
|
||||
|
||||
| 方法 | 路径 | 作用 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/sansheng/state?workspaceId=&sessionId=` | 状态投影;返回 `{ generatedAt, projects, current, health }` |
|
||||
| GET | `/sansheng/health` | 存储/DS Bot 状态新鲜度 |
|
||||
| POST | `/sansheng/project/resolve` | `{ workspaceId, path, title }` → `{ project }` 或 `{ missing:true }` |
|
||||
| POST | `/sansheng/provision` | `{ workspaceId, path, name, models, maxReworks }` → 创建项目(与工具共用核心) |
|
||||
| POST | `/sansheng/config` | `{ projectId, models, maxReworks, autoRework }` → 仅改本项目 |
|
||||
| POST | `/sansheng/control` | `{ projectId, action: pause|resume|stop }` → 调用 `rt.goalControl`(用户操作) |
|
||||
| POST | `/sansheng/reconcile` | `{ projectId, id, verdict }`(尚书或用户) |
|
||||
|
||||
所有写端点校验 `projectId` 与当前项目上下文,失败返回 4xx 与可读原因。
|
||||
|
||||
## 8. 状态投影(api.js)
|
||||
|
||||
每个 project 新增字段(不改顶部结构):
|
||||
|
||||
```js
|
||||
{
|
||||
phase: 'uninitialized'|'待配置'|'待执行'|'执行中'|'待审查'|'返工中'|'待核实'|'失败'|'暂停'|'已完成',
|
||||
attention: [{ role, reason, next }],
|
||||
currentStage: { index, title, acceptance, digest, taskCounts },
|
||||
submissionSeq, lastSubmission: {...}|null,
|
||||
reviewsHistory: [...], // 折叠历史区
|
||||
roles: [ { ..., sessionId, clickable, tone, next } ],
|
||||
}
|
||||
```
|
||||
|
||||
## 9. 测试
|
||||
|
||||
- 基线:`node --test --test-isolation=none sansheng/test/*.test.js`
|
||||
- 新增文件:`artifact.test.js`、`review-v3.test.js`、`isolation.test.js`、`dispatch-v2.test.js`、`api-v3.test.js`、`client.test.js`(扩展)。
|
||||
- 全部用隔离临时目录,不碰用户状态。
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
# 验收矩阵与证据状态(候选版本)
|
||||
|
||||
日期:2026-11-13
|
||||
结论:**候选版本**。仓库内自动化回归通过;已在隔离测试 profile(独立 DSH_HOME,宿主 0.2.2-rc.3)完成真实宿主冒烟:右栏入口、初始化项目、三卡与角色会话可打开、输入框位于底部,证据见 `03-host-smoke.md`。真实模型 E2E(E01–E04)、workspace-groups 项目树右键、深色/窄屏仍缺失;用户日常 desktop profile 未修改。
|
||||
|
||||
## 1. 自动化测试入口
|
||||
|
||||
```sh
|
||||
node --test --test-isolation=none sansheng/test/*.test.js
|
||||
node --check sansheng/client.js
|
||||
node --check sansheng/index.js
|
||||
```
|
||||
|
||||
测试目录新增:
|
||||
- `artifact.test.js`:成果快照(Git/非 Git/排除/缺失/sync=async)
|
||||
- `review-v3.test.js`:最新判决、成果/代次、G01–G07、A01–A05
|
||||
- `isolation.test.js`:I01–I06 与写租约
|
||||
- `dispatch-v2.test.js`:R01–R05
|
||||
- `api-v3.test.js`:状态投影与历史折叠
|
||||
- `gate-install.test.js`:F01、unknown 身份、治理损坏、跨项目
|
||||
- `client.test.js`:右栏/入口/项目上下文(见 UI 工作包报告)
|
||||
|
||||
## 2. 入口与布局
|
||||
|
||||
| ID | 状态 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| U01 输入框原生底部 | 真实宿主冒烟部分通过 | 测试 profile 1440×900 截图输入框在底部;本方案不接管 `main.conversation`;长消息/连续工具流未测 |
|
||||
| U02 从项目树打开 A | 真实宿主冒烟通过(测试 profile) | 通过右栏初始化「演示项目」后,左栏出现项目与三角色、右栏三卡;workspace-groups 项目树右键未在该 profile 复现(DS Bot 页面占据左栏),组件级 contextMenus 测试通过 |
|
||||
| U03 右栏重复点击聚焦 | 组件级通过 | `openRolesTab` 优先 better-sidebar/openTabIn;现有测试覆盖回退 |
|
||||
| U04 Better Sidebar 缺失/失败 | 真实宿主冒烟通过(回退入口) | 测试 profile 无 better-sidebar:左栏底部「三省」按钮可打开右栏「角色」页签;见 `03-host-smoke.md` |
|
||||
| U05 小窗口/宽屏/主题 | 部分验证 | 1440×900 浅色截图;深色/窄屏未测 |
|
||||
| U06 A/B 切换旧响应不覆盖 | 组件级通过 | client 请求序号丢弃过期响应(UI 测试) |
|
||||
| U07 新目标不显示旧验收 | 通过(api-v3) | 按 goalId 过滤 + 历史折叠 |
|
||||
| U08 先 reject 后 pass 不显示旧返工 | 通过(api-v3) | 当前阶段最新判决决定卡片 |
|
||||
| U09 断连/过期/配置失败提示 | 组件级通过 | 保留上次数据但显示“连接中断”;配置表单错误就地显示 |
|
||||
|
||||
## 3. 隔离
|
||||
|
||||
| ID | 状态 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| I01 默认参数创建 A/B 成功且身份独立 | 通过(isolation I01) | 全局 Bot 名唯一算法 + 项目绑定互斥 |
|
||||
| I02 A 尚书绑 B 拒绝 | 通过(isolation I02) | `bot-taken` 校验,无半绑定 |
|
||||
| I03 B 会话显式 A / 私聊跨项目 | 通过(isolation I03/I03b + ds-bot M-04) | `resolveProjectForCall` 冲突拒绝;`checkDelivery` 覆盖 message_bot 私聊与 rt.deliver |
|
||||
| I04 修改 A 模型不影响 B | 通过(isolation I04) | `updateProjectConfig` 只更新 A 的 Bot 与绑定 |
|
||||
| I05 A 记忆不注入 B | 源码级通过 / 真实宿主未验证 | M-05:team 作用域写入、读取、系统提示、autoRecall、memoryUpdate 全部按项目拒绝;无 ds-bot 测试框架,仅语法/静态检查 |
|
||||
| I06 跨项目自动投递拒绝 | 通过(isolation I05/I06) | governance.checkDelivery + ds-bot delivery 补丁 |
|
||||
| I07 并行写入与工作根 | 部分通过 | 写租约测试通过;`workDir` 通过 `rt.createBot/updateBot` 落到 Bot;同根并发仍以单写租约为准,未做真实文件系统越界测试 |
|
||||
|
||||
## 4. 门禁与成果
|
||||
|
||||
| ID | 状态 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| G01 无丞相验收 complete 拒绝 | 通过(review-v3) | `no-goal-review` |
|
||||
| G02 非项目 Main 修改拒绝 | 通过(review-v3/gate) | `main-bot` |
|
||||
| G03 先 pass 后 reject 最新 reject 生效 | 通过(review-v3 F02/G03) | 先取最新判决再审摘要 |
|
||||
| G04 reject→pass;旧摘要不能复活 | 通过(review-v3) | 最新判决 + 摘要/成果/代次校验 |
|
||||
| G05 B 证据不能批准 A | 通过(isolation I03b) | 项目身份与 projectId 绑定 |
|
||||
| G06 检查后变更并发改判 | 部分通过 | guard 在最终变更入口同步复核;无真实并发宿主测试 |
|
||||
| G07 状态损坏不放行 | 通过(gate-install G07) | registry 提示 + `state-unavailable` |
|
||||
| A01 改已跟踪文件 | 通过(artifact/review-v3) | git diff digest |
|
||||
| A02 新增未跟踪交付文件 | 通过(artifact/review-v3) | untracked manifest |
|
||||
| A03 改验收标准/任务范围 | 通过(review-v3) | reviewSubjectDigest |
|
||||
| A04 测试后改成果 | 通过(artifact) | 快照 digest 变化即失效 |
|
||||
| A05 仅状态变更 revision 增长 | 通过(gate) | 审查对象摘要不含 status/note;revision 不参与审批有效性 |
|
||||
|
||||
## 5. 派发与恢复
|
||||
|
||||
| ID | 状态 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| R01 业务拒绝字符串不记 confirmed | 通过(dispatch-v2 R01) | 比较目标 revision/id 前后快照 |
|
||||
| R02 同 requestId 同 payload 不重发 | 通过(dispatch-v2 R02) | `beginDispatch` 幂等 + payloadDigest |
|
||||
| R03 回执丢失重启 | 通过(dispatch-v2 R03) | prepared/in_flight → unknown,不盲目重发 |
|
||||
| R04 intent/结果保存失败 | 通过(dispatch-v2 R04) | 事务克隆回滚 |
|
||||
| R05 返工与原生 @ 只执行一次 | 通过(dispatch-v2 R05) | 稳定 requestId + addRework 去重 |
|
||||
| R06 返工上限跨重启 | 通过(records/gate) | budgetOf 取原生累计与本地记录最大值 |
|
||||
| R07 暂停/取消/刷新 | 部分通过 | `sansheng_control`/route 调 `rt.goalControl`;停止请求与已停止分开显示;未做宿主 E2E |
|
||||
|
||||
## 6. 真实模型端到端
|
||||
|
||||
| ID | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| E01 正常交付 | 未执行 | 缺已授权测试宿主;不能在 daily profile 上跑真实项目 |
|
||||
| E02 驳回返工 | 未执行 | 同上 |
|
||||
| E03 双项目并行 | 未执行 | 自动化隔离测试覆盖数据层,不代替真实模型 |
|
||||
| E04 中断恢复 | 未执行 | 单测覆盖故障窗口,真实重启未验证 |
|
||||
|
||||
## 7. 发布门核对
|
||||
|
||||
| 项 | 状态 |
|
||||
| --- | --- |
|
||||
| P1 缺陷关闭且回归可复现 | F01–F08、F10、F11 仓库内修复/回归;F09 旧包不接管主聊天已在旧包临时止血,新方案不注册 main.conversation |
|
||||
| U/I/G/A/R 必选项 | 自动化项通过;U01/U05/U07/U08 的视觉与真实宿主项未验证 |
|
||||
| E01–E04 | 未执行 → 候选状态 |
|
||||
| 两包依赖/宿主兼容 | 明确:sansheng 0.2.0 + ds-bot 0.3.2(本地补丁 M-01–M-05) |
|
||||
| 数据保留/升级/回退 | v2→v3 只补字段;旧项目/审查保留;不迁移旧十席数据 |
|
||||
| 真实截图与 UI 复核 | 缺失,必须由用户测试环境补 |
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
# 真实宿主冒烟记录(隔离测试 profile)
|
||||
|
||||
日期:2026-11-14
|
||||
宿主:DeepSeek Harness 0.2.2-rc.3
|
||||
测试环境:`C:\dsh-sansheng-test`(独立 `DSH_HOME`,不触碰用户日常 `~/.dsh` 桌面 profile)
|
||||
启动命令:
|
||||
|
||||
```powershell
|
||||
$env:DSH_HOME = 'C:\dsh-sansheng-test'
|
||||
dsh --profile web-test --port 7399 --host 127.0.0.1 --no-open
|
||||
```
|
||||
|
||||
profile `web-test` 的 bundles:`@deepseek-ai/dsh-base`、`@deepseek-ai/dsh-web-app`、`ds-bot`、`dsh-sansheng-sansheng`;
|
||||
两个本仓库包通过 ASCII 路径 junction 以 `link:` 安装,避免中文路径被 pnpm 写坏。
|
||||
|
||||
## 已取得的真实宿主证据
|
||||
|
||||
| 项 | 结果 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| 两个包被宿主加载 | 是;页面 bundle 包含 `dsh-sansheng-sansheng/client.js` 与 `ds-bot/client.js` | 浏览器 console 无本插件报错 |
|
||||
| 服务端工具/路由 | `GET /sansheng/state` → 200 `{projects:[],current:null,health:{status:"ok"}}`;`GET /sansheng/health` → 200,返回独立 `sansheng/state.json` 与 DS Bot state 计数 | HTTP 响应(见下) |
|
||||
| 原生侧栏入口 | 左栏底部出现「三省」按钮;点击后在右栏打开「角色」页签 | `evidence/host-right-uninitialized.png` |
|
||||
| 未初始化项目 | 右栏显示「此项目尚未初始化」,初始化表单默认折叠,仅有项目名/工作目录/三个模型字段 | `evidence/host-init-form.png` |
|
||||
| 通过 UI 创建项目 | 成功创建「演示项目」三 Bot + 项目群;左栏出现 `演示项目 · 三省六部` 与 工部/尚书/丞相;右栏三张角色卡显示、可点击、无“会话缺失” | `evidence/host-right-roles.png` |
|
||||
| 成功回滚与错误提示 | 先尝试把工作目录放进 DSH_HOME,宿主拒绝(“holds DeepSeek Harness data”);UI 显示「初始化失败:…已回滚本次新建的 Bot」,未落半绑定 | 本次运行日志/UI 文本 |
|
||||
| 原生聊天布局 | 输入框保持在底部,右栏展开/收起不影响输入框几何(1440×900 截图) | `evidence/host-right-roles.png` |
|
||||
|
||||
HTTP 响应原文(初始空状态):
|
||||
|
||||
```json
|
||||
{"generatedAt":...,"projects":[],"current":null,"currentMatch":null,"health":{"status":"ok","error":null}}
|
||||
```
|
||||
|
||||
`/sansheng/health`:
|
||||
|
||||
```json
|
||||
{"store":{"status":"ok","path":"C:\\dsh-sansheng-test\\sansheng\\state.json","error":null,"registry":"C:\\dsh-sansheng-test\\sansheng\\registry.json"},"governance":true,"dsbot":{"path":"C:\\dsh-sansheng-test\\bot\\state.json","bots":0,"rooms":0}}
|
||||
```
|
||||
|
||||
创建项目后同一端点显示 `bots: 4, rooms: 1`(Chief + 三 Bot、一个项目群),说明 ds-bot 运行时与治理服务在同一真实宿主进程内可用;`governance:true` 表示 `sansheng-governance` 已注册。
|
||||
|
||||
## 未验证(本测试 profile 的限制)
|
||||
|
||||
- 测试 profile 没有 DeepSeek 账号 / API key,未执行真实模型对话,因此 E01–E04 未完成。
|
||||
- 测试 profile 另外尝试加入 `workspace-groups-remote@1.3.0` 做共存探测;DS Bot 页面仍占据左栏并显示 Bot/群列表,未渲染 workspace-groups 项目树,因此 workspace 右键菜单入口未在该宿主里右键验证(组件级测试通过)。
|
||||
- 深色模式、窄屏、长消息滚动、连续工具流、拖拽右栏宽度未截屏验证。
|
||||
- 未修改、未重启用户日常 desktop profile;因此日常桌面仍是旧十席工作台,不能把本记录当作日常桌面已升级。
|
||||
|
||||
## 结论
|
||||
|
||||
真实宿主已验证:包能加载、右栏入口可发现、初始化项目可落地、三卡可见且会话可点、输入框布局未被接管。
|
||||
真实模型 E2E、workspace-groups 项目树右键、深色/窄屏视觉仍属缺口,发布状态保持**候选版本**。
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
# 发布说明(候选版本 v0.2.0 / ds-bot 0.3.2-sansheng.1)
|
||||
|
||||
日期:2026-11-14
|
||||
状态:**候选版本**。可用于隔离测试环境;用户日常 desktop profile 未由实施者修改。
|
||||
|
||||
## 1. 产物
|
||||
|
||||
| 包 | 版本 | 文件 |
|
||||
| --- | --- | --- |
|
||||
| `dsh-sansheng-sansheng` | 0.2.0 | `dist/dsh-sansheng-sansheng-0.2.0.tgz` |
|
||||
| `ds-bot`(上游 0.3.2 + M-01–M-05) | 0.3.2-sansheng.1 | `dist/ds-bot-0.3.2-sansheng.1.tgz` |
|
||||
|
||||
构建命令(在包目录运行):
|
||||
|
||||
```powershell
|
||||
node <path-to-pnpm.cjs> pack --pack-destination ..\dist
|
||||
```
|
||||
|
||||
## 2. 兼容性
|
||||
|
||||
- 宿主:DeepSeek Harness 0.2.2-rc.3(本机真实宿主冒烟版本);0.2.x 同代接口按 `docs/p0` 记录。
|
||||
- Node:>= 22(本机 24.21.0)。
|
||||
- 两个包必须一起升级:`sansheng` 依赖 `ds-bot` 的 M-01 运行时句柄、M-04 投递边界、M-05 记忆域。
|
||||
仅升级 `sansheng` 会导致项目隔离与自动返工不可用;仅升级 `ds-bot` 不影响上游行为,但新工作台无入口。
|
||||
|
||||
## 3. 安装 / 升级(用户自行执行)
|
||||
|
||||
1. 备份(用 Git,不建 backup 目录):确认日常 profile 的 `package.json` 与 `cordis.patch.yml` 已在 Git 控。
|
||||
2. 停旧包:从 `dsh.profile.bundles` 移除 `dsh-sansheng-liubu-mode`(不要让旧十席与新方案同时注册入口)。
|
||||
3. 安装两个 tarball:
|
||||
```powershell
|
||||
dsh plugin --profile desktop add <绝对路径>\dsh-sansheng-sansheng-0.2.0.tgz <绝对路径>\ds-bot-0.3.2-sansheng.1.tgz
|
||||
```
|
||||
4. 确认 `dsh.profile.bundles` 含 `dsh-sansheng-sansheng` 与 `ds-bot`。
|
||||
5. 彻底重启 DSH(插件宿主半改动只有重启生效)。
|
||||
6. 自检:
|
||||
- 打开任一项目会话,左栏底部出现「三省」;点击后在右栏看到「角色」页签。
|
||||
- 未绑定项目显示「此项目尚未初始化」;初始化表单默认折叠。
|
||||
- 已绑定项目显示三张角色卡,点击卡片打开对应 Bot 真实会话。
|
||||
- `GET /sansheng/health` 返回 `governance: true`。
|
||||
|
||||
## 4. 回退
|
||||
|
||||
- 从 `dsh.profile.bundles` 移除两个新包,恢复升级前的 `package.json`/`cordis.patch.yml`(Git 回退)。
|
||||
- 旧十席工作台可继续使用;新旧不要同时启用。
|
||||
- `sansheng` 自己的状态文件保留在 `$DSH_HOME/sansheng/`,回退不删除;旧版不读 v3 字段时请先备份该目录(不属于用户数据迁移,只是回退保险)。
|
||||
|
||||
## 5. 数据迁移
|
||||
|
||||
- `sansheng` v2 → v3:只补 `seq/artifacts/leases/submissionSeq/delivery/schemaVersion`,保留旧 `projects/reviews/dispatches/reworks/events`。
|
||||
- 旧十席数据、DS Bot `state.json`、旧工作目录均不迁移、不删除。
|
||||
- 旧审查记录的 `digest` 被当作 `reviewSubjectDigest` 的兼容别名读取;新记录同时写两者。
|
||||
|
||||
## 6. 已知限制(必须随版本说明)
|
||||
|
||||
- 真实模型 E2E(E01–E04)未执行;隔离测试 profile 无 API key。
|
||||
- `workspace-groups-remote` 项目树右键菜单未在真实测试 profile 复现(DS Bot 页面占据左栏);组件级 contextMenus 测试通过。用户日常环境若项目树可见,右键「三省六部」应可用;若不可用,用左栏底部「三省」入口。
|
||||
- 深色模式、窄屏、长消息/连续工具流未截图验证。
|
||||
- 项目树适配采用宿主原生 `contextMenus` + `sidebar.footer.action` + 右栏页签;不使用私有 DOM。
|
||||
- `ds-bot` 补丁需在升级上游后重放(见 `ds-bot/PATCHES.md` 升级步骤)。
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
|
|
@ -0,0 +1,467 @@
|
|||
# 三省六部工作台:实施与验收交接方案
|
||||
|
||||
> 用途:交给其他 agent 实施。本文是目标方案与工作包,不是完成报告,也不代表已授权修改用户日常桌面。
|
||||
>
|
||||
> 编制日期:2026-11-13(Asia/Shanghai)
|
||||
>
|
||||
> 仓库基线:`C:\Users\qyh15\三省六部`,分支 `feat/dsbot`,提交 `3f20f89`。编制前工作树干净;本次只新增本文。
|
||||
>
|
||||
> 推荐目标:以 `sansheng/ + ds-bot/` 三角色方案为唯一业务实现,恢复可靠入口、原生聊天布局、项目隔离、审批及中断恢复。旧十席工作台只作为历史参考,不同时运行两套治理系统。
|
||||
|
||||
## 0. 给执行 agent 的第一条指令
|
||||
|
||||
先阅读本文及当前仓库约束,完成 WP0 的版本与接口核对,再按依赖顺序实施。不要直接修改用户的 desktop profile、安装目录、node_modules 或重启其日常应用。不要把仓库中的新方案误认为已经部署到桌面。
|
||||
|
||||
用户希望:左侧复用现有项目树,中间保留正常聊天,右侧是所属项目的角色和任务;入口可见可用,模型配置只影响所在项目,多项目可并行且互不干扰。界面极简,次要表单默认折叠。
|
||||
|
||||
本次用户要求的是详细方案。本文列出的修改是交接任务,不是编制者已执行的操作。后续 agent 收到实施授权后再修改代码、提交和发布;任何生产更新或数据迁移仍按第 12 节办理。
|
||||
|
||||
### 不得省略的完成条件
|
||||
|
||||
- 从现有项目树找到并打开目标项目工作台,不需要在控制台设置开关。
|
||||
- 普通聊天输入框保持原生布局,长消息、工具流及右栏调整不会使其漂移。
|
||||
- 三角色可配置并打开真实会话,目标从派工到验收可以实际跑通。
|
||||
- 审批不能被群名格式、身份解析、旧通过记录或其他项目证据绕过。
|
||||
- 审批与实际交付成果绑定,成果变化导致旧审批失效。
|
||||
- 两个项目并行时,配置、上下文、记忆、消息、任务及文件写入边界有效。
|
||||
- 中断与重启后可核实并恢复,不盲目重复投递,不伪造完成状态。
|
||||
- 有真实宿主验证证据;单元测试通过、HTTP 200、页面资源可下载均不能代替它。
|
||||
|
||||
## 1. 当前事实与证据等级
|
||||
|
||||
### 1.1 两套版本必须分开
|
||||
|
||||
| 对象 | 已核实状态 | 实施含义 |
|
||||
|---|---|---|
|
||||
| 当前仓库 | `feat/dsbot@3f20f89`,根工作区仅含 `sansheng`、`ds-bot` | 新功能与正式修复以此为起点,启动前重新检查是否有新提交 |
|
||||
| 治理插件 | `sansheng/`,包名 `dsh-sansheng-sansheng` | 三角色、审查、门禁、派发记录和右栏三卡 |
|
||||
| 团队底座 | `ds-bot/`,包名 `ds-bot` | 原生 Bot、群、会话、消息与目标账本;本地补丁记在 `ds-bot/PATCHES.md` |
|
||||
| 用户桌面安装包 | `dsh-sansheng-liubu-mode 0.14.0` | 旧十席工作台,不是本仓库当前治理实现 |
|
||||
| 桌面侧栏插件 | 审查时为 `dsh-better-sidebar 0.32.1` | 其 registerTab 接入右侧页签,不等于左侧项目树入口 |
|
||||
| 桌面聊天插件 | 审查时为 `dsh-better-chat 1.0.1` | 需要纳入布局兼容验证,未证明它是此次故障根因 |
|
||||
|
||||
本地安装证据目录:`C:\Users\qyh15\.dsh\profiles\desktop\node_modules\dsh-sansheng-liubu-mode`。不要把这个目录当作长期开发仓库。
|
||||
|
||||
### 1.2 已实施的临时操作
|
||||
|
||||
用户单独授权修复当前布局后,编制者只修改旧安装包的 `workbench/panel/lib/client.js`:将 `mainTakeoverEnabled()` 改成固定返回 `false`,阻止旧包注册 `main.conversation`。右栏注册代码未删除。
|
||||
|
||||
验证范围:JavaScript 语法通过;开关为未设置/off/on 时均不接管;静态复核右栏注册独立于该开关。尚无当前已登录桌面刷新后的截图与交互验证。因此只能称为“本地临时止血”,不能称为整体布局和入口已修复。该修改不在当前仓库 Git 历史中,升级旧包可能覆盖。
|
||||
|
||||
### 1.3 已确认问题清单
|
||||
|
||||
证据等级:A=调用真实模块的内存复现并核对源码;B=源码可确定,但尚未真实宿主复现;C=运行中现象或待验证假设。A 不等于真实模型端到端验证。
|
||||
|
||||
| ID | 优先级 | 对象与问题 | 证据 | 修复工作包 |
|
||||
|---|---|---|---|---|
|
||||
| F01 | P1 | 新治理门禁解析不到群就放行;原生可解析带引号群名或 Main 可见群 | A | WP3 |
|
||||
| F02 | P1 | 同版本先 pass 后 reject,查找会跳过 reject 命中旧 pass | A | WP3 |
|
||||
| F03 | P1 | Bot 绑定 A/B 后,B 审查写入先匹配的 A,显式 project=B 也无效 | A | WP2/WP3 |
|
||||
| F04 | P1 | team 记忆由各项目群管理员写入并向其他 Bot 注入;私聊投递没有项目边界 | B | WP2 |
|
||||
| F05 | P1 | 审批摘要只覆盖任务账本,未绑定代码/产物版本 | B;摘要行为有补充复现 | WP4 |
|
||||
| F06 | P2 | 原生 group_goal 业务拒绝返回字符串,观察器可能记为 confirmed | A(错误识别)+ B(完整观察链) | WP5 |
|
||||
| F07 | P2 | 默认 Bot 名固定,第二个项目创建因全局重名失败 | A | WP2 |
|
||||
| F08 | P2 | 右栏取项目全部历史审查,新目标显示旧验收/旧驳回 | A | WP6 |
|
||||
| F09 | P1 | 旧桌面包替换主聊天 root,丢失宿主限定 root 的底部定位规则 | B;用户截图有错位现象 | WP1 |
|
||||
| F10 | P1 | 旧桌面包没有左侧入口注册;只注册右栏 | B | WP1 |
|
||||
| F11 | P2 | 旧包 Better Sidebar 注册失败后不尝试已可用的原生右栏 | A | WP1 |
|
||||
|
||||
其他需检查但不得先宣布为缺陷:自动返工与原生再次 @ 指令是否重复投递、状态文件损坏时是否放行、持久化失败是否留下内存脏状态。纳入 WP3/WP5 故障测试后再定性。
|
||||
|
||||
原有 `sansheng/test/*.test.js` 的 56 项测试在审查时全部通过。此事实说明已有覆盖未捕获上述问题,不代表所有现存功能正确。
|
||||
|
||||
## 2. 产品范围与不做事项
|
||||
|
||||
### 2.1 第一版角色
|
||||
|
||||
| 角色 | 职责 | 允许行为 | 不允许行为 |
|
||||
|---|---|---|---|
|
||||
| 丞相 lead | 明确目标、验收标准,最终审查 | 目标审查通过/驳回、查看证据 | 不直接绕过尚书改原生阶段状态,不因 Main 身份获得其他项目写权限 |
|
||||
| 尚书 shangshu | 拆分、调度、核查阶段、返工协调 | 本项目 group_goal 写操作、阶段审查、派工与受控恢复 | 不代替丞相最终验收、不跨项目审查/派工 |
|
||||
| 工部 gongbu | 执行工单、测试、提交成果 | 本项目任务执行、成果和证据提交 | 不自行批准阶段或目标,不改审批记录 |
|
||||
| 人类用户 | 明确需求、处理必要决策、监督 | 可显式暂停/取消及确认敏感操作 | UI 不应把人工完成声明伪装成 agent 实测成功 |
|
||||
|
||||
如原生用户或 Main 存在特殊权限,必须明确策略并记录为人工/管理操作;不能通过“识别不了 actor,就按 user”获得权限。
|
||||
|
||||
### 2.2 页面范围
|
||||
|
||||
- 左侧继续使用现有项目树。优先在项目行提供可发现的“三省六部”动作或项目上下文入口,不增加第二棵项目树。
|
||||
- 中间由宿主原生会话负责消息、输入、工具流、滚动和草稿。禁止复制根组件、猜测 CSS 哈希或靠 DOM 搬移输入框修复。
|
||||
- 右侧工作台显示丞相/尚书/工部、当前目标、当前阶段、执行状态及待处理事项。
|
||||
- 点击角色打开该项目真实会话;打开前校验绑定存在,不默默创建替代会话。
|
||||
- 角色模型配置按需展开,只影响当前项目。执行中是否允许切换必须明示,默认仅对下一次执行生效。
|
||||
- 初始化表单只展示项目、工作目录和必要模型选择,其他字段折叠。
|
||||
- 左侧独立全局导航按钮不是默认新增范围。若项目树没有可用扩展 API,先调查扩展点并记录方案;不要直接改宿主或私有 DOM。
|
||||
|
||||
### 2.3 本期暂不做
|
||||
|
||||
十席全面扩展、复杂组织图、自动增加部门、自建聊天渲染器、自建任务看板底座、另一套原生目标状态机、大规模视觉重设计、跨项目共享知识推荐。不要为了看起来完整而扩大范围。
|
||||
|
||||
## 3. 目标架构与权威数据
|
||||
|
||||
### 3.1 边界
|
||||
|
||||
- `ds-bot`:Bot/群/会话生命周期、原生 group_goal 状态与消息投递机制。
|
||||
- `sansheng`:项目绑定、权限和隔离策略、审查、成果引用、派发对账、右栏状态投影。
|
||||
- 现有项目树插件:项目选择与管理。适配层把其稳定项目/工作区标识解析到 sansheng 绑定。
|
||||
- 宿主:会话根布局、输入框、身份上下文、权限、插件加载和原生右侧栏。
|
||||
|
||||
原生 `group_goal` 仍是目标/阶段进度的唯一权威。不要在治理存储再维护一个可独立前进的“完成状态”。派发、审批、UI 状态均应引用原生目标身份与版本。
|
||||
|
||||
### 3.2 建议数据扩展(方案,不是现有 API)
|
||||
|
||||
字段名称可随当前代码调整,但语义与约束必须保留。
|
||||
|
||||
**ProjectBinding**
|
||||
- 稳定 `projectId`;与项目树 ID、宿主 workspace ID 的显式映射,不用显示名称作身份。
|
||||
- `roomId`、三个 role→botId 绑定,以及可验证的会话关联。
|
||||
- 允许的工作根目录、project storage/工作目录策略、模型配置、schemaVersion。
|
||||
- 一个 Bot 在本模式第一版只属于一个项目;创建/绑定事务内检查唯一性。
|
||||
|
||||
**Review**
|
||||
- `projectId / goalId / stageId(目标审查可空) / scope / reviewer / verdict`。
|
||||
- `goalRevision`、稳定的审查内容摘要 `reviewSubjectDigest`、`artifactSnapshotId`、单调递增的成果提交代次;摘要相同不意味着可跨代次复用审批。
|
||||
- 服务端单调序号、创建时间、证据引用;历史追加写入,不覆盖原记录。
|
||||
- 同一被审查对象的最新判决决定有效性,不能先按 verdict 过滤再找最新。
|
||||
|
||||
**ArtifactSnapshot**
|
||||
- 项目和任务身份、工作根、基准提交、受控文件清单及内容摘要。
|
||||
- 未提交变更与纳入交付的新增文件也必须覆盖;不能只记录 HEAD。
|
||||
- 测试证据标识、命令、执行位置、开始/结束时间、退出状态及日志引用。
|
||||
- 大文件按策略记录摘要/外部引用,不把原文塞进审查记录;敏感文件不得自动收集。
|
||||
|
||||
**DispatchRecord**
|
||||
- project/goal/stage/task、动作、发起身份、确定的 requestId/payloadDigest。
|
||||
- 状态、关联原生投递/工作 ID、原生结果及必要状态版本。
|
||||
- 同 ID 同 payload 不重复发送;同 ID 不同 payload 拒绝;未知结果进入核实。
|
||||
|
||||
### 3.3 版本摘要需要拆开
|
||||
|
||||
不要把所有变化压成一个 digest:
|
||||
1. 业务账本版本用于并发控制,任何相关状态变化可推进它。
|
||||
2. 审查对象摘要描述验收标准、任务范围与成果引用;纯显示变化不应产生无意义失效。
|
||||
3. 成果摘要描述实际文件/产物内容。
|
||||
|
||||
阶段通过本身可能推进原生 revision 或改变 status。实现时必须明确审查适用于哪个 precondition,以及通过事件如何记录引用;否则“审查通过→状态变化→审批立即失效”会形成新死锁。目标验收应在阶段均通过后针对完整成果重新出具。
|
||||
|
||||
## 4. 工作包与依赖
|
||||
|
||||
依赖顺序:WP0 → WP1;WP0 → WP2 → WP3 → WP4;WP3/WP4 → WP5;WP1/WP2/WP5 → WP6 → WP7。
|
||||
|
||||
少量独立测试/界面工作可并行,但数据契约必须先确定。不要让多个 agent 同时修改同一个核心文件。
|
||||
|
||||
### WP0:版本归一与接口勘察
|
||||
|
||||
**任务**
|
||||
1. 检查 Git 状态、分支、当前提交、远端目标、子包版本及项目约束。
|
||||
2. 将仓库结构和只读获取的已安装 manifest 对照,列出实际运行版本差异。
|
||||
3. 查清目标宿主支持的左侧项目树扩展、右栏注册、会话导航、当前会话/工作区身份获取方式。
|
||||
4. 在仓库记录接口来源与版本。未知接口不得凭历史记忆编造。
|
||||
5. 盘点旧工作台数据与新方案是否可兼容;本期默认保留旧数据,不自动迁移。
|
||||
6. 确定发布产物包含哪些包以及相互兼容版本;不能仅升级治理包却遗漏必需的底座补丁。
|
||||
|
||||
**产物**:基线与差异说明、接口契约、数据兼容判断、发布路线。
|
||||
|
||||
**退出条件**:明确唯一实现和可构建发布包;没有需要直接修改宿主才能成立的未说明依赖。
|
||||
|
||||
### WP1:入口与原生布局
|
||||
|
||||
**任务**
|
||||
1. 新方案只注册工作台入口与右栏内容,不接管 `main.conversation`。
|
||||
2. 接通现有项目树的打开动作:项目选择→绑定查询→初始化或本项目工作台。
|
||||
3. 打开动作必须选择并展开正确页签,而非仅注册组件;支持重复点击聚焦已有页签。
|
||||
4. 右栏注册采用可验证的生命周期与失败回退。服务存在≠注册成功。
|
||||
5. 注册失败要显示可恢复错误,并有有限重试/服务重挂恢复;不能刷屏或无限循环。
|
||||
6. 当主入口不可用时,提供原生右栏可发现入口,内容清楚标明当前项目。
|
||||
7. 角色会话不存在时给出诊断与显式修复动作,不默默替换绑定。
|
||||
8. 给出旧插件退出运行的升级方案,避免旧/新客户端同时注册竞争入口。
|
||||
|
||||
**重要**:不要把旧安装目录中固定 false 的补丁复制成新架构;新方案应根本不注册聊天根接管。
|
||||
|
||||
**验收**:U01–U05。提交实际宿主截图,尤其要展示输入框位于底部、入口可见、角色会话能打开。
|
||||
|
||||
### WP2:项目绑定、创建与隔离
|
||||
|
||||
**任务**
|
||||
1. 默认 Bot 名加入稳定的项目区分部分;截断和重名时仍确保唯一。
|
||||
2. 创建过程支持失败清理,只清理本次新建对象;不能删除用户预先存在的 Bot/群。
|
||||
3. bind 检查角色互异、管理员正确、Bot 所属唯一及房间与项目的唯一约束。
|
||||
4. 按当前群/会话解析项目;显式 project 与上下文冲突时返回明确拒绝,而不是覆盖或忽略。
|
||||
5. 私聊指定项目必须核对调用 Bot 归属;未识别 actor 不自动视为人类。
|
||||
6. 模型与会话绑定通过宿主支持的 API 更新,只影响本项目。
|
||||
7. 项目 Bot 的记忆读写与注入使用项目域;通用 team 内容若允许共享,需有明确白名单,不接受任意项目事实进入公共注入。
|
||||
8. 覆盖原生 message_bot、群投递及 rt.deliver 等实际可达路径的项目检查;不能只在前端拦截。
|
||||
9. 明确文件工作根与并发策略:优先独立目录/受支持的隔离工作树;同根写入不能宣称互不干扰。第一版默认每项目最多一个活动写任务,只读检查可并行;写任务占用须有明确持有者、释放与重启核实机制,不能仅靠 UI 禁用按钮。
|
||||
10. 在原生 Bot 初始化、会话创建时确认实际工具权限和工作目录限制。仅给 prompt 写“不准跨项目”不构成边界。
|
||||
|
||||
**验收**:I01–I07。两个项目不共享角色 Bot;配置/上下文/消息/文件四类边界都提供证据。
|
||||
|
||||
### WP3:身份、权限与审查门禁
|
||||
|
||||
**任务**
|
||||
1. 提取或复用统一目标解析器,guard、review、observer 与原生执行使用相同群名规范化和可见性语义。
|
||||
2. 对可能修改受治理目标的调用,解析失败、绑定失效、治理状态不可读应拒绝并提供恢复提示。
|
||||
3. 已明确解析为非受治理目标的操作维持原生行为,避免把整个 DS Bot 团队锁死。
|
||||
4. 主 Bot 的原生管理权限不能跳过项目角色策略;人类特权若保留,必须显式归因并留痕。
|
||||
5. 审查查询先限定 project/goal/stage/scope 与合法审查身份,取最新判决,再验证该判决的审查对象摘要、成果引用及提交代次是否匹配当前版本;不得先按成果摘要或 verdict 过滤而跳过较新的驳回。成果提交代次被推进或审批被撤销后,即使内容恢复为旧摘要,也不得自动复活旧批准,须重新审查。对未提交、也未被系统观察到的瞬时文件变化,不宣称能够追溯;通过冻结交付快照与最终校验确保实际交付内容受控。
|
||||
6. 统一阶段和目标审查规则;防止 B 审查被用于 A。
|
||||
7. 对检查与执行之间的并发变化做服务端控制:在最终变更入口重新验证预期版本与审批/成果引用,不能只依赖较早的一次 guard。
|
||||
8. 验证持久化故障、状态损坏与重启初始化期间的处理策略;禁止“空状态=不受治理”自动放行。
|
||||
|
||||
**验收**:G01–G07;必须包括带引号群名、非成员 Main、先通过后驳回和并发改判。
|
||||
|
||||
### WP4:成果快照与证据
|
||||
|
||||
**任务**
|
||||
1. 定义“交付范围”:哪些目录、文件和产物属于任务,哪些为生成缓存/敏感内容不得自动纳入。
|
||||
2. 实现成果快照。Git 项目覆盖基线提交、受控变更、交付范围内未跟踪文件;非 Git 项目用受控 manifest+内容摘要。
|
||||
3. 快照在服务端生成并验证,不接受 agent 任意提交的 hash 作为事实。
|
||||
4. 测试证据必须关联执行与快照;无法证明测试覆盖最终快照时显示“未验证”。
|
||||
5. review 引用不可变快照;pass/complete 前重新检查交付范围是否变化。
|
||||
6. 固定并发写入策略,确保校验之后不会继续修改已交付成果。可采用冻结快照与从快照交付、版本锁等方式;需说明 TOCTOU 防护。
|
||||
7. 对人工提供的证据单独标记来源,不伪装成宿主执行证据。
|
||||
8. 明确阶段完成、目标完成后的额外修改是否创建新版本/重新打开审查。
|
||||
|
||||
**验收**:A01–A05;修改文件、增加交付文件或改变验收标准后,旧批准不可继续完成。
|
||||
|
||||
### WP5:派发结果、返工与恢复
|
||||
|
||||
**任务**
|
||||
1. 将“执行器没报错”和“业务变更成功”分开。优先使用结构化原生结果;如需底座补丁,记录在 PATCHES 并保持非治理调用兼容。
|
||||
2. 不用英文错误字符串前缀作为主要业务判断。
|
||||
3. 持久化意图先于发送;记录 requestId 与原生 exchange/work 等关联,不丢失恢复依据。
|
||||
4. 结果状态建议:prepared、in_flight、confirmed、rejected、unknown、cancelled;具体名称可调整,但 unknown 不能自动变成功。
|
||||
5. 崩溃窗口逐段测试:记录前、记录后发送前、发送后回执前、回执到达后持久化前。
|
||||
6. 核实自动返工与原生提示是否会触发两次执行;统一一个派发责任方。
|
||||
7. 总返工预算按当前项目/目标可靠累计,不能因裁剪历史、重启或重复回执重置/多算。
|
||||
8. 取消需调用真实执行取消能力并核实状态;停止请求与已停止分别展示。尚无底座能力时明确限制。
|
||||
9. reconcile 提供可核查依据,保留人工结论来源;不得通过按钮直接把未知操作伪装成执行成功。
|
||||
10. 存储事务失败不能只留内存成功状态;按现有存储实现选择回滚/原子写/恢复机制。
|
||||
|
||||
**验收**:R01–R07;测试投递次数、原生状态和派发记录三者一致。
|
||||
|
||||
### WP6:状态投影和完整操作体验
|
||||
|
||||
**任务**
|
||||
1. 当前状态按 project/goal/stage/成果版本筛选,历史审查放入折叠历史区。
|
||||
2. 最新 reject 后有有效 pass 时,当前卡片不再显示历史返工。
|
||||
3. 最小状态集:未初始化、待配置、待执行、执行中、待审查、返工中、待核实、失败、暂停、已完成;具体组合避免相互矛盾。
|
||||
4. 只在需要人类动作时突出提示,显示原因和下一步操作。
|
||||
5. 前端切换项目时避免异步旧响应覆盖新项目;模型表单保存也校验项目身份。
|
||||
6. 轮询/事件订阅展示加载、断连和数据过期状态;不能把旧缓存显示为刚更新的成功状态。
|
||||
7. 分清暂停目标与取消当前执行的语义。按钮提交期间防重复,不靠禁用按钮替代服务端幂等。
|
||||
8. 验证角色打开、派工、审查、返工、暂停和恢复的必要操作均可达;不把所有动作隐藏在工具名称说明里。
|
||||
|
||||
**验收**:U06–U09、端到端 E01–E03。
|
||||
|
||||
### WP7:集成验收与发布
|
||||
|
||||
**任务**
|
||||
1. 运行全部现有测试及新增缺陷回归,再执行真实宿主端到端场景。
|
||||
2. 同时检查原生聊天、其他非治理会话、右栏插件和项目树没有被回归破坏。
|
||||
3. 记录兼容宿主/插件版本、构建命令、测试结果、实际截图和已知限制。
|
||||
4. 更新 README、升级说明与 PATCHES;删除或修正文档中不再成立的完成声明。
|
||||
5. 在云端提交、PR、审查、合并和发布可安装产物,提供明确版本与更新步骤。
|
||||
6. 不自动升级用户日常桌面。若需要测试真实宿主,使用已授权的测试环境;没有环境时报告缺失验收,不伪造截图或通过结果。
|
||||
|
||||
**退出条件**:第 9 节发布门全部满足;否则只能标为候选版本。
|
||||
|
||||
## 5. 现有文件定位
|
||||
|
||||
以下是 `3f20f89` 基线的起点,行号会变化,修改前先读真实实现。建议新模块名不是现有 API。
|
||||
|
||||
| 路径 | 核查或修改重点 |
|
||||
|---|---|
|
||||
| `sansheng/index.js` | 加载失败处理、服务安装顺序、是否存在治理失效放行 |
|
||||
| `sansheng/src/identity.js` | 当前群/会话/项目身份,unknown 不应默认获得用户权限 |
|
||||
| `sansheng/src/dsbot-state.js` | 群解析一致性、状态读取新鲜度和损坏处理 |
|
||||
| `sansheng/src/gates.js` | 解析失败放行、角色/项目边界 |
|
||||
| `sansheng/src/gate.js` | 最新审查规则、阶段/目标门禁、返工预算 |
|
||||
| `sansheng/src/tools.js` | provision 名称、bind 唯一性、review 项目选择、reconcile 来源 |
|
||||
| `sansheng/src/digest.js` | 账本摘要与成果快照分离 |
|
||||
| `sansheng/src/store.js` | 事务失败、唯一约束、schema/历史裁剪 |
|
||||
| `sansheng/src/observe.js` | 派发前后记录、真实业务成功、重复返工投递 |
|
||||
| `sansheng/src/records.js` | 错误识别与派发状态 |
|
||||
| `sansheng/src/api.js` | 当前对象过滤、历史与实时状态分离 |
|
||||
| `sansheng/client.js` | 新方案入口、角色打开、项目切换、配置和错误可见性 |
|
||||
| `sansheng/test/` | 加入以下回归;检查 fake 是否与真实宿主契约一致 |
|
||||
| `ds-bot/src/host/tools.js` | 原生 pickRoom、message_bot、跨项目投递可达路径 |
|
||||
| `ds-bot/src/host/goals.js` | 权限、原生目标变更、业务拒绝返回、版本并发检查 |
|
||||
| `ds-bot/src/host/memory.js` | team/项目域读写与注入 |
|
||||
| `ds-bot/src/host/delivery.js` | 原生投递标识、工作关联与恢复语义 |
|
||||
| `ds-bot/src/host/roster.js` | 全局名称唯一和创建清理 |
|
||||
| `ds-bot/PATCHES.md` | 所有底座改动的理由、上游基线和回归范围 |
|
||||
|
||||
可考虑新增 `project-context`、`artifact-snapshot`、`entry-adapter` 等职责清晰的小模块;先查已有能力,不为命名而分层。
|
||||
|
||||
旧桌面包的 `workbench/panel/lib/client.js` 只作为 F09–F11 的证据与迁移参考,不应成为正式修复的唯一落点。
|
||||
|
||||
## 6. 验收用例矩阵
|
||||
|
||||
每项记录:前置条件、具体输入、观察结果、期望结果、证据文件。默认用独立测试项目,避免操作用户真实任务。
|
||||
|
||||
### 6.1 入口与布局
|
||||
|
||||
| ID | 场景 | 必须满足 |
|
||||
|---|---|---|
|
||||
| U01 | 普通会话、长消息、连续工具流 | 输入框保持原生底部定位,无重叠和异常跳动 |
|
||||
| U02 | 从项目树打开 A | 打开 A 工作台;无绑定则进入 A 初始化,不落到默认 B |
|
||||
| U03 | 右栏关闭后重新打开、连续点击入口 | 可发现且可达,聚焦已有页签,不叠加重复页签 |
|
||||
| U04 | Better Sidebar 缺失/晚到/注册失败/卸载 | 原生入口可用或显示明确错误,不虚报成功 |
|
||||
| U05 | 小窗口、宽屏、明暗主题、拖动右栏 | 内容可读,布局不挤坏输入框;提交实际截图 |
|
||||
| U06 | A/B 快速切换并延迟 A 的接口响应 | A 响应不能覆盖 B 卡片/配置 |
|
||||
| U07 | 新目标开始,旧目标曾通过 | 新目标不显示已验收 |
|
||||
| U08 | 阶段先 reject 后 pass,再推进阶段 | 不长期显示旧返工原因 |
|
||||
| U09 | 接口断开、状态过期、模型配置失败 | 有可见反馈和恢复入口,不默默保留成功提示 |
|
||||
|
||||
### 6.2 隔离
|
||||
|
||||
| ID | 场景 | 必须满足 |
|
||||
|---|---|---|
|
||||
| I01 | 使用默认参数连续创建 A/B | 均成功,角色身份独立、名字唯一 |
|
||||
| I02 | 将 A 尚书绑定 B | 明确拒绝,不产生半绑定 |
|
||||
| I03 | B 会话显式传 A;私聊指定非所属项目 | 拒绝并记录可理解原因 |
|
||||
| I04 | 修改 A 模型配置 | B 配置及正在运行的会话不变 |
|
||||
| I05 | A 写项目记忆后启动/刷新 B 上下文 | B 不获得 A 标记内容 |
|
||||
| I06 | A 群/私聊/后台自动投递试图发送给 B | 服务端拒绝,不能绕过前端或经内部 deliver 通过 |
|
||||
| I07 | 两项目并行写入及越出允许工作根 | 允许范围内互不覆盖;越界受有效限制,不能只靠 prompt |
|
||||
|
||||
### 6.3 门禁和成果
|
||||
|
||||
| ID | 场景 | 必须满足 |
|
||||
|---|---|---|
|
||||
| G01 | 阶段均通过但无丞相验收,普通/带引号群名 complete | 都拒绝 |
|
||||
| G02 | 非项目 Main Bot 修改受治理群 | 按项目策略拒绝,不因 Main 豁免 |
|
||||
| G03 | 同一对象 pass→reject→complete/pass-stage | 最新 reject 生效 |
|
||||
| G04 | reject→pass;S1 pass→S2 reject→恢复 S1→complete | 前者仅在最新审批匹配当前提交代次时放行;后者拒绝,旧摘要不能复活旧批准 |
|
||||
| G05 | B 的证据、goal/stage 同名不同 ID | 无法批准 A |
|
||||
| G06 | 检查后、变更前并发改判/改成果 | 最终变更重新校验并拒绝过期决定 |
|
||||
| G07 | 治理状态文件损坏/加载失败/过期身份 | 受治理写操作停止并提示恢复,不静默放行 |
|
||||
| A01 | 通过后改已跟踪文件 | 旧批准失效 |
|
||||
| A02 | 通过后新增交付范围内未跟踪文件 | 旧批准失效 |
|
||||
| A03 | 通过后改变验收标准或任务范围 | 旧批准失效 |
|
||||
| A04 | 测试执行后又改成果 | 不声称最终成果已测试 |
|
||||
| A05 | 仅通过状态变更引起账本 revision 增长 | 按已定义版本语义正常推进,无审批死锁 |
|
||||
|
||||
### 6.4 派发和恢复
|
||||
|
||||
| ID | 场景 | 必须满足 |
|
||||
|---|---|---|
|
||||
| R01 | 原生工具返回业务拒绝字符串/结构化拒绝 | 不记 confirmed,不触发后续执行 |
|
||||
| R02 | 同 requestId 同 payload 重复调用 | 不重复投递;冲突 payload 拒绝 |
|
||||
| R03 | 发送成功回执丢失后重启 | 保留 unknown/可核实状态,不盲目重发 |
|
||||
| R04 | intent 保存失败/结果保存失败 | 不虚报成功,内存与持久化可恢复一致 |
|
||||
| R05 | 一次返工与原生 @ 提示同时存在 | 只启动一次有效返工,预算只扣一次 |
|
||||
| R06 | 达返工上限、清理历史、重启 | 上限仍有效,历史裁剪不能重置额度 |
|
||||
| R07 | 暂停/取消后恢复、执行中刷新 | 原生执行和 UI 状态一致,保留必要审查/成果记录 |
|
||||
|
||||
### 6.5 真实模型端到端
|
||||
|
||||
- E01 正常交付:从项目树初始化项目,给一个可检验的小代码任务,真实派发、修改文件、运行测试、阶段审核、最终验收;保存成果及执行证据。
|
||||
- E02 驳回返工:故意设置一个未满足的验收项;必须拒绝完成,返工后生成新成果与新审批,再完成。不能预填 fake review 代替。
|
||||
- E03 双项目并行:A/B 含可区分的文件与记忆标记,分别执行;A 返工/暂停时 B 继续,最终成果与证据不混用。
|
||||
- E04 中断恢复:在受控环境执行中断,重启后核实派发与工作状态,不重复执行已接受请求。
|
||||
|
||||
## 7. 测试与验证实施原则
|
||||
|
||||
1. 先保留并运行原有测试,再针对已确认缺陷写能失败的回归用例,修复后变绿。
|
||||
2. 单元层验证权限、摘要、审查排序、状态投影;集成层使用真实原生 resolver/result 契约,避免 fake 把字符串业务错误改成 isError 掩盖问题。
|
||||
3. 持久化与恢复测试用隔离临时目录,覆盖故障窗口和并发,不碰用户真实状态。
|
||||
4. UI 静态检查只证明语法和注册逻辑;真实页面才证明入口可见、定位正确、交互可达。
|
||||
5. 使用已授权的浏览器控制和测试宿主。没有控制通道时标记“未验证”,不读取用户浏览器凭据、不新开替代服务假装修复原页面。
|
||||
6. 不通过加任意 CSS、复制宿主组件或硬编码私有选择器绕过布局契约。
|
||||
7. 不为低风险样式改动写镜像实现测试;重点测试权限、隔离、并发、回执与实际用户路径。
|
||||
|
||||
基线测试命令(从仓库根运行,使用支持的 Node):
|
||||
|
||||
```sh
|
||||
node --test --test-isolation=none sansheng/test/*.test.js
|
||||
node --check sansheng/client.js
|
||||
node --check sansheng/index.js
|
||||
```
|
||||
|
||||
新增测试和构建命令按真实 package scripts 更新,不假设已经存在。
|
||||
|
||||
## 8. 分工与合并方式
|
||||
|
||||
建议由一个集成负责人加最多三个实施分工推进,不要求同时开大量 agent。
|
||||
|
||||
- 集成负责人:WP0、共享数据契约、核心文件协调、最终 diff/测试、WP7。
|
||||
- 入口/UI:WP1、WP6;主改 `sansheng/client.js` 和新入口适配模块。
|
||||
- 治理/隔离:WP2、WP3;主改 identity/gates/gate/tools 与必要底座边界。
|
||||
- 成果/恢复:WP4、WP5;主改 digest/observe/records/store 与必要原生结果契约。
|
||||
|
||||
`tools.js`、`store.js`、原生 `goals.js` 容易冲突:开工前指定唯一修改者,其余人提供接口需求或独立测试。不要并行自动格式化整个仓库。
|
||||
|
||||
每个工作包提交包含:问题与触发条件、实现、回归用例、验证结果、剩余限制。共享契约变更先合并再扩展调用者。使用 Git 分支/提交管理,不创建 backup 目录或多个“最终版”。
|
||||
|
||||
## 9. 里程碑与发布门
|
||||
|
||||
| 里程碑 | 完成范围 | 可宣称内容 | 不可宣称内容 |
|
||||
|---|---|---|---|
|
||||
| M0 | WP0 | 版本/接口/发布路径已明确 | 工作台已可用 |
|
||||
| M1 | WP1 | 入口与原生布局已验证 | 审批和隔离已可靠 |
|
||||
| M2 | WP2–WP4 | 项目身份、隔离、审批与成果约束通过回归 | 中断恢复和完整自治已验收 |
|
||||
| M3 | WP5–WP6 | 可操作完整闭环,失败与恢复有证据 | 未做真实测试时称可发布 |
|
||||
| M4 | WP7 | 指定兼容环境下可发布 | 超出验证版本的全兼容 |
|
||||
|
||||
发布门:
|
||||
- P1 缺陷全部关闭且有可复现回归。
|
||||
- F06–F08、F11 等影响用户可用性的问题修复或明确阻止受影响功能;不能静默带病发布。
|
||||
- U/I/G/A/R 必选项全部通过;不适用项需说明原因。
|
||||
- E01–E04 有真实运行证据;缺少环境时保持候选状态。
|
||||
- 两包依赖/宿主兼容关系明确;旧新同时启用风险有处理。
|
||||
- 数据保留、升级和回退说明齐全;更新不会无提示迁移/删除旧项目。
|
||||
- 真实页面截图与 UI/UX 复核完成,用户不依赖控制台和工具名才能进入工作台。
|
||||
|
||||
## 10. 开工必须解决的决策点
|
||||
|
||||
这些问题优先通过代码与只读环境调查解决,不把能查的事项全部抛给用户。
|
||||
|
||||
1. **项目树扩展契约**:当前安装的项目树插件叫什么、支持哪种项目动作、是否允许打开右栏?缺少公开 API 时再提出最小扩展方案。
|
||||
2. **项目 ID 映射**:现有树中的项目是否等同 workspace?若不是,显式建立映射,不靠名称猜测。
|
||||
3. **文件隔离**:两个项目是否会使用同一仓库目录?如会,确定隔离工作树/写锁和成果合并流程,再宣称支持并行。
|
||||
4. **记忆边界**:项目域记忆是否可复用原生 group scope?若不足,补底座支持;不要仅隐藏 team 按钮。
|
||||
5. **原生版本提交点**:在哪里能原子校验预期 goal/审批/成果并执行状态变更?无法闭合时应补原生接口,而不是只加强前置 guard。
|
||||
6. **取消与恢复能力**:核对原生真实支持的操作,区分可取消、只可停止等待和结果未知。
|
||||
7. **旧数据处理**:默认不迁移;如用户确需旧十席项目迁移,另拟映射与预览,批准后执行。
|
||||
8. **发布目标**:确认远端仓库、分支、CI、两个包的发布方式。不要根据历史 URL 擅自推送。
|
||||
|
||||
## 11. 交付清单
|
||||
|
||||
最终实施交付应包含:
|
||||
|
||||
- 代码变更及可审阅提交/PR,必要底座改动写入 PATCHES。
|
||||
- 版本与安装兼容清单,明确旧包退出与新包启用顺序。
|
||||
- 功能状态表:已验证/未验证/限制,不以“基本完成”掩盖缺口。
|
||||
- 缺陷关闭证据与完整测试结果。
|
||||
- 入口、角色、配置、审核、返工、断连、恢复的实际页面截图。
|
||||
- E01–E04 操作记录、成果摘要和测试证据;脱敏且不含令牌。
|
||||
- 升级/回退说明,保留用户数据的明确策略。
|
||||
- 用户操作说明:如何从项目树进入、切换角色、审查成果与处理失败。
|
||||
|
||||
建议把验证结果放在单一 `docs/verification/` 目录,按测试 ID 命名;这属于测试证据,不是代码备份目录。只保存必要证据,不复制整份用户数据。
|
||||
|
||||
## 12. 授权与实施边界
|
||||
|
||||
- 用户当前请求是编写交接方案;本次不修改业务代码、不提交/推送、不安装更新。
|
||||
- 后续实施以用户给执行 agent 的具体授权为准。此前“先修布局”的本地授权只覆盖已做的旧包止血,不自动扩展到新方案全量生产部署。
|
||||
- 按用户长期要求,正式插件修复应先走云端提交、PR、合并和发布,再由用户更新本地。未另获授权不得改日常 desktop profile、node_modules 或代装升级。
|
||||
- 不通过插件面板试开关/卸载来诊断,避免其重写 profile 的已知风险;不运行会重写中文 link 依赖的安装操作。
|
||||
- 不删除旧项目、群、会话、记忆或工作目录。不迁移用户数据,除非有明确范围及确认。
|
||||
- 不重启用户正在工作的应用,不另起服务器冒充当前 GUI。
|
||||
- 发现与本文基线不一致时,记录差异并调整计划;不要覆盖其他 agent 的新改动。
|
||||
|
||||
## 13. 可复制给执行 agent 的启动提示
|
||||
|
||||
```text
|
||||
请实施《docs/三省六部工作台-实施与验收交接方案.md》。
|
||||
先完成 WP0,核对当前分支、提交、实际接口和已安装版本,随后按依赖推进。
|
||||
目标是三角色最小完整闭环:现有项目树入口 + 原生聊天 + 项目右栏,
|
||||
以及真实项目隔离、审批/成果版本、派发恢复与端到端验收。
|
||||
不要恢复十席主聊天接管,不另造项目树,不把注册成功或 HTTP 200 当作完成。
|
||||
先在仓库实施并提供可审阅变更,按已有授权办理远端 PR/发布;
|
||||
未获单独授权不得修改日常 desktop profile、安装目录或迁移用户数据。
|
||||
每个里程碑报告实际通过的验收项、证据及未验证限制;
|
||||
若缺真实宿主环境,交付候选版本并明确缺口,不宣称已完成视觉和端到端验收。
|
||||
```
|
||||
|
|
@ -67,12 +67,120 @@ const rt = ctx.get('dsbot-runtime', false) // 未安装打过补丁的 ds-bot
|
|||
表现就是"插件全没了 / 启动崩溃"。`sidebar.settings` 那处上游本来就有 try/catch,不必改。
|
||||
改的是构建产物,重新构建上游后需重放本补丁。
|
||||
|
||||
## M-04:项目投递边界(Bot 间消息)
|
||||
|
||||
三个文件各有一个本地 helper(不新增共享模块):
|
||||
|
||||
```diff
|
||||
+const sanshengGovernance = () => {
|
||||
+ try { return ctx.get?.('sansheng-governance', false) } catch { return undefined }
|
||||
+}
|
||||
```
|
||||
|
||||
`delivery.js` 的 `deliver()`:解析出目标 Bot 之后、任何 `ensureCapabilities`/`followup` 之前:
|
||||
|
||||
```diff
|
||||
const to = rt.botOf(toId)
|
||||
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
|
||||
+ const verdict = sanshengGovernance()?.checkDelivery?.({ fromId, toId, roomId })
|
||||
+ if (verdict && verdict.allow === false) {
|
||||
+ throw Object.assign(new Error(verdict.reason ?? '跨项目投递被拒绝'), { code: 'sansheng/forbidden' })
|
||||
+ }
|
||||
```
|
||||
|
||||
`tools.js` 的 `message_bot`:私聊路径(`room === undefined`,即 `send()` 所走的分支)在真正投递前做同样的检查;群内路径已有 `groupRefusal`,不重复:
|
||||
|
||||
```diff
|
||||
+ const verdict = sanshengGovernance()?.checkDelivery?.({ fromId: sender.id, toId: target.id, roomId: undefined })
|
||||
+ if (verdict && verdict.allow === false) return verdict.reason ?? '跨项目投递被拒绝'
|
||||
return request === undefined ? await send() : answer(await rt.admitRequest(request, send))
|
||||
```
|
||||
|
||||
原因:DS Bot 的 `deliver` 是 Bot 间投递的最终入口,`message_bot` 只是其中一条上层路径;
|
||||
只挡工具调用会留下内部调用(例如派发恢复、自动投递)的绕过口。治理服务按项目判断
|
||||
`fromId`/`toId` 是否同属一个项目,跨项目时返回 `{ allow: false, reason }`,底座在
|
||||
任何 Session 写入前以 `sansheng/forbidden` 拒绝。
|
||||
|
||||
影响面:只在 `ctx.get('sansheng-governance', false)` 返回治理服务时生效;`fromId` 为
|
||||
用户或为空时由治理实现决定 allow。无治理服务时 optional chaining 返回 `undefined`,
|
||||
投递路径、异常类型、return 值与上游完全一致。群内 `@Name` 的 `callInGroup` 由
|
||||
`groupRefusal` 先行限制,本补丁不重复加检查。
|
||||
|
||||
## M-05:项目记忆域(team 作用域隔离)
|
||||
|
||||
`memory.js` 内新增同一 helper,并在写入、读取、提示注入与自动召回等处加治理判断:
|
||||
|
||||
```diff
|
||||
function writeDenied(scope, botId) {
|
||||
+ if (botId && botId !== 'user') {
|
||||
+ const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: scope.kind, roomId: scope.kind === 'group' ? scope.roomId : undefined })
|
||||
+ if (verdict && verdict.allow === false) return verdict.reason ?? '项目记忆边界拒绝此操作。'
|
||||
+ }
|
||||
if (scope.kind === 'team') return writesTeam(botId) ? undefined : '...'
|
||||
```
|
||||
|
||||
```diff
|
||||
function readScopes(raw, botId, sessionRoomId) {
|
||||
...
|
||||
+ if (scope && scope.kind === 'bot' && scope.botId !== botId && botId && botId !== 'user') {
|
||||
const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'bot', targetBotId: scope.botId })
|
||||
if (verdict && verdict.allow === false) return { error: verdict.reason ?? '...' }
|
||||
}
|
||||
let scopes = scope === undefined ? (...) : [scope]
|
||||
+ if (botId && botId !== 'user' && scopes.some(item => item.kind === 'team')) {
|
||||
+ const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'team' })
|
||||
+ if (verdict && verdict.allow === false) {
|
||||
+ scopes = scopes.filter(item => item.kind !== 'team')
|
||||
+ if (scopes.length === 0) return { error: '项目 Bot 不能读取跨项目共享记忆。' }
|
||||
+ }
|
||||
+ }
|
||||
```
|
||||
|
||||
```diff
|
||||
function memorySection(bot) {
|
||||
...
|
||||
+ const teamAllowed = !bot.id || bot.id === 'user'
|
||||
+ ? true
|
||||
+ : sanshengGovernance()?.checkMemoryScope?.({ botId: bot.id, scope: 'team' })?.allow !== false
|
||||
const team = teamAllowed ? sectionRead(join(dirOf(TEAM), MAIN)) : { text: '' }
|
||||
...
|
||||
- teamRule(rt.isMain(bot.id), writesTeam(bot.id), rt.isPrivate(bot.id)),
|
||||
+ ...(teamAllowed ? [teamRule(...)] : []),
|
||||
...
|
||||
+ ...(teamAllowed ? ['', '## Team memory, ...', ...] : []),
|
||||
```
|
||||
|
||||
`sectionFor` 的 `marks`/`holds` 同步跳过 team rule,避免已冻结的旧快照继续带出 team 段。
|
||||
|
||||
```diff
|
||||
function autoRecall(agent, bot, roomId, decision) {
|
||||
- const scopes = [own, ...(roomId === undefined ? [] : [groupScope(roomId)]), TEAM]
|
||||
+ const scopes = [own, ...(roomId === undefined ? [] : [groupScope(roomId)]), ...(teamAllowedFor(bot.id) ? [TEAM] : [])]
|
||||
```
|
||||
```diff
|
||||
function memoryUpdate(sessionId, bot, roomId) {
|
||||
- const keys = new Set([scopeKey(own), scopeKey(TEAM), ...])
|
||||
+ const keys = new Set([scopeKey(own), ...(teamAllowedFor(bot.id) ? [scopeKey(TEAM)] : []), ...])
|
||||
```
|
||||
|
||||
原因:`team` 作用域是 DS Bot 所有 Bot 共享的记忆,正好是跨项目泄漏点(00-baseline
|
||||
§3.4)。项目 Bot 不能读写 team 记忆;`own`/`group` 不受影响。治理只在 `botId` 为
|
||||
真实 Bot 时检查,`actor.id === 'user'` 的用户操作保持上游权限。
|
||||
|
||||
影响面:`remember`/`forget` 的 team 写入、`recall` 的 team 读取、系统提示的 team
|
||||
段与 `teamRule` 行、自动召回(autoRecall)与记忆变更提示(memoryUpdate)的 team
|
||||
键;不改变 own/group 记忆、不改变文件格式。无治理服务时 `teamAllowedFor` 为 true、
|
||||
`readScopes` 原样返回,行为与上游一致。
|
||||
|
||||
## 升级步骤
|
||||
|
||||
1. 取新版本 npm tarball,解压覆盖本目录(保留本文件与 `NOTICE`)。
|
||||
2. 重放 M-01;若上游已自行暴露运行时(例如 `ctx.set('dsbot', rt)`),删除本补丁
|
||||
并同步修改 `sansheng/src/runtime.js` 的取用名。
|
||||
3. 跑 `sansheng` 的单元测试与安装冒烟(见 `docs/install.md`)。
|
||||
3. 逐一重放其余补丁:M-02 检查 `cordis.patch.yml`,M-03 重放 `client.js` 的
|
||||
`settings.trigger` try/catch,M-04/M-05 按本文件 diff 恢复 `delivery.js`、
|
||||
`memory.js`、`tools.js` 的治理检查(并对三个文件跑 `node --check`)。
|
||||
4. 跑 `sansheng` 的单元测试与安装冒烟(见 `docs/install.md`)。
|
||||
|
||||
## 回退
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "ds-bot",
|
||||
"version": "0.3.2",
|
||||
"version": "0.3.2-sansheng.1",
|
||||
"description": "DS Bot: a team of long-lived Bots for DeepSeek Harness, with Main Bots, Bot-to-Bot messages and group chats",
|
||||
"keywords": [
|
||||
"dsh-plugin",
|
||||
|
|
|
|||
|
|
@ -7,6 +7,11 @@ import { headOf, textOf } from './text.js'
|
|||
export function install(rt) {
|
||||
const { ctx, state } = rt
|
||||
|
||||
// sansheng M-04: the project delivery boundary, when a governance service is installed.
|
||||
const sanshengGovernance = () => {
|
||||
try { return ctx.get?.('sansheng-governance', false) } catch { return undefined }
|
||||
}
|
||||
|
||||
const resolveAgent = async (sessionId) => {
|
||||
const resolved = await ctx.sessionController.resolveAgent(sessionId)
|
||||
if ('error' in resolved) throw Object.assign(new Error(resolved.error?.message ?? 'Session unavailable'), { code: resolved.error?.code })
|
||||
|
|
@ -61,6 +66,12 @@ export function install(rt) {
|
|||
const from = rt.botOf(fromId)
|
||||
const to = rt.botOf(toId)
|
||||
if (to === undefined) throw new Error(`Unknown Bot ${toId}`)
|
||||
// sansheng M-04: a project Bot may reach only Bots of its own project. Checked before
|
||||
// any Session work; without the service the upstream delivery is unchanged.
|
||||
const verdict = sanshengGovernance()?.checkDelivery?.({ fromId, toId, roomId })
|
||||
if (verdict && verdict.allow === false) {
|
||||
throw Object.assign(new Error(verdict.reason ?? '跨项目投递被拒绝'), { code: 'sansheng/forbidden' })
|
||||
}
|
||||
const fromName = senderName ?? from?.name ?? 'You'
|
||||
const room = rt.roomOf(roomId)
|
||||
const asker = work === undefined ? undefined : rt.botOf(state.works?.[work]?.from)?.name
|
||||
|
|
|
|||
|
|
@ -80,6 +80,15 @@ const NEWS_TEXT_MAX = 160
|
|||
export function install(rt) {
|
||||
const { ctx, config, home, state } = rt
|
||||
|
||||
// sansheng M-05: the project memory boundary, when a governance service is installed.
|
||||
const sanshengGovernance = () => {
|
||||
try { return ctx.get?.('sansheng-governance', false) } catch { return undefined }
|
||||
}
|
||||
const teamAllowedFor = (botId) => {
|
||||
if (!botId || botId === 'user') return true
|
||||
return sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'team' })?.allow !== false
|
||||
}
|
||||
|
||||
if (config.memory === false) {
|
||||
Object.assign(rt, {
|
||||
memoryEnabled: false,
|
||||
|
|
@ -404,6 +413,12 @@ export function install(rt) {
|
|||
return { scope: ownScope(bot.id) }
|
||||
}
|
||||
function writeDenied(scope, botId) {
|
||||
// sansheng M-05: a project Bot may not write the team memory, which is shared across
|
||||
// projects. The user (and ids that are not a Bot) keep the upstream rights.
|
||||
if (botId && botId !== 'user') {
|
||||
const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: scope.kind, roomId: scope.kind === 'group' ? scope.roomId : undefined })
|
||||
if (verdict && verdict.allow === false) return verdict.reason ?? '项目记忆边界拒绝此操作。'
|
||||
}
|
||||
if (scope.kind === 'team') return writesTeam(botId) ? undefined : 'Only Main Bots and group admins write the team memory. Tell a Main Bot with message_bot what the team should know.'
|
||||
if (scope.kind === 'group') return rt.roomOf(scope.roomId)?.members.includes(botId) ? undefined : 'Only the members of a group chat write its memory.'
|
||||
if (scope.botId !== botId && !rt.isMain(botId)) return 'Only a Main Bot can change another Bot\'s memory. Use message_bot to tell that Bot instead.'
|
||||
|
|
@ -722,21 +737,27 @@ export function install(rt) {
|
|||
function memorySection(bot) {
|
||||
const own = ownScope(bot.id)
|
||||
const main = sectionRead(join(dirOf(own), MAIN))
|
||||
const team = sectionRead(join(dirOf(TEAM), MAIN))
|
||||
// sansheng M-05: a project Bot gets no team section; every other part is unchanged.
|
||||
const teamAllowed = !bot.id || bot.id === 'user'
|
||||
? true
|
||||
: sanshengGovernance()?.checkMemoryScope?.({ botId: bot.id, scope: 'team' })?.allow !== false
|
||||
const team = teamAllowed ? sectionRead(join(dirOf(TEAM), MAIN)) : { text: '' }
|
||||
const ownTopics = sectionTopics(own)
|
||||
const teamTopics = sectionTopics(TEAM)
|
||||
const teamTopics = teamAllowed ? sectionTopics(TEAM) : { lines: [] }
|
||||
const lines = [
|
||||
'# Your memory',
|
||||
memoryRules(reviewOn),
|
||||
teamRule(rt.isMain(bot.id), writesTeam(bot.id), rt.isPrivate(bot.id)),
|
||||
...(teamAllowed ? [teamRule(rt.isMain(bot.id), writesTeam(bot.id), rt.isPrivate(bot.id))] : []),
|
||||
'',
|
||||
'## Your memory (MEMORY.md)',
|
||||
...sectionEntries(main, ownTopics.lines, bot),
|
||||
'',
|
||||
'## Team memory, shared by every Bot (team/MEMORY.md)',
|
||||
...sectionEntries(team, teamTopics.lines, bot),
|
||||
...(teamAllowed ? [
|
||||
'',
|
||||
'## Team memory, shared by every Bot (team/MEMORY.md)',
|
||||
...sectionEntries(team, teamTopics.lines, bot),
|
||||
] : []),
|
||||
]
|
||||
return { text: lines.join('\n'), failed: main.failed !== undefined || team.failed !== undefined || ownTopics.failed === true || teamTopics.failed === true }
|
||||
return { text: lines.join('\n'), failed: main.failed !== undefined || ownTopics.failed === true || (teamAllowed && (team.failed !== undefined || teamTopics.failed === true)) }
|
||||
}
|
||||
function groupSection(roomId, bot) {
|
||||
const group = groupScope(roomId)
|
||||
|
|
@ -796,8 +817,12 @@ export function install(rt) {
|
|||
// A group Session's section is the Bot's own; its group's memory comes as a message
|
||||
// (see the agent/pre-step below), so both share the provider's cached prefix, tools
|
||||
// included: the provider puts the tools after the whole system prompt.
|
||||
const marks = [teamRule(rt.isMain(bot.id), writesTeam(bot.id), rt.isPrivate(bot.id))]
|
||||
const holds = text => marks.every(mark => text.includes(mark))
|
||||
// sansheng M-05: a project Bot has no team section, so no team rule either.
|
||||
const teamAllowed = !bot.id || bot.id === 'user'
|
||||
? true
|
||||
: sanshengGovernance()?.checkMemoryScope?.({ botId: bot.id, scope: 'team' })?.allow !== false
|
||||
const marks = teamAllowed ? [teamRule(rt.isMain(bot.id), writesTeam(bot.id), rt.isPrivate(bot.id))] : []
|
||||
const holds = text => marks.every(mark => text.includes(mark)) && (teamAllowed || !text.includes('## Team memory'))
|
||||
const kept = frozen.get(sessionId)
|
||||
if (kept !== undefined && holds(kept)) return kept
|
||||
const pending = pendingChange()
|
||||
|
|
@ -885,7 +910,7 @@ export function install(rt) {
|
|||
try { history = agent.session?.deriveMessages?.() ?? [] } catch { /* nothing to look in */ }
|
||||
const shown = new Set(history.filter(isRecalled).flatMap(message => message.source.ids ?? []))
|
||||
const own = ownScope(bot.id)
|
||||
const scopes = [own, ...(roomId === undefined ? [] : [groupScope(roomId)]), TEAM]
|
||||
const scopes = [own, ...(roomId === undefined ? [] : [groupScope(roomId)]), ...(teamAllowedFor(bot.id) ? [TEAM] : [])]
|
||||
let topicEntries
|
||||
try {
|
||||
topicEntries = scopes.flatMap(scope => allEntries(loadScope(scope).slice(1)).map(entry => ({ ...entry, tag: tagOf(scope, bot.id) })))
|
||||
|
|
@ -934,7 +959,7 @@ export function install(rt) {
|
|||
return undefined
|
||||
}
|
||||
const own = ownScope(bot.id)
|
||||
const keys = new Set([scopeKey(own), scopeKey(TEAM), ...(roomId === undefined ? [] : [scopeKey(groupScope(roomId))])])
|
||||
const keys = new Set([scopeKey(own), ...(teamAllowedFor(bot.id) ? [scopeKey(TEAM)] : []), ...(roomId === undefined ? [] : [scopeKey(groupScope(roomId))])])
|
||||
try {
|
||||
for (const path of new Set([journalPath, journalFor(scopeKey(own), 'read').path])) readTail(path)
|
||||
} catch (error) {
|
||||
|
|
@ -1125,16 +1150,27 @@ export function install(rt) {
|
|||
}))
|
||||
|
||||
// The scopes a caller reads: by default its own, its group's when it speaks in one,
|
||||
// and the team's.
|
||||
// and the team's. A project Bot does not read the team memory, which every project shares.
|
||||
function readScopes(raw, botId, sessionRoomId) {
|
||||
const roomId = rt.roomOf(sessionRoomId)?.members.includes(botId) ? sessionRoomId : undefined
|
||||
const { scope, error } = namedScope(raw, botId, roomId)
|
||||
if (error) return { error }
|
||||
if (scope === undefined) return { scopes: roomId === undefined ? [ownScope(botId), TEAM] : [ownScope(botId), groupScope(roomId), TEAM] }
|
||||
if (scope.kind === 'bot' && scope.botId !== botId) {
|
||||
if (scope && scope.kind === 'bot' && scope.botId !== botId && botId && botId !== 'user') {
|
||||
const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'bot', targetBotId: scope.botId })
|
||||
if (verdict && verdict.allow === false) return { error: verdict.reason ?? '项目记忆边界拒绝读取其他项目成员记忆。' }
|
||||
}
|
||||
let scopes = scope === undefined ? (roomId === undefined ? [ownScope(botId), TEAM] : [ownScope(botId), groupScope(roomId), TEAM]) : [scope]
|
||||
if (botId && botId !== 'user' && scopes.some(item => item.kind === 'team')) {
|
||||
const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'team' })
|
||||
if (verdict && verdict.allow === false) {
|
||||
scopes = scopes.filter(item => item.kind !== 'team')
|
||||
if (scopes.length === 0) return { error: '项目 Bot 不能读取跨项目共享记忆。' }
|
||||
}
|
||||
}
|
||||
if (scope !== undefined && scope.kind === 'bot' && scope.botId !== botId) {
|
||||
if (rt.isPrivate(scope.botId)) return { error: 'That Bot is private. Ask the user to share what you need.' }
|
||||
}
|
||||
return { scopes: [scope] }
|
||||
return { scopes }
|
||||
}
|
||||
const tagOf = (scope, botId) => (scope.kind === 'team' ? 'team' : scope.kind === 'group' ? 'group' : scope.botId === botId ? 'yours' : rt.botOf(scope.botId)?.name ?? '?')
|
||||
|
||||
|
|
|
|||
|
|
@ -50,6 +50,11 @@ const WORKING_DIRECTORY_TOOL = 'working_directory'
|
|||
export function install(rt) {
|
||||
const { ctx, state } = rt
|
||||
|
||||
// sansheng M-04: the project delivery boundary, when a governance service is installed.
|
||||
const sanshengGovernance = () => {
|
||||
try { return ctx.get?.('sansheng-governance', false) } catch { return undefined }
|
||||
}
|
||||
|
||||
const callerBot = (exec) => rt.botOf(rt.selfOf(exec.agent?.id))
|
||||
const callerRoom = (exec) => {
|
||||
const roomId = rt.groupOwners.get(exec.agent?.id)?.roomId
|
||||
|
|
@ -290,6 +295,10 @@ export function install(rt) {
|
|||
const stop = rt.isMain(sender.id) ? ' If it must not go on there, use stop_bot.' : ''
|
||||
return `${out} Your message does not reach its work in ${groups.map(whereOf).join(' and ')}.${stop}`
|
||||
}
|
||||
// sansheng M-04: a Bot's own chat is still a project boundary. The group path above
|
||||
// already has groupRefusal; here the check runs before any delivery or request.
|
||||
const verdict = sanshengGovernance()?.checkDelivery?.({ fromId: sender.id, toId: target.id, roomId: undefined })
|
||||
if (verdict && verdict.allow === false) return verdict.reason ?? '跨项目投递被拒绝'
|
||||
return request === undefined ? await send() : answer(await rt.admitRequest(request, send))
|
||||
},
|
||||
}))
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,5 +1,6 @@
|
|||
import { DsBotState } from './src/dsbot-state.js'
|
||||
import { installGates } from './src/gates.js'
|
||||
import { installGovernance } from './src/governance.js'
|
||||
import { installObserver } from './src/observe.js'
|
||||
import { dsbotStatePath, sanshengStatePath } from './src/paths.js'
|
||||
import { newBootId } from './src/records.js'
|
||||
|
|
@ -10,10 +11,23 @@ import { installTools } from './src/tools.js'
|
|||
export const name = 'sansheng'
|
||||
export const inject = ['tools']
|
||||
|
||||
function botSessionProbe({ ctx, dsbot }) {
|
||||
return sessionId => {
|
||||
if (!sessionId) return false
|
||||
if (dsbot.isBotSession(sessionId)) return true
|
||||
try {
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
return rt?.isBotSession?.(sessionId) === true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 三省六部伴侣插件。原生 group_goal 是阶段进度唯一权威;
|
||||
* 这里只补 DS Bot 没有的东西:项目三角色绑定、审查记录、目标门禁、
|
||||
* 派发回执与返工预算。
|
||||
* 这里只补 DS Bot 没有的东西:项目三角色绑定、审查记录、成果快照、目标门禁、
|
||||
* 派发回执与返工预算,以及项目隔离的治理服务。
|
||||
*/
|
||||
export async function apply(ctx, config = {}) {
|
||||
const home = typeof config.home === 'string' && config.home.trim() !== '' ? config.home : undefined
|
||||
|
|
@ -26,7 +40,7 @@ export async function apply(ctx, config = {}) {
|
|||
const bootId = newBootId()
|
||||
try {
|
||||
await store.load()
|
||||
// 重启对账:上次启动里停在 intent 的派发,结果未知,标记待核实。
|
||||
// 重启对账:上次启动里停在 prepared/in_flight 的派发,结果未知,标记待核实。
|
||||
const pending = await store.reconcileDispatches(bootId)
|
||||
if (pending > 0) {
|
||||
console.warn(`sansheng: ${pending} 条派发在上次退出时未拿到回执,已标记待核实(用 sansheng_reconcile 核对)。`)
|
||||
|
|
@ -34,8 +48,10 @@ export async function apply(ctx, config = {}) {
|
|||
} catch (error) {
|
||||
console.warn(`sansheng: 无法读取 ${store.file}:${error?.message ?? error}`)
|
||||
}
|
||||
installGates({ ctx, store, dsbot })
|
||||
installObserver({ ctx, store, dsbot, bootId })
|
||||
installTools({ ctx, store, dsbot, bootId })
|
||||
const isBotSession = botSessionProbe({ ctx, dsbot })
|
||||
installGovernance({ ctx, store })
|
||||
installGates({ ctx, store, dsbot, isBotSession })
|
||||
installObserver({ ctx, store, dsbot, bootId, isBotSession })
|
||||
installTools({ ctx, store, dsbot, isBotSession })
|
||||
installRoute({ ctx, store, dsbot })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-sansheng-sansheng",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"description": "三省六部:在 DS Bot 团队上提供丞相/尚书/工部三角色、目标门禁与审查记录。",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -9,17 +9,27 @@ function clip(text, max = DETAIL_MAX) {
|
|||
return value.length <= max ? value : `${value.slice(0, max - 1)}…`
|
||||
}
|
||||
|
||||
function sortReviews(reviews) {
|
||||
return [...(reviews ?? [])].sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0))
|
||||
}
|
||||
|
||||
function latest(reviews) {
|
||||
return reviews.length > 0 ? reviews[0] : undefined
|
||||
const sorted = sortReviews(reviews)
|
||||
return sorted.length > 0 ? sorted[0] : undefined
|
||||
}
|
||||
|
||||
function taskCounts(stage, botId) {
|
||||
const tasks = (stage?.tasks ?? []).filter(task => task.botId === botId)
|
||||
const done = tasks.filter(task => task.status === 'done').length
|
||||
const active = tasks.filter(task => task.status === 'active' || task.status === 'doing').length
|
||||
const active = tasks.filter(task => task.status === 'active' || task.status === 'doing' || task.status === 'working').length
|
||||
return { total: tasks.length, done, active, open: tasks.length - done }
|
||||
}
|
||||
|
||||
function botChatSessionId(bot) {
|
||||
// DS Bot 的 Bot id 就是它的私聊 root Session id;部分状态版本另有 sessionId 字段。
|
||||
return bot?.sessionId ?? bot?.id ?? null
|
||||
}
|
||||
|
||||
function leadCard({ project, goal, bot, goalReviews }) {
|
||||
const review = latest(goalReviews)
|
||||
const card = {
|
||||
|
|
@ -30,9 +40,12 @@ function leadCard({ project, goal, bot, goalReviews }) {
|
|||
name: bot?.name ?? null,
|
||||
model: project.models?.lead ?? bot?.model ?? null,
|
||||
exists: Boolean(bot),
|
||||
sessionId: botChatSessionId(bot),
|
||||
clickable: Boolean(botChatSessionId(bot)),
|
||||
line: '等待交付',
|
||||
detail: '',
|
||||
tone: 'idle',
|
||||
next: '',
|
||||
}
|
||||
if (review) {
|
||||
card.line = review.verdict === 'pass'
|
||||
|
|
@ -45,6 +58,7 @@ function leadCard({ project, goal, bot, goalReviews }) {
|
|||
if (goal && (goal.stages ?? []).length > 0 && (goal.stages ?? []).every(stage => stage.status === 'passed')) {
|
||||
card.line = '等待验收'
|
||||
card.tone = 'attention'
|
||||
card.next = '打开丞相会话,核对整体交付后记录 goal_pass。'
|
||||
} else if (goal) {
|
||||
card.line = '目标进行中'
|
||||
}
|
||||
|
|
@ -52,7 +66,7 @@ function leadCard({ project, goal, bot, goalReviews }) {
|
|||
return card
|
||||
}
|
||||
|
||||
function shangshuCard({ project, goal, bot, budget, unknown, dispatches, botId }) {
|
||||
function shangshuCard({ project, goal, bot, budget, unknown, dispatches }) {
|
||||
const card = {
|
||||
role: 'shangshu',
|
||||
label: ROLE_LABEL.shangshu,
|
||||
|
|
@ -61,12 +75,16 @@ function shangshuCard({ project, goal, bot, budget, unknown, dispatches, botId }
|
|||
name: bot?.name ?? null,
|
||||
model: project.models?.shangshu ?? bot?.model ?? null,
|
||||
exists: Boolean(bot),
|
||||
sessionId: botChatSessionId(bot),
|
||||
clickable: Boolean(botChatSessionId(bot)),
|
||||
line: '未起草目标',
|
||||
detail: '',
|
||||
tone: 'idle',
|
||||
next: '',
|
||||
}
|
||||
if (!goal) {
|
||||
card.detail = '用 group_goal draft / start 起草目标'
|
||||
card.next = '打开尚书会话,起草目标与阶段。'
|
||||
return card
|
||||
}
|
||||
const stages = goal.stages ?? []
|
||||
|
|
@ -79,10 +97,11 @@ function shangshuCard({ project, goal, bot, budget, unknown, dispatches, botId }
|
|||
if (recent) parts.push(clip(recent.action, 12))
|
||||
card.detail = parts.join(' · ')
|
||||
card.tone = goal.status === 'complete' ? 'ok' : unknown > 0 ? 'warn' : 'active'
|
||||
if (unknown > 0) card.next = '先核对 unknown 派发,再决定是否重发。'
|
||||
return card
|
||||
}
|
||||
|
||||
function gongbuCard({ project, goal, bot, stageReviews }) {
|
||||
function gongbuCard({ project, goal, bot, stageReviews, currentStageIndex }) {
|
||||
const card = {
|
||||
role: 'gongbu',
|
||||
label: ROLE_LABEL.gongbu,
|
||||
|
|
@ -91,13 +110,21 @@ function gongbuCard({ project, goal, bot, stageReviews }) {
|
|||
name: bot?.name ?? null,
|
||||
model: project.models?.gongbu ?? bot?.model ?? null,
|
||||
exists: Boolean(bot),
|
||||
sessionId: botChatSessionId(bot),
|
||||
clickable: Boolean(botChatSessionId(bot)),
|
||||
line: '无工单',
|
||||
detail: '',
|
||||
tone: 'idle',
|
||||
next: '',
|
||||
}
|
||||
const stage = goal?.stages?.[goal.current]
|
||||
const counts = taskCounts(stage, project.bots?.gongbu)
|
||||
const reject = latest(stageReviews.filter(review => review.verdict === 'reject'))
|
||||
// 只看当前阶段的最新审查:历史驳回在后续通过后不再显示为返工中。
|
||||
// 兼容旧记录:0-based(goal.current)与 1-based(审查工具)都接受。
|
||||
const currentIndexes = new Set([currentStageIndex, goal?.current])
|
||||
const currentReviews = (stageReviews ?? []).filter(review => currentIndexes.has(review.stageIndex ?? null))
|
||||
const latestStage = latest(currentReviews)
|
||||
const reject = latestStage?.verdict === 'reject' ? latestStage : undefined
|
||||
if (counts.total > 0) {
|
||||
const open = (stage.tasks ?? []).find(task => task.botId === project.bots?.gongbu && task.status !== 'done')
|
||||
card.line = reject
|
||||
|
|
@ -105,19 +132,53 @@ function gongbuCard({ project, goal, bot, stageReviews }) {
|
|||
: counts.open > 0 ? `工单 ${counts.done}/${counts.total}` : `工单 ${counts.total} 条已完成`
|
||||
card.detail = clip(reject?.reason ?? open?.task ?? (stage.tasks ?? []).find(task => task.botId === project.bots?.gongbu)?.task ?? '')
|
||||
card.tone = reject ? 'warn' : counts.open > 0 ? 'active' : 'ok'
|
||||
if (reject) card.next = '按驳回原因返工,完成后提交证据。'
|
||||
return card
|
||||
}
|
||||
if (reject) {
|
||||
card.line = '返工中'
|
||||
card.detail = clip(reject.reason)
|
||||
card.tone = 'warn'
|
||||
card.next = '按驳回原因返工,完成后提交证据。'
|
||||
}
|
||||
return card
|
||||
}
|
||||
|
||||
function stageDecisionFor(project, goal, state) {
|
||||
if (!goal) return undefined
|
||||
const stageIndex = (goal.current ?? -1) + 1
|
||||
const matches = (state.reviews ?? []).filter(review =>
|
||||
review.projectId === project.id && review.goalId === goal.id
|
||||
&& review.kind === 'stage' && (review.stageIndex ?? null) === stageIndex)
|
||||
return latest(matches)
|
||||
}
|
||||
|
||||
function computePhase({ project, goal, roomExists, unknown, state }) {
|
||||
if (!roomExists) return '失败'
|
||||
if (!goal) return Object.keys(project.bots ?? {}).length === 3 ? '待执行' : '待配置'
|
||||
if (goal.status === 'paused') return '暂停'
|
||||
if (goal.status === 'complete') return '已完成'
|
||||
if (goal.status === 'stopped') return '失败'
|
||||
if (goal.status === 'drafting') return '待执行'
|
||||
if (unknown > 0) return '待核实'
|
||||
const stages = goal.stages ?? []
|
||||
const stage = stages[goal.current]
|
||||
const decision = stageDecisionFor(project, goal, state)
|
||||
if (decision?.verdict === 'reject') return '返工中'
|
||||
if (stages.length > 0 && stages.every(item => item.status === 'passed')) return '待审查'
|
||||
if (stage) {
|
||||
const tasks = stage.tasks ?? []
|
||||
const open = tasks.filter(task => task.status !== 'done')
|
||||
if (tasks.length > 0 && open.length === 0) return '待审查'
|
||||
if (tasks.length > 0) return '执行中'
|
||||
}
|
||||
return '待执行'
|
||||
}
|
||||
|
||||
/**
|
||||
* 右侧栏三卡片的数据源:纯函数,方便单测。
|
||||
* 只读 sansheng 自己的状态 + DS Bot 的只读视图,不写任何东西。
|
||||
* v3 增加 phase / attention / currentStage / submission / 折叠历史;旧字段保持兼容。
|
||||
*/
|
||||
export function buildStatePayload({ store, dsbot, now = Date.now() }) {
|
||||
const state = store.peek()
|
||||
|
|
@ -132,16 +193,68 @@ export function buildStatePayload({ store, dsbot, now = Date.now() }) {
|
|||
const bots = ROLE_IDS.map(role => dsbot.botOf(project.bots?.[role]))
|
||||
const roles = [
|
||||
leadCard({ project, goal, bot: bots[0], goalReviews }),
|
||||
shangshuCard({ project, goal, bot: bots[1], budget, unknown, dispatches, botId: project.bots?.shangshu }),
|
||||
gongbuCard({ project, goal, bot: bots[2], stageReviews }),
|
||||
shangshuCard({ project, goal, bot: bots[1], budget, unknown, dispatches }),
|
||||
gongbuCard({ project, goal, bot: bots[2], stageReviews, currentStageIndex: (goal?.current ?? -1) + 1 }),
|
||||
]
|
||||
// 角色卡上的 sessionId 以 DS Bot 当前会话为准(私聊 Bot 的 sessionId)。
|
||||
for (const card of roles) {
|
||||
const bot = dsbot.botOf(card.botId)
|
||||
const botSession = botChatSessionId(bot)
|
||||
if (botSession) {
|
||||
card.sessionId = botSession
|
||||
card.clickable = true
|
||||
}
|
||||
}
|
||||
const phase = computePhase({ project, goal, roomExists: Boolean(room), unknown, state })
|
||||
const attention = roles
|
||||
.filter(card => card.tone === 'warn' || card.tone === 'attention')
|
||||
.map(card => ({ role: card.role, label: card.label, reason: card.detail || card.line, next: card.next }))
|
||||
if (unknown > 0 && !attention.some(item => item.role === 'shangshu')) {
|
||||
attention.push({ role: 'shangshu', label: ROLE_LABEL.shangshu, reason: `${unknown} 条派发待核实`, next: '核对 unknown 派发后再决定是否重发。' })
|
||||
}
|
||||
const stage = goal?.stages?.[goal.current]
|
||||
const decision = stageDecisionFor(project, goal, state)
|
||||
const history = [...(state.reviews ?? []).filter(review => review.projectId === project.id)]
|
||||
.sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0))
|
||||
.slice(0, 20)
|
||||
.map(review => ({
|
||||
id: review.id,
|
||||
kind: review.kind,
|
||||
verdict: review.verdict,
|
||||
reviewerRole: review.reviewerRole,
|
||||
goalRevision: review.goalRevision,
|
||||
stageIndex: review.stageIndex,
|
||||
reason: clip(review.reason ?? review.evidence, 120),
|
||||
at: review.at,
|
||||
}))
|
||||
const artifacts = typeof store.artifactsFor === 'function' ? store.artifactsFor(project.id, 1) : []
|
||||
return {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
roomId: project.roomId,
|
||||
roomName: room?.name ?? null,
|
||||
roomExists: Boolean(room),
|
||||
workspaceId: project.workspaceId ?? null,
|
||||
hostWorkspaceId: project.hostWorkspaceId ?? project.workspaceId ?? null,
|
||||
workDir: project.workDir ?? null,
|
||||
autoRework: project.autoRework !== false,
|
||||
phase,
|
||||
attention,
|
||||
submissionSeq: project.submissionSeq ?? artifacts[0]?.submissionSeq ?? 0,
|
||||
lastSubmission: artifacts.length > 0
|
||||
? {
|
||||
id: artifacts[0].id,
|
||||
digest: artifacts[0].digest,
|
||||
kind: artifacts[0].kind,
|
||||
fileCount: artifacts[0].fileCount,
|
||||
totalBytes: artifacts[0].totalBytes,
|
||||
submissionSeq: artifacts[0].submissionSeq,
|
||||
createdAt: artifacts[0].createdAt,
|
||||
}
|
||||
: null,
|
||||
lease: typeof store.leaseOf === 'function' && store.leaseOf(project.id)
|
||||
? { holder: store.leaseOf(project.id).holder, taskId: store.leaseOf(project.id).taskId, expiresAt: store.leaseOf(project.id).expiresAt }
|
||||
: null,
|
||||
roles,
|
||||
goal: goal
|
||||
? {
|
||||
|
|
@ -155,10 +268,22 @@ export function buildStatePayload({ store, dsbot, now = Date.now() }) {
|
|||
stageTitle: clip(goal.stages?.[goal.current]?.title, 60),
|
||||
}
|
||||
: null,
|
||||
currentStage: stage
|
||||
? {
|
||||
index: goal.current + 1,
|
||||
title: clip(stage.title, 60),
|
||||
acceptance: clip(stage.acceptance, 120),
|
||||
reworks: Number(stage.reworks) || 0,
|
||||
taskCounts: taskCounts(stage, project.bots?.gongbu),
|
||||
lastDecision: decision
|
||||
? { verdict: decision.verdict, reason: clip(decision.reason ?? decision.evidence, 120), at: decision.at }
|
||||
: null,
|
||||
}
|
||||
: null,
|
||||
budget,
|
||||
unknownDispatches: unknown,
|
||||
reviews: goalReviews.concat(stageReviews)
|
||||
.sort((a, b) => (b.at ?? 0) - (a.at ?? 0))
|
||||
.sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0))
|
||||
.slice(0, 3)
|
||||
.map(review => ({
|
||||
kind: review.kind,
|
||||
|
|
@ -168,14 +293,33 @@ export function buildStatePayload({ store, dsbot, now = Date.now() }) {
|
|||
stageIndex: review.stageIndex,
|
||||
at: review.at,
|
||||
})),
|
||||
reviewsHistory: history,
|
||||
recentDispatches: dispatches.map(item => ({
|
||||
id: item.id,
|
||||
action: item.action,
|
||||
status: item.status,
|
||||
at: item.at,
|
||||
stageIndex: item.stageIndex,
|
||||
})),
|
||||
// 只有需要人类动作时才突出显示;其余状态保持安静。
|
||||
nextAction: attention[0]?.next ?? null,
|
||||
}
|
||||
})
|
||||
projects.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN'))
|
||||
return { generatedAt: now, projects }
|
||||
}
|
||||
|
||||
/** 根据 workspaceId / sessionId 找出当前项目(由调用方决定 workspaceId 来源)。 */
|
||||
export function resolveCurrentProject(payload, { workspaceId, sessionId } = {}) {
|
||||
const projects = payload?.projects ?? []
|
||||
if (workspaceId) {
|
||||
const byWorkspace = projects.find(project =>
|
||||
project.workspaceId === workspaceId || project.hostWorkspaceId === workspaceId)
|
||||
if (byWorkspace) return { project: byWorkspace, matchedBy: 'workspace' }
|
||||
}
|
||||
if (sessionId) {
|
||||
const bySession = projects.find(project => project.roles?.some(role => role.sessionId === sessionId))
|
||||
if (bySession) return { project: bySession, matchedBy: 'session' }
|
||||
}
|
||||
return { project: undefined, matchedBy: null }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,748 @@
|
|||
import { execFile, execFileSync } from 'node:child_process'
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import {
|
||||
closeSync,
|
||||
createReadStream,
|
||||
lstatSync,
|
||||
openSync,
|
||||
readdirSync,
|
||||
readSync,
|
||||
statSync,
|
||||
} from 'node:fs'
|
||||
import { lstat, readdir, stat } from 'node:fs/promises'
|
||||
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import { canonical, sha256 } from './digest.js'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
/** 默认排除的目录名;按目录名整棵剪枝。 */
|
||||
export const DEFAULT_EXCLUDE_DIRS = Object.freeze([
|
||||
'.git',
|
||||
'node_modules',
|
||||
'.venv',
|
||||
'venv',
|
||||
'__pycache__',
|
||||
'dist',
|
||||
'build',
|
||||
'coverage',
|
||||
'.next',
|
||||
'.cache',
|
||||
'.turbo',
|
||||
'target',
|
||||
'out',
|
||||
])
|
||||
|
||||
/** 默认排除的文件模式;同时作用于目录名,避免敏感目录被整棵收进来。 */
|
||||
export const DEFAULT_EXCLUDE_FILES = Object.freeze([
|
||||
'*.log',
|
||||
'*.tmp',
|
||||
'.env*',
|
||||
'*.pem',
|
||||
'*.key',
|
||||
'*.p12',
|
||||
'id_rsa*',
|
||||
'credentials*',
|
||||
'.DS_Store',
|
||||
'Thumbs.db',
|
||||
])
|
||||
|
||||
/**
|
||||
* 默认排除集合。本身是可遍历数组,便于调用方直接 includes;
|
||||
* `dirs` / `files` 给出分类,供 UI 或策略合并使用。
|
||||
*/
|
||||
export const DEFAULT_EXCLUDES = Object.freeze(Object.assign(
|
||||
[...DEFAULT_EXCLUDE_DIRS, ...DEFAULT_EXCLUDE_FILES],
|
||||
{ dirs: DEFAULT_EXCLUDE_DIRS, files: DEFAULT_EXCLUDE_FILES },
|
||||
))
|
||||
|
||||
export const DEFAULT_MAX_FILE_BYTES = 4 * 1024 * 1024
|
||||
export const DEFAULT_MAX_FILES = 5000
|
||||
|
||||
/** 单文件内容摘要的硬上限;更大的文件只记录 size/mtime,不把内容读进内存。 */
|
||||
const HASH_LIMIT_BYTES = 64 * 1024 * 1024
|
||||
const READ_CHUNK_BYTES = 1024 * 1024
|
||||
const GIT_MAX_BUFFER = 64 * 1024 * 1024
|
||||
|
||||
const KIND_LABELS = Object.freeze({
|
||||
unscoped: '未指定工作目录',
|
||||
missing: '工作目录不存在',
|
||||
git: 'Git 仓库',
|
||||
files: '普通文件目录',
|
||||
})
|
||||
|
||||
function toPosix(value) {
|
||||
return String(value).split(sep).join('/')
|
||||
}
|
||||
|
||||
function normalizeWorkDir(value) {
|
||||
const text = typeof value === 'string' ? value.trim() : ''
|
||||
if (text === '') return ''
|
||||
return toPosix(resolve(text))
|
||||
}
|
||||
|
||||
function normalizeEntry(value) {
|
||||
let text = typeof value === 'string' ? value.trim() : ''
|
||||
if (text === '') return ''
|
||||
text = text.replace(/\\/g, '/').replace(/^\.\//, '')
|
||||
return text.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
function stringList(value) {
|
||||
if (!Array.isArray(value)) return []
|
||||
const out = []
|
||||
const seen = new Set()
|
||||
for (const item of value) {
|
||||
const text = normalizeEntry(item)
|
||||
if (text === '' || seen.has(text)) continue
|
||||
seen.add(text)
|
||||
out.push(text)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function uniqueStrings(values) {
|
||||
const out = []
|
||||
const seen = new Set()
|
||||
for (const value of values) {
|
||||
if (typeof value !== 'string' || value === '' || seen.has(value)) continue
|
||||
seen.add(value)
|
||||
out.push(value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function positiveNumber(value, fallback) {
|
||||
const number = Number(value)
|
||||
return Number.isFinite(number) && number > 0 ? number : fallback
|
||||
}
|
||||
|
||||
function positiveInteger(value, fallback) {
|
||||
const number = positiveNumber(value, fallback)
|
||||
return Math.max(1, Math.floor(number))
|
||||
}
|
||||
|
||||
/**
|
||||
* 交付范围:默认排除之外追加项目自定义排除;maxFileBytes/maxFiles 也可由
|
||||
* project.delivery 覆盖(服务端仍会对缺失/非法值回落到默认值)。
|
||||
*/
|
||||
export function deliveryPolicyOf(project) {
|
||||
const delivery = project?.delivery && typeof project.delivery === 'object' ? project.delivery : {}
|
||||
return {
|
||||
include: stringList(delivery.include),
|
||||
exclude: uniqueStrings([...DEFAULT_EXCLUDES, ...stringList(delivery.exclude)]),
|
||||
maxFileBytes: positiveNumber(delivery.maxFileBytes, DEFAULT_MAX_FILE_BYTES),
|
||||
maxFiles: positiveInteger(delivery.maxFiles, DEFAULT_MAX_FILES),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePolicy(policy) {
|
||||
const value = policy && typeof policy === 'object' ? policy : {}
|
||||
return {
|
||||
include: stringList(value.include),
|
||||
// 显式传入的 policy 也必须叠加默认排除,不能因为调用方漏写而收集 .env/.git。
|
||||
exclude: uniqueStrings([...DEFAULT_EXCLUDES, ...stringList(value.exclude)]),
|
||||
maxFileBytes: positiveNumber(value.maxFileBytes, DEFAULT_MAX_FILE_BYTES),
|
||||
maxFiles: positiveInteger(value.maxFiles, DEFAULT_MAX_FILES),
|
||||
}
|
||||
}
|
||||
|
||||
function clonePolicy(policy) {
|
||||
return {
|
||||
include: [...policy.include],
|
||||
exclude: [...policy.exclude],
|
||||
maxFileBytes: policy.maxFileBytes,
|
||||
maxFiles: policy.maxFiles,
|
||||
}
|
||||
}
|
||||
|
||||
function globToRegExp(pattern) {
|
||||
let source = '^'
|
||||
for (let i = 0; i < pattern.length; i += 1) {
|
||||
const char = pattern[i]
|
||||
if (char === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
source += '.*'
|
||||
i += 1
|
||||
} else {
|
||||
source += '[^/]*'
|
||||
}
|
||||
} else if (char === '?') {
|
||||
source += '[^/]'
|
||||
} else {
|
||||
source += char.replace(/[-.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
}
|
||||
return new RegExp(`${source}$`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 排除/交付范围匹配器。目录名与文件名中的大小写不敏感(Windows 工作区常见),
|
||||
* 带 `/` 的模式按相对路径匹配,并同时作为目录前缀生效。
|
||||
*/
|
||||
function createScopeMatcher(policy) {
|
||||
const dirNames = new Set(DEFAULT_EXCLUDE_DIRS.map(name => name.toLowerCase()))
|
||||
const patterns = policy.exclude.map(pattern => pattern.toLowerCase()).filter(Boolean)
|
||||
const regexes = new Map()
|
||||
const prefixes = policy.include
|
||||
.map(prefix => prefix.replace(/^\/+/, '').replace(/\/+$/, ''))
|
||||
.filter(Boolean)
|
||||
|
||||
function regexOf(pattern) {
|
||||
let regex = regexes.get(pattern)
|
||||
if (!regex) {
|
||||
regex = globToRegExp(pattern)
|
||||
regexes.set(pattern, regex)
|
||||
}
|
||||
return regex
|
||||
}
|
||||
|
||||
function matchesPattern(pattern, name, relPath) {
|
||||
const lowerRel = relPath.toLowerCase()
|
||||
if (pattern.includes('/')) {
|
||||
if (regexOf(pattern).test(lowerRel)) return true
|
||||
const base = pattern.replace(/\/+$/, '')
|
||||
return lowerRel === base || lowerRel.startsWith(`${base}/`)
|
||||
}
|
||||
return regexOf(pattern).test(name.toLowerCase())
|
||||
}
|
||||
|
||||
return {
|
||||
prefixes,
|
||||
|
||||
dirExcluded(name, relPath) {
|
||||
if (dirNames.has(name.toLowerCase())) return true
|
||||
return patterns.some(pattern => matchesPattern(pattern, name, relPath))
|
||||
},
|
||||
|
||||
fileExcluded(name, relPath) {
|
||||
return patterns.some(pattern => matchesPattern(pattern, name, relPath))
|
||||
},
|
||||
|
||||
/** 对 git 清单里的完整相对路径做排除判断(没有逐层 readdir 的机会)。 */
|
||||
pathExcluded(relPath) {
|
||||
const segments = relPath.split('/')
|
||||
for (let i = 0; i < segments.length - 1; i += 1) {
|
||||
const name = segments[i]
|
||||
const dirRel = segments.slice(0, i + 1).join('/')
|
||||
if (dirNames.has(name.toLowerCase())) return true
|
||||
if (patterns.some(pattern => matchesPattern(pattern, name, dirRel))) return true
|
||||
}
|
||||
const name = segments[segments.length - 1]
|
||||
return patterns.some(pattern => matchesPattern(pattern, name, relPath))
|
||||
},
|
||||
|
||||
underInclude(relPath) {
|
||||
if (prefixes.length === 0) return true
|
||||
return prefixes.some(prefix => relPath === prefix || relPath.startsWith(`${prefix}/`))
|
||||
},
|
||||
|
||||
dirCouldMatchInclude(relPath) {
|
||||
if (prefixes.length === 0) return true
|
||||
return prefixes.some(prefix => (
|
||||
prefix === relPath
|
||||
|| prefix.startsWith(`${relPath}/`)
|
||||
|| relPath.startsWith(`${prefix}/`)
|
||||
))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function sha256Buffer(buffer) {
|
||||
return createHash('sha256').update(buffer).digest('hex')
|
||||
}
|
||||
|
||||
function hashFileSync(filePath) {
|
||||
const hash = createHash('sha256')
|
||||
const handle = openSync(filePath, 'r')
|
||||
try {
|
||||
const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES)
|
||||
for (;;) {
|
||||
const bytes = readSync(handle, buffer, 0, buffer.length, null)
|
||||
if (bytes === 0) break
|
||||
hash.update(bytes === buffer.length ? buffer : buffer.subarray(0, bytes))
|
||||
}
|
||||
} finally {
|
||||
closeSync(handle)
|
||||
}
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
async function hashFile(filePath) {
|
||||
const hash = createHash('sha256')
|
||||
const stream = createReadStream(filePath, { highWaterMark: READ_CHUNK_BYTES })
|
||||
for await (const chunk of stream) hash.update(chunk)
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
function missingPathError(error) {
|
||||
return error?.code === 'ENOENT' || error?.code === 'ENOTDIR'
|
||||
}
|
||||
|
||||
function fileEntrySync(fullPath, relPath) {
|
||||
let info
|
||||
try {
|
||||
info = statSync(fullPath)
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) return null
|
||||
throw error
|
||||
}
|
||||
if (!info.isFile()) return null
|
||||
const base = { path: relPath, size: info.size, mtimeMs: Math.round(info.mtimeMs) }
|
||||
if (info.size > HASH_LIMIT_BYTES) return { ...base, sha256: null, skipped: 'too-large' }
|
||||
try {
|
||||
return { ...base, sha256: hashFileSync(fullPath) }
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) return null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function fileEntry(fullPath, relPath) {
|
||||
let info
|
||||
try {
|
||||
info = await stat(fullPath)
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) return null
|
||||
throw error
|
||||
}
|
||||
if (!info.isFile()) return null
|
||||
const base = { path: relPath, size: info.size, mtimeMs: Math.round(info.mtimeMs) }
|
||||
if (info.size > HASH_LIMIT_BYTES) return { ...base, sha256: null, skipped: 'too-large' }
|
||||
try {
|
||||
return { ...base, sha256: await hashFile(fullPath) }
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) return null
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function direntNameCompare(a, b) {
|
||||
if (a.name < b.name) return -1
|
||||
if (a.name > b.name) return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
function walkFilesSync(context, matcher) {
|
||||
const files = []
|
||||
let truncated = false
|
||||
|
||||
function visit(absDir, relDir) {
|
||||
if (truncated) return
|
||||
const entries = readdirSync(absDir, { withFileTypes: true }).sort(direntNameCompare)
|
||||
for (const entry of entries) {
|
||||
if (truncated) return
|
||||
const name = entry.name
|
||||
const relPath = relDir === '' ? name : `${relDir}/${name}`
|
||||
// 符号链接可能指向工作区外,不追、不 hash。
|
||||
if (entry.isSymbolicLink()) continue
|
||||
if (entry.isDirectory()) {
|
||||
if (matcher.dirExcluded(name, relPath)) continue
|
||||
if (!matcher.dirCouldMatchInclude(relPath)) continue
|
||||
visit(join(absDir, name), relPath)
|
||||
continue
|
||||
}
|
||||
if (!entry.isFile()) continue
|
||||
if (!matcher.underInclude(relPath)) continue
|
||||
if (matcher.fileExcluded(name, relPath)) continue
|
||||
if (files.length >= context.policy.maxFiles) {
|
||||
truncated = true
|
||||
return
|
||||
}
|
||||
const item = fileEntrySync(join(absDir, name), relPath)
|
||||
if (item) files.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
visit(context.workDir, '')
|
||||
return { files, truncated }
|
||||
}
|
||||
|
||||
async function walkFiles(context, matcher) {
|
||||
const files = []
|
||||
let truncated = false
|
||||
|
||||
async function visit(absDir, relDir) {
|
||||
if (truncated) return
|
||||
const entries = (await readdir(absDir, { withFileTypes: true })).sort(direntNameCompare)
|
||||
for (const entry of entries) {
|
||||
if (truncated) return
|
||||
const name = entry.name
|
||||
const relPath = relDir === '' ? name : `${relDir}/${name}`
|
||||
if (entry.isSymbolicLink()) continue
|
||||
if (entry.isDirectory()) {
|
||||
if (matcher.dirExcluded(name, relPath)) continue
|
||||
if (!matcher.dirCouldMatchInclude(relPath)) continue
|
||||
await visit(join(absDir, name), relPath)
|
||||
continue
|
||||
}
|
||||
if (!entry.isFile()) continue
|
||||
if (!matcher.underInclude(relPath)) continue
|
||||
if (matcher.fileExcluded(name, relPath)) continue
|
||||
if (files.length >= context.policy.maxFiles) {
|
||||
truncated = true
|
||||
return
|
||||
}
|
||||
const item = await fileEntry(join(absDir, name), relPath)
|
||||
if (item) files.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
await visit(context.workDir, '')
|
||||
return { files, truncated }
|
||||
}
|
||||
|
||||
function gitOptions() {
|
||||
return {
|
||||
cwd: undefined,
|
||||
encoding: 'buffer',
|
||||
maxBuffer: GIT_MAX_BUFFER,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}
|
||||
}
|
||||
|
||||
function gitOutputSync(workDir, args) {
|
||||
try {
|
||||
const stdout = execFileSync('git', args, { ...gitOptions(), cwd: workDir })
|
||||
return { ok: true, stdout }
|
||||
} catch (error) {
|
||||
return { ok: false, stdout: Buffer.alloc(0), error }
|
||||
}
|
||||
}
|
||||
|
||||
async function gitOutput(workDir, args) {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('git', args, { ...gitOptions(), cwd: workDir })
|
||||
return { ok: true, stdout }
|
||||
} catch (error) {
|
||||
return { ok: false, stdout: Buffer.alloc(0), error }
|
||||
}
|
||||
}
|
||||
|
||||
function decodeNullSeparated(buffer) {
|
||||
return buffer.toString('utf8').split('\0').filter(Boolean)
|
||||
}
|
||||
|
||||
function relativeFromGitPath(workDir, repoRoot, gitPath) {
|
||||
const fullPath = join(repoRoot, ...gitPath.split('/'))
|
||||
const rel = relative(workDir, fullPath)
|
||||
if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null
|
||||
return toPosix(rel)
|
||||
}
|
||||
|
||||
function gitResultDetails(base, status, diff) {
|
||||
const baseCommit = base.ok ? base.stdout.toString('utf8').trim() || null : null
|
||||
if (!status.ok) {
|
||||
throw new Error(`无法读取 Git 状态:${status.error?.message ?? 'git status 失败'}`)
|
||||
}
|
||||
// 尚无提交的仓库没有 HEAD,diff HEAD 失败时按空 diff 处理;已有 HEAD 时失败必须报错。
|
||||
if (!diff.ok && baseCommit !== null) {
|
||||
throw new Error(`无法读取 Git 变更:${diff.error?.message ?? 'git diff 失败'}`)
|
||||
}
|
||||
return {
|
||||
baseCommit,
|
||||
statusDigest: sha256Buffer(status.stdout),
|
||||
diffDigest: sha256Buffer(diff.ok ? diff.stdout : Buffer.alloc(0)),
|
||||
}
|
||||
}
|
||||
|
||||
function collectGitSync(context) {
|
||||
const probe = gitOutputSync(context.workDir, ['rev-parse', '--is-inside-work-tree'])
|
||||
if (!probe.ok || probe.stdout.toString('utf8').trim() !== 'true') return null
|
||||
|
||||
const base = gitOutputSync(context.workDir, ['rev-parse', 'HEAD'])
|
||||
const status = gitOutputSync(context.workDir, ['status', '--porcelain=v1', '-z'])
|
||||
const diff = gitOutputSync(context.workDir, ['diff', 'HEAD', '--binary', '--no-color', '--no-ext-diff'])
|
||||
const details = gitResultDetails(base, status, diff)
|
||||
|
||||
const top = gitOutputSync(context.workDir, ['rev-parse', '--show-toplevel'])
|
||||
const repoRoot = top.ok ? toPosix(resolve(top.stdout.toString('utf8').trim())) : context.workDir
|
||||
const listing = gitOutputSync(context.workDir, ['ls-files', '--others', '--exclude-standard', '--full-name', '-z'])
|
||||
const untracked = listing.ok ? decodeNullSeparated(listing.stdout) : []
|
||||
|
||||
const matcher = createScopeMatcher(context.policy)
|
||||
const files = []
|
||||
let truncated = false
|
||||
for (const gitPath of untracked) {
|
||||
const relPath = relativeFromGitPath(context.workDir, repoRoot, gitPath)
|
||||
if (relPath === null) continue
|
||||
if (!matcher.underInclude(relPath)) continue
|
||||
if (matcher.pathExcluded(relPath)) continue
|
||||
if (files.length >= context.policy.maxFiles) {
|
||||
truncated = true
|
||||
break
|
||||
}
|
||||
let info
|
||||
try {
|
||||
info = lstatSync(join(context.workDir, ...relPath.split('/')))
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) continue
|
||||
throw error
|
||||
}
|
||||
if (info.isSymbolicLink() || !info.isFile()) continue
|
||||
const item = fileEntrySync(join(context.workDir, ...relPath.split('/')), relPath)
|
||||
if (item) files.push(item)
|
||||
}
|
||||
|
||||
return { ...details, files, truncated }
|
||||
}
|
||||
|
||||
async function collectGit(context) {
|
||||
const probe = await gitOutput(context.workDir, ['rev-parse', '--is-inside-work-tree'])
|
||||
if (!probe.ok || probe.stdout.toString('utf8').trim() !== 'true') return null
|
||||
|
||||
const [base, status, diff, top, listing] = await Promise.all([
|
||||
gitOutput(context.workDir, ['rev-parse', 'HEAD']),
|
||||
gitOutput(context.workDir, ['status', '--porcelain=v1', '-z']),
|
||||
gitOutput(context.workDir, ['diff', 'HEAD', '--binary', '--no-color', '--no-ext-diff']),
|
||||
gitOutput(context.workDir, ['rev-parse', '--show-toplevel']),
|
||||
gitOutput(context.workDir, ['ls-files', '--others', '--exclude-standard', '--full-name', '-z']),
|
||||
])
|
||||
const details = gitResultDetails(base, status, diff)
|
||||
|
||||
const repoRoot = top.ok ? toPosix(resolve(top.stdout.toString('utf8').trim())) : context.workDir
|
||||
const untracked = listing.ok ? decodeNullSeparated(listing.stdout) : []
|
||||
const matcher = createScopeMatcher(context.policy)
|
||||
const files = []
|
||||
let truncated = false
|
||||
|
||||
for (const gitPath of untracked) {
|
||||
const relPath = relativeFromGitPath(context.workDir, repoRoot, gitPath)
|
||||
if (relPath === null) continue
|
||||
if (!matcher.underInclude(relPath)) continue
|
||||
if (matcher.pathExcluded(relPath)) continue
|
||||
if (files.length >= context.policy.maxFiles) {
|
||||
truncated = true
|
||||
break
|
||||
}
|
||||
const fullPath = join(context.workDir, ...relPath.split('/'))
|
||||
let info
|
||||
try {
|
||||
info = await lstat(fullPath)
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) continue
|
||||
throw error
|
||||
}
|
||||
if (info.isSymbolicLink() || !info.isFile()) continue
|
||||
const item = await fileEntry(fullPath, relPath)
|
||||
if (item) files.push(item)
|
||||
}
|
||||
|
||||
return { ...details, files, truncated }
|
||||
}
|
||||
|
||||
function buildContext({ project, goal, stageIndex = null, scope = 'stage', policy, now = Date.now() }) {
|
||||
const workDir = normalizeWorkDir(project?.workDir)
|
||||
const normalizedScope = scope === 'goal' ? 'goal' : 'stage'
|
||||
const parsedIndex = stageIndex === null || stageIndex === undefined || stageIndex === '' ? null : Number(stageIndex)
|
||||
const createdAt = typeof now === 'function' ? now() : now
|
||||
return {
|
||||
projectId: project?.id ?? '',
|
||||
goalId: goal?.id ?? null,
|
||||
scope: normalizedScope,
|
||||
stageIndex: normalizedScope === 'goal' || !Number.isInteger(parsedIndex) ? null : parsedIndex,
|
||||
workDir,
|
||||
policy: normalizePolicy(policy ?? deliveryPolicyOf(project)),
|
||||
createdAt: Number.isFinite(Number(createdAt)) ? Number(createdAt) : Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
function makeSnapshot(context, kind) {
|
||||
return {
|
||||
id: `art-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
projectId: context.projectId,
|
||||
goalId: context.goalId,
|
||||
scope: context.scope,
|
||||
stageIndex: context.stageIndex,
|
||||
workDir: context.workDir,
|
||||
kind,
|
||||
exists: false,
|
||||
baseCommit: null,
|
||||
statusDigest: null,
|
||||
diffDigest: null,
|
||||
files: [],
|
||||
fileCount: 0,
|
||||
totalBytes: 0,
|
||||
truncated: false,
|
||||
policy: clonePolicy(context.policy),
|
||||
digest: '',
|
||||
createdAt: context.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
function finalizeSnapshot(snapshot) {
|
||||
snapshot.files.sort((a, b) => {
|
||||
if (a.path < b.path) return -1
|
||||
if (a.path > b.path) return 1
|
||||
return 0
|
||||
})
|
||||
snapshot.fileCount = snapshot.files.length
|
||||
snapshot.totalBytes = snapshot.files.reduce((sum, file) => sum + (Number(file.size) || 0), 0)
|
||||
if (snapshot.kind === 'unscoped') {
|
||||
snapshot.digest = sha256(`unscoped:${snapshot.projectId}`)
|
||||
} else if (snapshot.kind === 'missing') {
|
||||
snapshot.digest = sha256(`missing:${snapshot.projectId}:${snapshot.workDir}`)
|
||||
} else {
|
||||
snapshot.digest = sha256(canonical({
|
||||
workDir: snapshot.workDir,
|
||||
kind: snapshot.kind,
|
||||
baseCommit: snapshot.baseCommit,
|
||||
statusDigest: snapshot.statusDigest,
|
||||
diffDigest: snapshot.diffDigest,
|
||||
files: snapshot.files,
|
||||
}))
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
function fillFromGit(snapshot, collected) {
|
||||
snapshot.exists = true
|
||||
snapshot.baseCommit = collected.baseCommit
|
||||
snapshot.statusDigest = collected.statusDigest
|
||||
snapshot.diffDigest = collected.diffDigest
|
||||
snapshot.files = collected.files
|
||||
snapshot.truncated = collected.truncated
|
||||
return snapshot
|
||||
}
|
||||
|
||||
/**
|
||||
* 抓取一份不可变的成果快照。workDir 为空/不存在时也生成稳定摘要,
|
||||
* 供审查记录引用;调用方不需要(也不允许)自报文件 hash。
|
||||
*/
|
||||
export async function captureArtifactSnapshot({
|
||||
project,
|
||||
goal,
|
||||
stageIndex = null,
|
||||
scope = 'stage',
|
||||
policy,
|
||||
now = Date.now(),
|
||||
} = {}) {
|
||||
const context = buildContext({ project, goal, stageIndex, scope, policy, now })
|
||||
if (context.workDir === '') return finalizeSnapshot(makeSnapshot(context, 'unscoped'))
|
||||
|
||||
let info
|
||||
try {
|
||||
info = await stat(context.workDir)
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) return finalizeSnapshot(makeSnapshot(context, 'missing'))
|
||||
throw error
|
||||
}
|
||||
if (!info.isDirectory()) return finalizeSnapshot(makeSnapshot(context, 'missing'))
|
||||
|
||||
const git = await collectGit(context)
|
||||
if (git) return finalizeSnapshot(fillFromGit(makeSnapshot(context, 'git'), git))
|
||||
|
||||
const walked = await walkFiles(context, createScopeMatcher(context.policy))
|
||||
const snapshot = makeSnapshot(context, 'files')
|
||||
snapshot.exists = true
|
||||
snapshot.files = walked.files
|
||||
snapshot.truncated = walked.truncated
|
||||
return finalizeSnapshot(snapshot)
|
||||
}
|
||||
|
||||
/** captureArtifactSnapshot 的同步版本:语义完全一致,供同步 guard 在最终变更前校验。 */
|
||||
export function captureArtifactSnapshotSync({
|
||||
project,
|
||||
goal,
|
||||
stageIndex = null,
|
||||
scope = 'stage',
|
||||
policy,
|
||||
now = Date.now(),
|
||||
} = {}) {
|
||||
const context = buildContext({ project, goal, stageIndex, scope, policy, now })
|
||||
if (context.workDir === '') return finalizeSnapshot(makeSnapshot(context, 'unscoped'))
|
||||
|
||||
let info
|
||||
try {
|
||||
info = statSync(context.workDir)
|
||||
} catch (error) {
|
||||
if (missingPathError(error)) return finalizeSnapshot(makeSnapshot(context, 'missing'))
|
||||
throw error
|
||||
}
|
||||
if (!info.isDirectory()) return finalizeSnapshot(makeSnapshot(context, 'missing'))
|
||||
|
||||
const git = collectGitSync(context)
|
||||
if (git) return finalizeSnapshot(fillFromGit(makeSnapshot(context, 'git'), git))
|
||||
|
||||
const walked = walkFilesSync(context, createScopeMatcher(context.policy))
|
||||
const snapshot = makeSnapshot(context, 'files')
|
||||
snapshot.exists = true
|
||||
snapshot.files = walked.files
|
||||
snapshot.truncated = walked.truncated
|
||||
return finalizeSnapshot(snapshot)
|
||||
}
|
||||
|
||||
function verifyCurrent(snapshot, project, current) {
|
||||
if (!snapshot || typeof snapshot !== 'object' || snapshot.kind === undefined) {
|
||||
return { ok: false, reason: '缺少可核实的成果快照,无法判断交付内容是否变化。', current: undefined }
|
||||
}
|
||||
if (project && project.id && snapshot.projectId !== undefined && snapshot.projectId !== project.id) {
|
||||
return { ok: false, reason: '成果快照不属于当前项目,不能作为本次审查依据。', current: undefined }
|
||||
}
|
||||
if (snapshot.kind !== current.kind) {
|
||||
const before = KIND_LABELS[snapshot.kind] ?? String(snapshot.kind)
|
||||
const after = KIND_LABELS[current.kind] ?? String(current.kind)
|
||||
return {
|
||||
ok: false,
|
||||
reason: `成果来源已变化:审查时为${before},当前为${after}。`,
|
||||
current,
|
||||
}
|
||||
}
|
||||
if (snapshot.kind === 'unscoped') {
|
||||
// 无工作目录的项目没有可核对的交付物;保持向后兼容。
|
||||
return { ok: true, current }
|
||||
}
|
||||
if (snapshot.kind === 'missing') {
|
||||
if (current.digest === snapshot.digest) return { ok: true, current }
|
||||
return { ok: false, reason: '成果目录已变化:审查时工作目录不存在,当前状态与审查时不一致。', current }
|
||||
}
|
||||
if (snapshot.digest !== current.digest) {
|
||||
return { ok: false, reason: '成果已变化:交付文件或提交与审查时不一致。', current }
|
||||
}
|
||||
return { ok: true, current }
|
||||
}
|
||||
|
||||
/** 重新抓取同 scope 的成果并与审查时的快照摘要比对。 */
|
||||
export async function verifyArtifactSnapshot({ snapshot, project, policy } = {}) {
|
||||
if (!snapshot || typeof snapshot !== 'object' || snapshot.kind === undefined) {
|
||||
return { ok: false, reason: '缺少可核实的成果快照,无法判断交付内容是否变化。', current: undefined }
|
||||
}
|
||||
const current = await captureArtifactSnapshot({
|
||||
project,
|
||||
goal: snapshot.goalId ? { id: snapshot.goalId } : undefined,
|
||||
stageIndex: snapshot.stageIndex ?? null,
|
||||
scope: snapshot.scope ?? 'stage',
|
||||
policy: policy ?? snapshot.policy,
|
||||
})
|
||||
return verifyCurrent(snapshot, project, current)
|
||||
}
|
||||
|
||||
/** verifyArtifactSnapshot 的同步版本。 */
|
||||
export function verifyArtifactSnapshotSync({ snapshot, project, policy } = {}) {
|
||||
if (!snapshot || typeof snapshot !== 'object' || snapshot.kind === undefined) {
|
||||
return { ok: false, reason: '缺少可核实的成果快照,无法判断交付内容是否变化。', current: undefined }
|
||||
}
|
||||
const current = captureArtifactSnapshotSync({
|
||||
project,
|
||||
goal: snapshot.goalId ? { id: snapshot.goalId } : undefined,
|
||||
stageIndex: snapshot.stageIndex ?? null,
|
||||
scope: snapshot.scope ?? 'stage',
|
||||
policy: policy ?? snapshot.policy,
|
||||
})
|
||||
return verifyCurrent(snapshot, project, current)
|
||||
}
|
||||
|
||||
/** 供状态投影/审查记录只读引用的摘要字段。 */
|
||||
export function summarizeSnapshot(snapshot) {
|
||||
return {
|
||||
digest: snapshot?.digest ?? null,
|
||||
kind: snapshot?.kind ?? null,
|
||||
fileCount: snapshot?.fileCount ?? 0,
|
||||
totalBytes: snapshot?.totalBytes ?? 0,
|
||||
truncated: snapshot?.truncated ?? false,
|
||||
baseCommit: snapshot?.baseCommit ?? null,
|
||||
diffDigest: snapshot?.diffDigest ?? null,
|
||||
exists: snapshot?.exists ?? false,
|
||||
}
|
||||
}
|
||||
|
|
@ -63,3 +63,56 @@ export function goalDigest(goal) {
|
|||
})),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* 审查对象摘要:只描述"验收标准与任务范围",不含任务状态/备注/阶段状态。
|
||||
* 纯执行进度变化不应让一份基于同一验收标准的审查无意义失效;
|
||||
* 实际成果是否变化由 ArtifactSnapshot 的 digest 单独约束。
|
||||
*/
|
||||
export function reviewSubjectDigest(kind, goal, stageIndex = null) {
|
||||
if (!goal) return undefined
|
||||
if (kind === 'stage') {
|
||||
const index = Number(stageIndex)
|
||||
const stage = goal.stages?.[index - 1]
|
||||
if (!stage) return undefined
|
||||
return sha256(canonical({
|
||||
kind: 'stage',
|
||||
goalId: goal.id ?? '',
|
||||
stageIndex: index,
|
||||
stageId: stage.id ?? '',
|
||||
title: stage.title ?? '',
|
||||
acceptance: stage.acceptance ?? '',
|
||||
tasks: (stage.tasks ?? []).map(task => ({
|
||||
id: task.id ?? '',
|
||||
botId: task.botId ?? '',
|
||||
task: task.task ?? '',
|
||||
})),
|
||||
}))
|
||||
}
|
||||
if (kind === 'goal') {
|
||||
return sha256(canonical({
|
||||
kind: 'goal',
|
||||
goalId: goal.id ?? '',
|
||||
objective: goal.objective ?? '',
|
||||
acceptance: goal.acceptance ?? '',
|
||||
constraints: goal.constraints ?? [],
|
||||
stages: (goal.stages ?? []).map((stage, i) => ({
|
||||
index: i + 1,
|
||||
stageId: stage.id ?? '',
|
||||
title: stage.title ?? '',
|
||||
acceptance: stage.acceptance ?? '',
|
||||
tasks: (stage.tasks ?? []).map(task => ({
|
||||
id: task.id ?? '',
|
||||
botId: task.botId ?? '',
|
||||
task: task.task ?? '',
|
||||
})),
|
||||
})),
|
||||
}))
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 成果快照摘要(成果模块生成,审查只引用,不自行计算文件 hash)。 */
|
||||
export function artifactDigestOf(snapshot) {
|
||||
return snapshot?.digest
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,12 @@ function emptyState() {
|
|||
return { version: 1, mainBotIds: [], bots: {}, rooms: {} }
|
||||
}
|
||||
|
||||
/** 与 DS Bot 原生 pickRoom 相同的群名规范化:去掉首尾空白和成对引号。 */
|
||||
function unquote(text) {
|
||||
return String(text ?? '').trim().replace(/^["'“”「『《]+|["'“”」』》]+$/g, '').trim()
|
||||
}
|
||||
|
||||
|
||||
function buildIndex(state) {
|
||||
const chats = new Map()
|
||||
const pastChats = new Map()
|
||||
|
|
@ -139,19 +145,28 @@ export class DsBotState {
|
|||
|
||||
/** 私聊里操作某个群目标时,按 id 或名字找这个 Bot 所在的群。 */
|
||||
pickRoom(botId, ref) {
|
||||
const key = String(ref ?? '').trim()
|
||||
const key = unquote(ref)
|
||||
if (key === '') return { error: '缺少群名。' }
|
||||
const rooms = this.roomsOfBot(botId)
|
||||
// Main Bot 在原生 group_goal 里可见所有群;这里必须与原生语义一致,
|
||||
// 否则门禁解析不到群时会错误放行(F01)。
|
||||
const rooms = this.isMain(botId) ? Object.values(this.#state.rooms ?? {}) : this.roomsOfBot(botId)
|
||||
const exactId = rooms.find(room => room.id === key)
|
||||
if (exactId) return { room: exactId }
|
||||
const exactName = rooms.filter(room => room.name === key)
|
||||
const exactName = rooms.filter(room => unquote(room.name) === key)
|
||||
if (exactName.length === 1) return { room: exactName[0] }
|
||||
const loose = rooms.filter(room => room.name?.toLocaleLowerCase() === key.toLocaleLowerCase())
|
||||
const loose = rooms.filter(room => unquote(room.name).toLocaleLowerCase() === key.toLocaleLowerCase())
|
||||
if (loose.length === 1) return { room: loose[0] }
|
||||
if (loose.length > 1) return { error: `有 ${loose.length} 个同名群「${key}」;改用群 id。` }
|
||||
return { error: `这个 Bot 不在名为「${key}」的群里。` }
|
||||
}
|
||||
|
||||
/** 某会话是否 DS Bot 会话(当前或历史私聊/群会话)。 */
|
||||
isBotSession(sessionId) {
|
||||
if (!sessionId) return false
|
||||
return this.selfOf(sessionId) !== undefined
|
||||
}
|
||||
|
||||
|
||||
goalOfRoom(roomId) {
|
||||
return this.roomOf(roomId)?.goal
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { goalDigest, stageDigest } from './digest.js'
|
||||
import { artifactDigestOf, goalDigest, reviewSubjectDigest, stageDigest } from './digest.js'
|
||||
import { roleLabel } from './roles.js'
|
||||
|
||||
export const GOAL_MUTATIONS = new Set([
|
||||
|
|
@ -7,22 +7,6 @@ export const GOAL_MUTATIONS = new Set([
|
|||
|
||||
const deny = (code, reason) => ({ allow: false, code, reason })
|
||||
|
||||
function findReview(reviews, match) {
|
||||
for (let i = (reviews?.length ?? 0) - 1; i >= 0; i -= 1) {
|
||||
const review = reviews[i]
|
||||
if (review.projectId !== match.projectId) continue
|
||||
if (review.goalId !== match.goalId) continue
|
||||
if (review.goalRevision !== match.revision) continue
|
||||
if (review.kind !== match.kind) continue
|
||||
if ((review.stageIndex ?? null) !== (match.stageIndex ?? null)) continue
|
||||
if (review.digest !== match.digest) continue
|
||||
if (review.verdict !== match.verdict) continue
|
||||
if (match.reviewerRole !== undefined && review.reviewerRole !== match.reviewerRole) continue
|
||||
return review
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 返工预算:原生阶段里的 reworks 累计是权威,revise 重建阶段会把它清零,
|
||||
* 所以再与本地返工记录数取较大值,保证"按整个目标累计"不被改写目标绕过。
|
||||
|
|
@ -35,16 +19,81 @@ export function budgetOf(goal, project, recorded = []) {
|
|||
return { used, max, left: Math.max(0, max - used) }
|
||||
}
|
||||
|
||||
function sortKey(review) {
|
||||
return [Number(review?.seq) || 0, Number(review?.at) || 0]
|
||||
}
|
||||
|
||||
function compareReview(a, b) {
|
||||
const [aSeq, aAt] = sortKey(a)
|
||||
const [bSeq, bAt] = sortKey(b)
|
||||
return bSeq - aSeq || bAt - aAt
|
||||
}
|
||||
|
||||
/**
|
||||
* 最新判决:先限定 项目/目标/审查类型/阶段/合法审查身份,再取最新一条;
|
||||
* 绝不先按 verdict 过滤——那会让"先 pass 后 reject"错误命中旧 pass。
|
||||
*/
|
||||
export function latestDecision(reviews, { projectId, goalId, kind, stageIndex = null, reviewerRoles }) {
|
||||
const legal = new Set(reviewerRoles ?? [])
|
||||
const matches = (reviews ?? []).filter(review => {
|
||||
if (!review) return false
|
||||
if (review.projectId !== projectId) return false
|
||||
if (review.goalId !== goalId) return false
|
||||
if (review.kind !== kind) return false
|
||||
if ((review.stageIndex ?? null) !== stageIndex) return false
|
||||
if (legal.size > 0 && !legal.has(review.reviewerRole)) return false
|
||||
return true
|
||||
})
|
||||
if (matches.length === 0) return undefined
|
||||
return matches.sort(compareReview)[0]
|
||||
}
|
||||
|
||||
function reviewDigestOf(review) {
|
||||
return review?.reviewSubjectDigest ?? review?.digest
|
||||
}
|
||||
|
||||
function subjectMatches(review, { kind, goal, stageIndex }) {
|
||||
const stored = reviewDigestOf(review)
|
||||
if (stored === undefined) return false
|
||||
const current = reviewSubjectDigest(kind, goal, stageIndex)
|
||||
if (review.reviewSubjectDigest !== undefined) return stored === current
|
||||
// 兼容 v2 旧记录:它们存的是 stageDigest/goalDigest。
|
||||
const legacy = kind === 'stage' ? stageDigest(goal, stageIndex) : goalDigest(goal)
|
||||
return stored === current || stored === legacy
|
||||
}
|
||||
|
||||
/**
|
||||
* 纯函数门禁:尚书是唯一目标操作者;阶段通过/驳回要自己的审查记录,
|
||||
* 目标完成要丞相的验收记录;返工受预算限制;工部与丞相不得改目标。
|
||||
*
|
||||
* 审批约束(v3):
|
||||
* - 最新判决决定有效性;最新 reject 不能被更旧的 pass 绕过。
|
||||
* - 审查对象摘要(验收标准+任务范围)、成果摘要、提交代次都必须匹配当前值。
|
||||
* - 项目有 workDir 时,审查必须绑定服务端生成的成果快照;成果变化即失效。
|
||||
*/
|
||||
export function evaluateGoalAction({ action, actor, project, goal, reviews, members, args, reworks = [] }) {
|
||||
export function evaluateGoalAction({
|
||||
action, actor, project, goal, reviews, members, args, reworks = [], artifact, projectFreshness,
|
||||
}) {
|
||||
if (!project) return { allow: true }
|
||||
if (!GOAL_MUTATIONS.has(action)) return { allow: true }
|
||||
|
||||
if (project.degraded === true || projectFreshness === 'broken' || projectFreshness === 'missing') {
|
||||
return deny('state-unavailable', '三省六部治理状态不可读(状态文件损坏或加载失败)。受治理目标已停止修改;请先恢复状态文件或重新绑定项目。')
|
||||
}
|
||||
|
||||
if (actor?.kind === 'unknown') {
|
||||
return deny('unknown-actor', actor.reason ?? '无法确认调用者身份,受治理操作已拒绝。')
|
||||
}
|
||||
// 用户从页面/会话直接操作时放行;Bot 才需要角色约束。
|
||||
if (actor?.kind !== 'bot') return { allow: true }
|
||||
|
||||
if (actor.projectConflict) {
|
||||
return deny('project-conflict', `Bot「${actor.botName ?? actor.botId}」同时属于多个项目,无法确定项目边界;请先清理绑定。`)
|
||||
}
|
||||
if (project.id && actor.project && actor.project.id !== project.id) {
|
||||
return deny('project-mismatch', `这是项目「${actor.project.name}」的 Bot,不能修改项目「${project.name}」的目标。`)
|
||||
}
|
||||
|
||||
const shangshuName = members?.find(member => member.role === 'shangshu')?.name ?? '尚书'
|
||||
const leadName = members?.find(member => member.role === 'lead')?.name ?? '丞相'
|
||||
|
||||
|
|
@ -92,14 +141,44 @@ export function evaluateGoalAction({ action, actor, project, goal, reviews, memb
|
|||
|
||||
if (!goal) return { allow: true }
|
||||
|
||||
const checkArtifact = (review) => {
|
||||
if (!project.workDir) return undefined
|
||||
if (!review) return undefined
|
||||
if (!review.artifactDigest) {
|
||||
return deny('no-artifact', '这份审查没有绑定成果快照;请重新用 sansheng_review 记录(会自动生成成果快照)。')
|
||||
}
|
||||
const currentDigest = artifactDigestOf(artifact)
|
||||
if (artifact === undefined || artifact === null) {
|
||||
return deny('artifact-unavailable', '无法读取当前成果快照,不能推进受治理目标。')
|
||||
}
|
||||
if (currentDigest !== review.artifactDigest) {
|
||||
return deny('artifact-changed', '交付成果在审查之后发生了变化(文件、未跟踪交付物或提交不同);旧审查已失效,请重新审查并生成新快照。')
|
||||
}
|
||||
if (Number.isInteger(review.submissionSeq) && Number.isInteger(project.submissionSeq) && review.submissionSeq !== project.submissionSeq) {
|
||||
return deny('submission-advanced', '成果提交代次已推进(已有更新的成果提交);旧审批不能复用,请基于当前成果重新审查。')
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (action === 'pass') {
|
||||
const stageIndex = goal.current + 1
|
||||
const stage = goal.stages?.[stageIndex - 1]
|
||||
if (!stage) return deny('no-stage', '当前没有可通过的阶段。')
|
||||
const digest = stageDigest(goal, stageIndex)
|
||||
if (!findReview(reviews, { projectId: project.id, goalId: goal.id, revision: goal.revision, kind: 'stage', stageIndex, digest, verdict: 'pass' })) {
|
||||
const review = latestDecision(reviews, {
|
||||
projectId: project.id, goalId: goal.id, kind: 'stage', stageIndex,
|
||||
reviewerRoles: ['shangshu', 'user'],
|
||||
})
|
||||
if (!review) {
|
||||
return deny('no-stage-review', `通过阶段 ${stageIndex}「${stage.title}」前,先用 sansheng_review action=stage_pass stage=${stageIndex} evidence=... 记录尚书审查。`)
|
||||
}
|
||||
if (review.verdict !== 'pass') {
|
||||
return deny('latest-reject', `阶段 ${stageIndex} 的最新审查结论是驳回(${review.reason ?? '未写原因'});返工后必须重新记录 stage_pass 才能通过。`)
|
||||
}
|
||||
if (!subjectMatches(review, { kind: 'stage', goal, stageIndex })) {
|
||||
return deny('no-stage-review', `阶段 ${stageIndex} 的最新通过审查针对的是另一版验收标准/任务范围;请按当前版本重新记录 stage_pass。`)
|
||||
}
|
||||
const artifactVerdict = checkArtifact(review)
|
||||
if (artifactVerdict) return artifactVerdict
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
|
|
@ -109,10 +188,19 @@ export function evaluateGoalAction({ action, actor, project, goal, reviews, memb
|
|||
if (budget.used >= budget.max) {
|
||||
return deny('budget', `返工预算已用尽(${budget.used}/${budget.max})。请与用户确认后用 revise 调整目标,或 stop 结束。`)
|
||||
}
|
||||
const digest = stageDigest(goal, stageIndex)
|
||||
if (!findReview(reviews, { projectId: project.id, goalId: goal.id, revision: goal.revision, kind: 'stage', stageIndex, digest, verdict: 'reject' })) {
|
||||
const review = latestDecision(reviews, {
|
||||
projectId: project.id, goalId: goal.id, kind: 'stage', stageIndex,
|
||||
reviewerRoles: ['shangshu', 'user'],
|
||||
})
|
||||
if (!review) {
|
||||
return deny('no-reject-review', `驳回阶段 ${stageIndex} 前,先用 sansheng_review action=stage_reject reason=... 记录审查发现。`)
|
||||
}
|
||||
if (review.verdict !== 'reject') {
|
||||
return deny('latest-pass', `阶段 ${stageIndex} 的最新审查结论是通过;不能基于旧审查发起返工。`)
|
||||
}
|
||||
if (!subjectMatches(review, { kind: 'stage', goal, stageIndex })) {
|
||||
return deny('no-stage-review', `阶段 ${stageIndex} 的最新驳回针对的是另一版验收标准/任务范围;请按当前版本重新记录 stage_reject。`)
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
|
|
@ -121,10 +209,21 @@ export function evaluateGoalAction({ action, actor, project, goal, reviews, memb
|
|||
if (stages.length === 0 || stages.some(stage => stage.status !== 'passed')) {
|
||||
return deny('not-all-passed', '还有阶段未通过,不能完成目标。')
|
||||
}
|
||||
const digest = goalDigest(goal)
|
||||
if (!findReview(reviews, { projectId: project.id, goalId: goal.id, revision: goal.revision, kind: 'goal', stageIndex: null, digest, verdict: 'pass', reviewerRole: 'lead' })) {
|
||||
const review = latestDecision(reviews, {
|
||||
projectId: project.id, goalId: goal.id, kind: 'goal', stageIndex: null,
|
||||
reviewerRoles: ['lead', 'user'],
|
||||
})
|
||||
if (!review) {
|
||||
return deny('no-goal-review', `完成前先由丞相记录目标验收:sansheng_review action=goal_pass evidence=...(当前版本 revision ${goal.revision})。`)
|
||||
}
|
||||
if (review.verdict !== 'pass') {
|
||||
return deny('goal-latest-reject', `目标的最新验收结论是驳回(${review.reason ?? '未写原因'});修正后必须重新记录 goal_pass。`)
|
||||
}
|
||||
if (!subjectMatches(review, { kind: 'goal', goal })) {
|
||||
return deny('no-goal-review', '目标验收针对的是另一版目标/验收标准;请按当前版本重新记录 goal_pass。')
|
||||
}
|
||||
const artifactVerdict = checkArtifact(review)
|
||||
if (artifactVerdict) return artifactVerdict
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,29 +1,59 @@
|
|||
import { captureArtifactSnapshotSync } from './artifact.js'
|
||||
import { evaluateGoalAction, GOAL_MUTATIONS } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import { roleOfBot } from './roles.js'
|
||||
|
||||
/**
|
||||
* 根级 tools.guard:原生 group_goal 执行前同步判定。
|
||||
* 只处理绑定了三省六部项目的群;未绑定的群保持 DS Bot 原生行为。
|
||||
*
|
||||
* 与旧实现的区别:
|
||||
* - 群解析使用与 DS Bot 原生相同的规范化(去引号、Main 可见全部群);
|
||||
* - 解析失败时,若调用者属于某个项目,拒绝而不是放行(F01);
|
||||
* - 先确认调用者是可解析的 Bot 身份;会话过期/状态损坏返回 unknown,绝不按用户放行;
|
||||
* - 项目状态不可读(registry 能证明该群受治理)时停止写操作,避免"空状态=不受治理"。
|
||||
*/
|
||||
export function installGates({ ctx, store, dsbot }) {
|
||||
export function installGates({ ctx, store, dsbot, isBotSession }) {
|
||||
return ctx.tools.guard(exec => {
|
||||
try {
|
||||
if (!exec || exec.name !== 'group_goal') return undefined
|
||||
const action = String(exec.arguments?.action ?? '')
|
||||
if (!GOAL_MUTATIONS.has(action)) return undefined
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession })
|
||||
if (actor.kind === 'unknown') {
|
||||
return `三省六部:${actor.reason}(action=${action})`
|
||||
}
|
||||
if (actor.kind !== 'bot') return undefined
|
||||
if (actor.projectConflict) {
|
||||
return `三省六部:Bot「${actor.botName ?? actor.botId}」同时属于多个项目,拒绝修改目标;请先清理绑定。`
|
||||
}
|
||||
|
||||
let roomId = dsbot.roomOfSession(exec.agent?.id)
|
||||
if (!roomId) {
|
||||
const ref = String(exec.arguments?.group ?? '').trim()
|
||||
if (ref === '') return undefined
|
||||
if (ref === '') {
|
||||
return actor.project
|
||||
? '三省六部:无法确定当前群属于哪个项目(没有群上下文也没有 group 参数),本次目标修改未执行。'
|
||||
: undefined
|
||||
}
|
||||
const picked = dsbot.pickRoom(actor.botId, ref)
|
||||
if (picked.error !== undefined) return undefined
|
||||
if (picked.error !== undefined) {
|
||||
// 项目 Bot 指名一个解析不到的群:宁可拒绝,也不让原生命令落到未治理群或别的项目。
|
||||
if (actor.project || store.registryProjectForBot?.(actor.botId)) {
|
||||
return `三省六部:无法解析群「${ref}」到当前项目(${picked.error}),本次目标修改未执行。`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
roomId = picked.room.id
|
||||
}
|
||||
const project = store.projectByRoom(roomId)
|
||||
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
let project = store.projectByRoom(roomId)
|
||||
if (!project) {
|
||||
const hinted = store.registryProjectForRoom?.(roomId)
|
||||
if (hinted) {
|
||||
project = { id: hinted, name: '(治理状态不可读)', degraded: true, bots: {}, maxReworks: 3 }
|
||||
}
|
||||
}
|
||||
if (!project) return undefined
|
||||
|
||||
const room = dsbot.roomOf(roomId)
|
||||
|
|
@ -32,6 +62,21 @@ export function installGates({ ctx, store, dsbot }) {
|
|||
name: dsbot.botOf(id)?.name ?? id,
|
||||
role: roleOfBot(project, id),
|
||||
}))
|
||||
|
||||
let artifact
|
||||
if (project.workDir && (action === 'pass' || action === 'rework' || action === 'complete')) {
|
||||
try {
|
||||
artifact = captureArtifactSnapshotSync({
|
||||
project,
|
||||
goal: room?.goal,
|
||||
stageIndex: action === 'complete' ? null : (room?.goal?.current ?? -1) + 1,
|
||||
scope: action === 'complete' ? 'goal' : 'stage',
|
||||
})
|
||||
} catch (error) {
|
||||
return `三省六部:无法生成当前成果快照(${error?.message ?? error}),本次目标修改未执行。`
|
||||
}
|
||||
}
|
||||
|
||||
const verdict = evaluateGoalAction({
|
||||
action,
|
||||
actor: { ...actor, role: roleOfBot(project, actor.botId) },
|
||||
|
|
@ -41,6 +86,8 @@ export function installGates({ ctx, store, dsbot }) {
|
|||
reworks: store.peek().reworks,
|
||||
members,
|
||||
args: exec.arguments ?? {},
|
||||
artifact,
|
||||
projectFreshness: health.status,
|
||||
})
|
||||
if (!verdict.allow) return `三省六部:${verdict.reason}`
|
||||
return undefined
|
||||
|
|
|
|||
|
|
@ -0,0 +1,73 @@
|
|||
/**
|
||||
* 对外治理服务:ds-bot 的投递与记忆模块在运行时调用。
|
||||
* 目标是把"项目边界"放在服务端,而不是只靠 prompt 或前端按钮。
|
||||
*/
|
||||
export function installGovernance({ ctx, store }) {
|
||||
const api = {
|
||||
version: 3,
|
||||
projectOfBot(botId) {
|
||||
const project = store.projectByBot(botId)
|
||||
return project ? { id: project.id, name: project.name } : undefined
|
||||
},
|
||||
projectOfRoom(roomId) {
|
||||
const project = store.projectByRoom(roomId)
|
||||
return project ? { id: project.id, name: project.name } : undefined
|
||||
},
|
||||
/** Bot 间投递(含 rt.deliver 与 message_bot 的私聊路径)的项目检查。 */
|
||||
checkDelivery({ fromId, toId, roomId } = {}) {
|
||||
const fromProject = store.projectByBot(fromId)
|
||||
const toProject = store.projectByBot(toId)
|
||||
const roomProject = store.projectByRoom(roomId)
|
||||
|
||||
if (roomProject) {
|
||||
if (fromProject && fromProject.id !== roomProject.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:发送方属于「${fromProject.name}」,群属于「${roomProject.name}」。` }
|
||||
}
|
||||
if (toProject && toProject.id !== roomProject.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:接收方属于「${toProject.name}」,群属于「${roomProject.name}」。` }
|
||||
}
|
||||
if (fromProject && !toProject) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:接收方不属于任何项目,不能接收「${fromProject.name}」的项目内容。` }
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
if (!fromProject) return { allow: true }
|
||||
if (!toProject) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:「${fromProject.name}」的 Bot 不能给项目外 Bot 发私聊消息。` }
|
||||
}
|
||||
if (toProject.id !== fromProject.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:「${fromProject.name}」的 Bot 不能给「${toProject.name}」的 Bot 发消息。` }
|
||||
}
|
||||
return { allow: true }
|
||||
},
|
||||
/** 记忆作用域检查:项目 Bot 不读写 team 共享域,也不能读写别的项目群/成员记忆。 */
|
||||
checkMemoryScope({ botId, scope, roomId, targetBotId } = {}) {
|
||||
if (!botId || botId === 'user') return { allow: true }
|
||||
const project = store.projectByBot(botId)
|
||||
if (!project) return { allow: true }
|
||||
if (scope === 'team') {
|
||||
return { allow: false, reason: `「${project.name}」的项目 Bot 不读写跨项目共享的 team 记忆;项目事实请存在本项目群记忆或自己的记忆里。` }
|
||||
}
|
||||
if (scope === 'group') {
|
||||
const roomProject = store.projectByRoom(roomId)
|
||||
if (!roomProject || roomProject.id !== project.id) {
|
||||
return { allow: false, reason: `记忆边界拒绝:「${project.name}」的 Bot 不能读写其他项目的群记忆。` }
|
||||
}
|
||||
}
|
||||
if (scope === 'bot' && targetBotId) {
|
||||
const targetProject = store.projectByBot(targetBotId)
|
||||
if (!targetProject || targetProject.id !== project.id) {
|
||||
return { allow: false, reason: `记忆边界拒绝:「${project.name}」的 Bot 不能读写其他项目成员的记忆。` }
|
||||
}
|
||||
}
|
||||
return { allow: true }
|
||||
},
|
||||
}
|
||||
try {
|
||||
if (typeof ctx.provide === 'function') ctx.provide('sansheng-governance', api)
|
||||
} catch (error) {
|
||||
console.warn(`sansheng: 无法注册 governance 服务:${error?.message ?? error}`)
|
||||
}
|
||||
return api
|
||||
}
|
||||
|
|
@ -3,19 +3,48 @@ import { roleOfBot } from './roles.js'
|
|||
/**
|
||||
* 一次工具调用的真实身份:DS Bot 的会话 id → Bot id → 项目角色。
|
||||
* 身份只来自执行 agent 的会话映射,绝不采信模型参数里的自称。
|
||||
*
|
||||
* 关键边界:
|
||||
* - 没有 sessionId:宿主/用户直接调用(如右栏按钮),视为用户。
|
||||
* - 会话是 Bot 会话但反查不到 Bot:过期或损坏身份,返回 unknown,绝不降级成用户。
|
||||
* - 非 Bot 会话:普通用户会话,视为用户。
|
||||
* - 一个 Bot 命中多个项目:返回 projectConflict,调用方必须拒绝而不是取第一个。
|
||||
*/
|
||||
export function resolveActor({ dsbot, store, sessionId }) {
|
||||
const botId = sessionId ? dsbot.selfOf(sessionId) : undefined
|
||||
if (!botId) return { kind: 'user', sessionId }
|
||||
export function resolveActor({ dsbot, store, sessionId, isBotSession }) {
|
||||
if (!sessionId) return { kind: 'user', trusted: true, sessionId }
|
||||
const botId = dsbot.selfOf(sessionId)
|
||||
let botSession = false
|
||||
if (typeof isBotSession === 'function') {
|
||||
try {
|
||||
botSession = isBotSession(sessionId) === true
|
||||
} catch {
|
||||
botSession = false
|
||||
}
|
||||
}
|
||||
if (!botId && !botSession) return { kind: 'user', trusted: true, sessionId }
|
||||
if (!botId) {
|
||||
return {
|
||||
kind: 'unknown',
|
||||
trusted: false,
|
||||
sessionId,
|
||||
reason: '这个会话属于 Bot,但当前 DS Bot 状态里找不到对应身份(可能刚被删除或状态文件损坏);受治理操作已拒绝。',
|
||||
}
|
||||
}
|
||||
const bot = dsbot.botOf(botId)
|
||||
const project = store.projectByBot(botId)
|
||||
const projects = typeof store.projectsByBot === 'function'
|
||||
? store.projectsByBot(botId)
|
||||
: [store.projectByBot(botId)].filter(Boolean)
|
||||
const project = projects.length === 1 ? projects[0] : projects[0]
|
||||
return {
|
||||
kind: 'bot',
|
||||
trusted: true,
|
||||
sessionId,
|
||||
botId,
|
||||
botName: bot?.name ?? botId,
|
||||
isMain: dsbot.isMain(botId),
|
||||
project,
|
||||
projectConflict: projects.length > 1,
|
||||
projects,
|
||||
role: project ? roleOfBot(project, botId) : undefined,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,22 @@
|
|||
import { budgetOf } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import { describeDispatch, detectRework, isGoalMutation, isToolError, newId } from './records.js'
|
||||
import {
|
||||
classifyGoalOutcome, describeDispatch, detectRework, isGoalMutation, newId, payloadDigestOf,
|
||||
} from './records.js'
|
||||
import { roleOfBot } from './roles.js'
|
||||
|
||||
function textOfResult(result) {
|
||||
if (typeof result === 'string') return result
|
||||
const content = Array.isArray(result?.content) ? result.content : []
|
||||
return content.filter(part => part?.type === 'text').map(part => String(part.text ?? '')).join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* 观测 group_goal:调用前落一条派发意图,调用后补回执。
|
||||
* 观测 group_goal:调用前落一条派发意图,调用后按"业务是否真的变化"补回执。
|
||||
* 原生机制仍是唯一执行者;这里只记账、对账,以及在确认返工时把返工单交给工部。
|
||||
* 任何记账失败都不能影响原生调用的结果。
|
||||
*/
|
||||
export function installObserver({ ctx, store, dsbot, bootId }) {
|
||||
export function installObserver({ ctx, store, dsbot, bootId, isBotSession }) {
|
||||
return ctx.on('tools/execute', async (exec, next) => {
|
||||
if (!exec || exec.name !== 'group_goal') return next()
|
||||
const action = String(exec.arguments?.action ?? '')
|
||||
|
|
@ -18,8 +26,9 @@ export function installObserver({ ctx, store, dsbot, bootId }) {
|
|||
let before
|
||||
let project
|
||||
let roomId
|
||||
let replay = false
|
||||
try {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession })
|
||||
roomId = dsbot.roomOfSession(exec.agent?.id)
|
||||
if (!roomId) {
|
||||
const ref = String(exec.arguments?.group ?? '').trim()
|
||||
|
|
@ -32,23 +41,38 @@ export function installObserver({ ctx, store, dsbot, bootId }) {
|
|||
if (project) {
|
||||
const room = dsbot.roomOf(roomId)
|
||||
before = room?.goal
|
||||
record = {
|
||||
const stageIndex = action === 'pass' || action === 'rework' ? (before?.current ?? -1) + 1 : null
|
||||
const requestId = String(exec.arguments?.request_id ?? exec.arguments?.requestId ?? '').trim() || undefined
|
||||
const started = await store.beginDispatch({
|
||||
id: newId('dsp'),
|
||||
requestId,
|
||||
payloadDigest: payloadDigestOf({ action, roomId, args: exec.arguments, actorBotId: actor.botId, stageIndex }),
|
||||
bootId,
|
||||
projectId: project.id,
|
||||
roomId,
|
||||
goalId: before?.id ?? null,
|
||||
goalRevision: before?.revision ?? null,
|
||||
action,
|
||||
stageIndex: action === 'pass' || action === 'rework' ? (before?.current ?? -1) + 1 : null,
|
||||
stageIndex,
|
||||
actorBotId: actor.botId ?? null,
|
||||
actorRole: actor.kind === 'bot' ? roleOfBot(project, actor.botId) : 'user',
|
||||
actorName: actor.botName ?? null,
|
||||
reason: String(exec.arguments?.reason ?? '').trim() || null,
|
||||
})
|
||||
record = started.record
|
||||
replay = started.replay === true
|
||||
if (replay) {
|
||||
// 同 requestId 同 payload 的重试:不重新执行原生动作。
|
||||
if (record.nativeResult?.text) return record.nativeResult.text
|
||||
if (record.status === 'prepared' || record.status === 'in_flight' || record.status === 'unknown') {
|
||||
return `三省六部:请求 ${record.requestId ?? record.id} 正在处理或结果未知(${record.status}),本次没有重复执行;请先用 sansheng_reconcile 核实。`
|
||||
}
|
||||
return record.note ?? `三省六部:请求 ${record.requestId ?? record.id} 已处理过,本次没有重复执行。`
|
||||
}
|
||||
await store.beginDispatch(record)
|
||||
if (!replay) await store.markDispatchInFlight(record.id)
|
||||
}
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error?.code === 'payload-conflict') throw error
|
||||
record = undefined
|
||||
}
|
||||
|
||||
|
|
@ -58,7 +82,10 @@ export function installObserver({ ctx, store, dsbot, bootId }) {
|
|||
} catch (error) {
|
||||
if (record) {
|
||||
try {
|
||||
await store.finishDispatch(record.id, { status: 'failed', note: String(error?.message ?? error) })
|
||||
await store.finishDispatch(record.id, {
|
||||
status: 'unknown',
|
||||
note: `原生调用抛出异常,结果未知:${String(error?.message ?? error)}`,
|
||||
})
|
||||
} catch { /* 记账失败不影响调用 */ }
|
||||
}
|
||||
throw error
|
||||
|
|
@ -74,21 +101,23 @@ export function installObserver({ ctx, store, dsbot, bootId }) {
|
|||
}
|
||||
|
||||
async function settle({ ctx, store, dsbot, project, record, action, result, before, roomId }) {
|
||||
const failed = isToolError(result)
|
||||
const after = dsbot.roomOf(roomId)?.goal
|
||||
const after = roomId ? dsbot.roomOf(roomId)?.goal : undefined
|
||||
const outcome = classifyGoalOutcome({ action, before, after, result })
|
||||
const revisionAfter = after?.revision ?? null
|
||||
await store.finishDispatch(record.id, {
|
||||
status: failed ? 'failed' : 'confirmed',
|
||||
status: outcome.status,
|
||||
revisionAfter,
|
||||
note: failed ? '原生调用返回失败。' : null,
|
||||
nativeResult: { ok: outcome.status === 'confirmed', text: textOfResult(result).slice(0, 1000) },
|
||||
note: outcome.note,
|
||||
})
|
||||
await store.addEvent({
|
||||
kind: 'dispatch',
|
||||
projectId: project.id,
|
||||
summary: describeDispatch({ ...record, status: failed ? 'failed' : 'confirmed' }),
|
||||
summary: describeDispatch({ ...record, status: outcome.status }),
|
||||
action,
|
||||
status: outcome.status,
|
||||
})
|
||||
if (failed || action !== 'rework') return
|
||||
if (outcome.status !== 'confirmed' || action !== 'rework') return
|
||||
|
||||
const detected = detectRework({ before, after, reason: record.reason })
|
||||
if (!detected) return
|
||||
|
|
@ -119,6 +148,38 @@ async function settle({ ctx, store, dsbot, project, record, action, result, befo
|
|||
detected.reason === '' ? '' : `驳回原因:${detected.reason}`,
|
||||
`这是第 ${budget.used}/${budget.max} 轮返工;完成后在群里 @尚书 回报,附改动与测试证据。`,
|
||||
].filter(line => line !== '').join('\n')
|
||||
|
||||
// 自动返工是独立于 group_goal 的一次派发:稳定 requestId 保证同一目标版本只发一次。
|
||||
const requestId = `rwk:${after.id}:${revisionAfter}:${project.bots?.gongbu ?? ''}`
|
||||
let dispatch
|
||||
try {
|
||||
const started = await store.beginDispatch({
|
||||
id: newId('dsp'),
|
||||
requestId,
|
||||
payloadDigest: payloadDigestOf({ action: 'auto_rework', roomId, args: { text }, actorBotId: project.bots?.shangshu, stageIndex: detected.stageNo }),
|
||||
bootId: record.bootId,
|
||||
projectId: project.id,
|
||||
roomId,
|
||||
goalId: after.id,
|
||||
goalRevision: revisionAfter,
|
||||
action: 'auto_rework',
|
||||
stageIndex: detected.stageNo,
|
||||
actorBotId: project.bots?.shangshu ?? null,
|
||||
actorRole: 'shangshu',
|
||||
actorName: null,
|
||||
reason: detected.reason,
|
||||
})
|
||||
dispatch = started.record
|
||||
if (started.replay) {
|
||||
await store.finishDispatch(record.id, { autoRework: 'already-delivered' })
|
||||
return
|
||||
}
|
||||
await store.markDispatchInFlight(dispatch.id)
|
||||
} catch {
|
||||
await store.finishDispatch(record.id, { autoRework: 'intent-failed' })
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await rt.deliver({
|
||||
fromId: project.bots.shangshu,
|
||||
|
|
@ -129,8 +190,17 @@ async function settle({ ctx, store, dsbot, project, record, action, result, befo
|
|||
role: 'request',
|
||||
note: '返工派单',
|
||||
})
|
||||
await store.finishDispatch(dispatch.id, {
|
||||
status: 'confirmed',
|
||||
nativeResult: { ok: true, text: '返工消息已交给工部 Session。' },
|
||||
})
|
||||
await store.finishDispatch(record.id, { autoRework: 'delivered' })
|
||||
} catch (error) {
|
||||
await store.finishDispatch(record.id, { autoRework: `failed: ${String(error?.message ?? error)}` })
|
||||
// 失败可能发生在消息已入队之后:记为 unknown,不自动重发,交给 sansheng_reconcile。
|
||||
await store.finishDispatch(dispatch.id, {
|
||||
status: 'unknown',
|
||||
note: `返工投递异常,结果未知:${String(error?.message ?? error)}`,
|
||||
})
|
||||
await store.finishDispatch(record.id, { autoRework: `unknown: ${String(error?.message ?? error)}` })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,331 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { clampInt, instructionsFor, ROOM_NOTICE } from './texts.js'
|
||||
import { ROLE_COLOR, ROLE_IDS, ROLE_LABEL } from './roles.js'
|
||||
|
||||
function clip(text, max) {
|
||||
const value = String(text ?? '').trim()
|
||||
return value.length <= max ? value : value.slice(0, max - 1) + '…'
|
||||
}
|
||||
|
||||
function projectId() {
|
||||
return `prj-${randomUUID().replace(/-/g, '').slice(0, 8)}`
|
||||
}
|
||||
|
||||
function botNameCandidates(base, projectName, id) {
|
||||
const shortName = clip(projectName, 12)
|
||||
return [...new Set([
|
||||
base,
|
||||
`${base}·${shortName}`.slice(0, 40),
|
||||
`${base}·${shortName}·${id.slice(-4)}`.slice(0, 40),
|
||||
`${base}·${id.slice(-6)}`.slice(0, 40),
|
||||
])]
|
||||
}
|
||||
|
||||
/** 全局 Bot 名唯一:先查已有名字,创建时再兜住宿主的重名异常。 */
|
||||
async function createUniqueBot(rt, options, projectName, id) {
|
||||
let lastError
|
||||
for (const name of botNameCandidates(options.name, projectName, id)) {
|
||||
try {
|
||||
if (typeof rt.findBot === 'function' && rt.findBot(name)) continue
|
||||
} catch { /* findBot 不可用时直接尝试创建 */ }
|
||||
try {
|
||||
return await rt.createBot({ ...options, name })
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
if (!/already exists|已存在|同名/i.test(String(error?.message ?? error))) throw error
|
||||
}
|
||||
}
|
||||
throw lastError ?? new Error('无法为 Bot 找到唯一名字。')
|
||||
}
|
||||
|
||||
async function uniqueRoomName(rt, dsbot, base) {
|
||||
const desired = clip(base, 40)
|
||||
const rooms = Object.values(dsbot.snapshot?.().rooms ?? {})
|
||||
if (!rooms.some(room => room.name === desired)) return desired
|
||||
for (let index = 2; index < 100; index += 1) {
|
||||
const next = `${clip(base, 36)}·${index}`
|
||||
if (!rooms.some(room => room.name === next)) return next
|
||||
}
|
||||
return `${clip(base, 32)}·${Date.now().toString(36).slice(-4)}`
|
||||
}
|
||||
|
||||
function checkProjectName(store, name, selfId) {
|
||||
const existing = Object.values(store.peek().projects).find(project => project.name === name && project.id !== selfId)
|
||||
if (existing) return `项目「${name}」已经存在(${existing.id},群 ${existing.roomId});换一个名字。`
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建三省六部项目:三 Bot + 项目群(尚书 admin)+ 绑定。
|
||||
* 账号/工作区只登记,不改宿主项目树;失败只清理本次新建对象。
|
||||
*/
|
||||
export async function provisionProject({ ctx, store, dsbot, args, actor }) {
|
||||
if (actor?.kind === 'bot') return { ok: false, text: '只有用户能创建项目;Bot 在现有项目群里工作。' }
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
if (!rt || typeof rt.createBot !== 'function') {
|
||||
return { ok: false, text: '没有找到 DS-Bot 运行时(dsbot-runtime 服务)。请先安装并启用 ds-bot,再重启 DSH;并用带 ctx.provide 的基线补丁(见 docs/p0/README.md)。' }
|
||||
}
|
||||
await rt.load()
|
||||
|
||||
const projectName = String(args.project ?? args.name ?? '').trim()
|
||||
if (projectName === '') return { ok: false, text: '请提供 project(项目名)。' }
|
||||
if (projectName.length > 40) return { ok: false, text: '项目名最多 40 个字符。' }
|
||||
const nameError = checkProjectName(store, projectName)
|
||||
if (nameError) return { ok: false, text: nameError }
|
||||
|
||||
const id = projectId()
|
||||
const botNames = {
|
||||
lead: String(args.leadName ?? '丞相').trim(),
|
||||
shangshu: String(args.shangshuName ?? '尚书').trim(),
|
||||
gongbu: String(args.gongbuName ?? '工部').trim(),
|
||||
}
|
||||
for (const role of ROLE_IDS) {
|
||||
if (botNames[role] === '') return { ok: false, text: `缺少${ROLE_LABEL[role]}的名字。` }
|
||||
if (botNames[role].length > 40) return { ok: false, text: `${ROLE_LABEL[role]}的名字最多 40 个字符。` }
|
||||
}
|
||||
if (new Set(ROLE_IDS.map(role => botNames[role])).size !== 3) return { ok: false, text: '三个 Bot 的名字必须不同。' }
|
||||
|
||||
const models = {}
|
||||
for (const role of ROLE_IDS) {
|
||||
const raw = args.models?.[role]
|
||||
if (raw === undefined || raw === null || String(raw).trim() === '') continue
|
||||
try {
|
||||
models[role] = await rt.resolveModel(String(raw).trim())
|
||||
} catch (error) {
|
||||
return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}` }
|
||||
}
|
||||
}
|
||||
|
||||
const groupName = await uniqueRoomName(rt, dsbot, String(args.groupName ?? `${projectName} · 三省六部`))
|
||||
const workDir = args.workDir === undefined || args.workDir === null || String(args.workDir).trim() === ''
|
||||
? undefined
|
||||
: String(args.workDir).trim()
|
||||
const workspaceId = args.workspaceId === undefined || args.workspaceId === null || String(args.workspaceId).trim() === ''
|
||||
? null
|
||||
: String(args.workspaceId).trim()
|
||||
const hostWorkspaceId = args.hostWorkspaceId === undefined || args.hostWorkspaceId === null || String(args.hostWorkspaceId).trim() === ''
|
||||
? workspaceId
|
||||
: String(args.hostWorkspaceId).trim()
|
||||
const maxReworks = clampInt(args.maxReworks, 3, 1, 10)
|
||||
|
||||
const created = []
|
||||
let room
|
||||
try {
|
||||
for (const role of ROLE_IDS) {
|
||||
const bot = await createUniqueBot(rt, {
|
||||
name: botNames[role],
|
||||
role: ROLE_LABEL[role],
|
||||
instructions: instructionsFor(role, projectName, groupName),
|
||||
color: ROLE_COLOR[role],
|
||||
brief: `「${projectName}」项目的${ROLE_LABEL[role]}。`,
|
||||
model: models[role],
|
||||
...(workDir === undefined ? {} : { workDir }),
|
||||
}, projectName, id)
|
||||
created.push(bot.id)
|
||||
}
|
||||
room = await rt.createRoom({
|
||||
members: created,
|
||||
name: groupName,
|
||||
admin: created[1],
|
||||
mode: 'admin',
|
||||
createdBy: null,
|
||||
notice: ROOM_NOTICE,
|
||||
})
|
||||
} catch (error) {
|
||||
for (const botId of created) {
|
||||
try { await rt.deleteBot(botId) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
return { ok: false, text: `创建失败:${error?.message ?? error}。已回滚本次新建的 Bot。` }
|
||||
}
|
||||
|
||||
const project = {
|
||||
id,
|
||||
schemaVersion: 3,
|
||||
name: projectName,
|
||||
workspaceId,
|
||||
hostWorkspaceId,
|
||||
projectTreeId: args.projectTreeId ?? null,
|
||||
workDir: workDir ?? null,
|
||||
roomId: room.id,
|
||||
bots: { lead: created[0], shangshu: created[1], gongbu: created[2] },
|
||||
models,
|
||||
maxReworks,
|
||||
autoRework: args.autoRework !== false,
|
||||
delivery: { include: Array.isArray(args.include) ? args.include : [], exclude: Array.isArray(args.exclude) ? args.exclude : [] },
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
try {
|
||||
await store.saveProject(project)
|
||||
} catch (error) {
|
||||
if (typeof rt.deleteRoom === 'function') {
|
||||
try { await rt.deleteRoom(room.id) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
for (const botId of created) {
|
||||
try { await rt.deleteBot(botId) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
return { ok: false, text: `保存项目绑定失败:${error?.message ?? error}。已回滚群与 Bot。` }
|
||||
}
|
||||
|
||||
const actualNames = await Promise.all(created.map(async botId => rt.botOf?.(botId)?.name ?? botId))
|
||||
return {
|
||||
ok: true,
|
||||
project,
|
||||
text: [
|
||||
`已创建项目「${projectName}」${project.id}。`,
|
||||
`群「${room.name}」:管理员=尚书 ${actualNames[1] ?? botNames.shangshu}。`,
|
||||
`Bot:丞相 ${actualNames[0] ?? botNames.lead} / 尚书 ${actualNames[1] ?? botNames.shangshu} / 工部 ${actualNames[2] ?? botNames.gongbu}。`,
|
||||
`模型:${ROLE_IDS.map(role => `${ROLE_LABEL[role]}=${models[role] ?? 'DS Bot 默认'}`).join(',')}。`,
|
||||
`工作目录:${workDir ?? '未设置(成果快照只按项目记账)'}${workspaceId ? `;工作区 ${workspaceId}` : ''}。`,
|
||||
`返工预算 ${maxReworks} 轮(按整个目标累计)。`,
|
||||
'下一步:在项目群发需求,让丞相对齐目标;尚书用 group_goal 起草/启动,并按阶段 @工部 派工。',
|
||||
].join('\n'),
|
||||
}
|
||||
}
|
||||
|
||||
/** 把已有群绑定为项目:角色互异、群管理员正确、Bot/群唯一。 */
|
||||
export async function bindProject({ store, dsbot, rt, args }) {
|
||||
const roomRef = String(args.room ?? '').trim()
|
||||
if (roomRef === '') return { ok: false, text: '请提供 room(项目群名或 id)。' }
|
||||
const state = dsbot.snapshot()
|
||||
const rooms = Object.values(state.rooms ?? {})
|
||||
const unquote = text => String(text ?? '').trim().replace(/^["'“”「『《]+|["'“”」』》]+$/g, '').trim()
|
||||
const room = rooms.find(item => item.id === roomRef)
|
||||
?? rooms.find(item => unquote(item.name) === unquote(roomRef))
|
||||
?? rooms.find(item => unquote(item.name).toLocaleLowerCase() === unquote(roomRef).toLocaleLowerCase())
|
||||
if (!room) return { ok: false, text: `找不到群「${roomRef}」。确认群名,或先在 DS Bot 里建群。` }
|
||||
const existing = store.projectByRoom(room.id)
|
||||
if (existing) return { ok: false, text: `群「${room.name}」已绑定项目「${existing.name}」(${existing.id})。` }
|
||||
|
||||
const findBot = ref => {
|
||||
const key = String(ref ?? '').trim()
|
||||
if (key === '') return undefined
|
||||
return state.bots?.[key] ?? dsbot.botByName(key)
|
||||
}
|
||||
const bots = {}
|
||||
for (const role of ROLE_IDS) {
|
||||
let bot = findBot(args[role])
|
||||
if (!bot) {
|
||||
bot = Object.values(state.bots ?? {}).find(item =>
|
||||
(room.members ?? []).includes(item.id) && (item.role === ROLE_LABEL[role] || item.name === ROLE_LABEL[role]))
|
||||
}
|
||||
if (!bot) return { ok: false, text: `没找到${ROLE_LABEL[role]} Bot:请用 ${role} 参数给名字或 id,或先把它加入群。` }
|
||||
if (!(room.members ?? []).includes(bot.id)) return { ok: false, text: `${ROLE_LABEL[role]}「${bot.name}」不在群「${room.name}」里。` }
|
||||
const bound = store.projectsByBot(bot.id)
|
||||
if (bound.length > 0) return { ok: false, text: `Bot「${bot.name}」已属于项目「${bound[0].name}」(${bound[0].id}),一个 Bot 只能属于一个项目。` }
|
||||
bots[role] = bot.id
|
||||
}
|
||||
if (new Set(Object.values(bots)).size !== 3) return { ok: false, text: '丞相/尚书/工部必须是三个不同的 Bot。' }
|
||||
if (room.admin !== bots.shangshu) {
|
||||
const admin = room.admin ? state.bots?.[room.admin]?.name ?? room.admin : '无'
|
||||
return { ok: false, text: `群管理员当前是 ${admin},必须是尚书。先在 DS Bot 的群设置里把管理员改成${ROLE_LABEL.shangshu},再绑定。` }
|
||||
}
|
||||
|
||||
const projectName = String(args.project ?? room.name).trim().slice(0, 40)
|
||||
const nameError = checkProjectName(store, projectName)
|
||||
if (nameError) return { ok: false, text: nameError }
|
||||
const workDir = args.workDir === undefined || args.workDir === null || String(args.workDir).trim() === ''
|
||||
? null
|
||||
: String(args.workDir).trim()
|
||||
// 绑定已有 Bot 时把工作根落到 Bot 的会话上,文件边界才真正生效(不能只写提示词)。
|
||||
if (workDir && rt && typeof rt.updateBot === 'function') {
|
||||
for (const role of ROLE_IDS) {
|
||||
try {
|
||||
await rt.updateBot(bots[role], { workDir }, undefined)
|
||||
} catch (error) {
|
||||
return { ok: false, text: `设置${ROLE_LABEL[role]}工作目录失败:${error?.message ?? error}` }
|
||||
}
|
||||
}
|
||||
}
|
||||
const id = projectId()
|
||||
const project = {
|
||||
id,
|
||||
schemaVersion: 3,
|
||||
name: projectName,
|
||||
workspaceId: args.workspaceId === undefined || args.workspaceId === null ? null : String(args.workspaceId),
|
||||
hostWorkspaceId: args.hostWorkspaceId === undefined || args.hostWorkspaceId === null ? null : String(args.hostWorkspaceId),
|
||||
projectTreeId: args.projectTreeId ?? null,
|
||||
workDir,
|
||||
roomId: room.id,
|
||||
bots,
|
||||
models: args.models ?? {},
|
||||
maxReworks: clampInt(args.maxReworks, 3, 1, 10),
|
||||
autoRework: args.autoRework !== false,
|
||||
delivery: { include: Array.isArray(args.include) ? args.include : [], exclude: Array.isArray(args.exclude) ? args.exclude : [] },
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
try {
|
||||
await store.saveProject(project)
|
||||
} catch (error) {
|
||||
return { ok: false, text: `绑定失败:${error?.message ?? error}` }
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
project,
|
||||
text: [
|
||||
`已把群「${room.name}」绑定为项目「${project.name}」(${project.id})。`,
|
||||
`丞相=${state.bots?.[bots.lead]?.name},尚书=${state.bots?.[bots.shangshu]?.name}(管理员),工部=${state.bots?.[bots.gongbu]?.name}。`,
|
||||
'从下一次 group_goal 起,角色、审查记录与返工预算开始生效。',
|
||||
].join('\n'),
|
||||
}
|
||||
}
|
||||
|
||||
/** 只影响本项目的模型/预算/自动返工/交付范围配置。 */
|
||||
export async function updateProjectConfig({ ctx, store, args }) {
|
||||
const project = store.resolveProject(args.project ?? args.projectId)
|
||||
if (!project) return { ok: false, text: `找不到项目「${args.project ?? args.projectId ?? ''}」。` }
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
const patch = {}
|
||||
const changed = []
|
||||
|
||||
if (args.models && typeof args.models === 'object') {
|
||||
const models = { ...project.models }
|
||||
const applied = []
|
||||
for (const role of ROLE_IDS) {
|
||||
const raw = args.models[role]
|
||||
if (raw === undefined || raw === null || String(raw).trim() === '') continue
|
||||
let resolved = String(raw).trim()
|
||||
try {
|
||||
if (rt && typeof rt.resolveModel === 'function') resolved = await rt.resolveModel(resolved)
|
||||
} catch (error) {
|
||||
return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}` }
|
||||
}
|
||||
const botId = project.bots?.[role]
|
||||
if (rt && typeof rt.updateBot === 'function' && botId) {
|
||||
try {
|
||||
await rt.updateBot(botId, { model: resolved }, undefined)
|
||||
} catch (error) {
|
||||
for (const undo of applied) {
|
||||
try { await rt.updateBot(undo.botId, { model: undo.previous }, undefined) } catch { /* 尽力回滚 */ }
|
||||
}
|
||||
return { ok: false, text: `更新${ROLE_LABEL[role]}模型失败:${error?.message ?? error}` }
|
||||
}
|
||||
applied.push({ botId, previous: project.models?.[role] ?? null })
|
||||
}
|
||||
models[role] = resolved
|
||||
changed.push(`${ROLE_LABEL[role]}模型=${resolved}`)
|
||||
}
|
||||
patch.models = models
|
||||
}
|
||||
if (args.maxReworks !== undefined) {
|
||||
patch.maxReworks = clampInt(args.maxReworks, project.maxReworks ?? 3, 1, 10)
|
||||
changed.push(`返工预算=${patch.maxReworks}`)
|
||||
}
|
||||
if (args.autoRework !== undefined) {
|
||||
patch.autoRework = args.autoRework !== false
|
||||
changed.push(`自动返工=${patch.autoRework ? '开' : '关'}`)
|
||||
}
|
||||
if (args.include !== undefined || args.exclude !== undefined) {
|
||||
patch.delivery = {
|
||||
include: Array.isArray(args.include) ? args.include : project.delivery?.include ?? [],
|
||||
exclude: Array.isArray(args.exclude) ? args.exclude : project.delivery?.exclude ?? [],
|
||||
}
|
||||
changed.push('交付范围已更新')
|
||||
}
|
||||
if (changed.length === 0) return { ok: false, text: '没有要修改的配置。可改 models / maxReworks / autoRework / include / exclude。' }
|
||||
try {
|
||||
await store.updateProject(project.id, patch)
|
||||
} catch (error) {
|
||||
return { ok: false, text: `保存配置失败:${error?.message ?? error}` }
|
||||
}
|
||||
return { ok: true, text: `已更新项目「${project.name}」(${project.id}):${changed.join(',')}。只影响本项目,其他项目与正在运行的会话不受影响。` }
|
||||
}
|
||||
|
|
@ -1,8 +1,19 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { canonical, sha256 } from './digest.js'
|
||||
import { budgetOf } from './gate.js'
|
||||
|
||||
const MUTATIONS = new Set(['draft', 'start', 'revise', 'task', 'pass', 'rework', 'complete', 'pause', 'resume', 'stop'])
|
||||
|
||||
export const DISPATCH_STATUS = Object.freeze({
|
||||
prepared: '已准备',
|
||||
in_flight: '发送中',
|
||||
confirmed: '已确认',
|
||||
rejected: '被拒绝',
|
||||
failed: '未执行',
|
||||
unknown: '待核实',
|
||||
cancelled: '已取消',
|
||||
})
|
||||
|
||||
export function isGoalMutation(action) {
|
||||
return MUTATIONS.has(String(action ?? ''))
|
||||
}
|
||||
|
|
@ -16,12 +27,45 @@ export function newBootId() {
|
|||
return `boot-${Date.now().toString(36)}-${randomUUID().replace(/-/g, '').slice(0, 6)}`
|
||||
}
|
||||
|
||||
function textOfResult(result) {
|
||||
if (result === undefined || result === null) return ''
|
||||
if (typeof result === 'string') return result
|
||||
const content = Array.isArray(result.content) ? result.content : []
|
||||
return content.filter(part => part?.type === 'text').map(part => String(part.text ?? '')).join('\n')
|
||||
}
|
||||
|
||||
/** 工具结果里的失败标记;不同版本可能用 isError 或 error 字段。 */
|
||||
export function isToolError(result) {
|
||||
if (result === undefined || result === null) return false
|
||||
if (result.isError === true || result.error !== undefined) return true
|
||||
const content = Array.isArray(result.content) ? result.content : []
|
||||
return content.some(part => part?.type === 'text' && String(part.text ?? '').startsWith('Error:'))
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 区分"执行器没报错"与"业务真的变了"。
|
||||
* 原生 group_goal 的业务拒绝是普通字符串,isError 不置位;所以必须看目标 revision/id 前后快照。
|
||||
* 返回 { status:'confirmed'|'rejected', note }。
|
||||
*/
|
||||
export function classifyGoalOutcome({ action, before, after, result }) {
|
||||
if (isToolError(result)) {
|
||||
return { status: 'rejected', note: textOfResult(result) || '原生调用返回失败。' }
|
||||
}
|
||||
const beforeId = before?.id ?? null
|
||||
const afterId = after?.id ?? null
|
||||
const beforeRevision = Number(before?.revision ?? -1)
|
||||
const afterRevision = Number(after?.revision ?? -1)
|
||||
const changed = after !== undefined && (
|
||||
afterId !== beforeId
|
||||
|| afterRevision > beforeRevision
|
||||
|| (action === 'draft' && after?.status === 'drafting')
|
||||
|| (action === 'start' && after?.status === 'active')
|
||||
)
|
||||
if (changed) return { status: 'confirmed', note: null }
|
||||
const text = textOfResult(result)
|
||||
return {
|
||||
status: 'rejected',
|
||||
note: text === '' ? '原生目标状态没有变化,按业务拒绝处理。' : text.slice(0, 500),
|
||||
}
|
||||
}
|
||||
|
||||
function stageIndexOf(stageList, predicate) {
|
||||
|
|
@ -55,16 +99,16 @@ export function detectRework({ before, after, reason }) {
|
|||
|
||||
/** 派发记录前缀(状态展示用)。 */
|
||||
export function describeDispatch(record) {
|
||||
const status = {
|
||||
intent: '进行中',
|
||||
confirmed: '已确认',
|
||||
failed: '未执行',
|
||||
unknown: '待核实',
|
||||
}[record.status] ?? record.status
|
||||
const status = DISPATCH_STATUS[record.status] ?? record.status
|
||||
const stage = Number.isInteger(record.stageIndex) ? ` 阶段${record.stageIndex}` : ''
|
||||
return `${record.id} ${record.action}${stage} → ${status}`
|
||||
}
|
||||
|
||||
/** 派发 payload 的稳定摘要:同 requestId 不同 payload 必须拒绝。 */
|
||||
export function payloadDigestOf({ action, roomId, args, actorBotId, stageIndex }) {
|
||||
return sha256(canonical({ action, roomId, args: args ?? {}, actorBotId: actorBotId ?? null, stageIndex: stageIndex ?? null }))
|
||||
}
|
||||
|
||||
export function budgetAfter(goal, project, recorded = []) {
|
||||
return budgetOf(goal, project, recorded)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
import { buildStatePayload } from './api.js'
|
||||
import { buildStatePayload, resolveCurrentProject } from './api.js'
|
||||
import { provisionProject, updateProjectConfig } from './provision.js'
|
||||
|
||||
const BODY_LIMIT = 128 * 1024
|
||||
|
||||
function send(res, status, payload) {
|
||||
const body = JSON.stringify(payload)
|
||||
|
|
@ -9,9 +12,77 @@ function send(res, status, payload) {
|
|||
res.end(body)
|
||||
}
|
||||
|
||||
function query(req) {
|
||||
try {
|
||||
const url = new URL(req.url ?? '/', 'http://localhost')
|
||||
return Object.fromEntries(url.searchParams.entries())
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let size = 0
|
||||
const chunks = []
|
||||
req.on('data', chunk => {
|
||||
size += chunk.length
|
||||
if (size > BODY_LIMIT) {
|
||||
reject(Object.assign(new Error('请求体过大'), { statusCode: 413 }))
|
||||
req.destroy()
|
||||
return
|
||||
}
|
||||
chunks.push(chunk)
|
||||
})
|
||||
req.on('end', () => {
|
||||
if (chunks.length === 0) return resolve({})
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
|
||||
} catch (error) {
|
||||
reject(Object.assign(new Error(`JSON 解析失败:${error?.message ?? error}`), { statusCode: 400 }))
|
||||
}
|
||||
})
|
||||
req.on('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
function methodGuard(req, res, methods) {
|
||||
if (methods.includes(req.method)) return true
|
||||
send(res, 405, { error: 'method not allowed', allow: methods })
|
||||
return false
|
||||
}
|
||||
|
||||
function projectSummary(project) {
|
||||
if (!project) return null
|
||||
return {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
workspaceId: project.workspaceId ?? null,
|
||||
hostWorkspaceId: project.hostWorkspaceId ?? project.workspaceId ?? null,
|
||||
workDir: project.workDir ?? null,
|
||||
roomId: project.roomId ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
function findProjectForWorkspace({ store, workspaceId, path }) {
|
||||
const projects = Object.values(store.peek().projects)
|
||||
if (workspaceId) {
|
||||
const byWorkspace = projects.find(project =>
|
||||
project.workspaceId === workspaceId || project.hostWorkspaceId === workspaceId || project.projectTreeId === workspaceId)
|
||||
if (byWorkspace) return byWorkspace
|
||||
}
|
||||
if (path) {
|
||||
const normalized = String(path).replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
|
||||
const byPath = projects.find(project => project.workDir
|
||||
&& String(project.workDir).replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase() === normalized)
|
||||
if (byPath) return byPath
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 右栏三卡片的数据接口。只读:读 sansheng 自己的状态与 DS Bot 的只读视图。
|
||||
* 与工具走同一份数据,页面不额外持有真相。
|
||||
* 右栏数据与项目动作接口。读取只读;写入端点只做用户显式动作(初始化/配置/控制/核实),
|
||||
* 每个写端点都重新校验 projectId 与项目上下文,不依赖前端状态。
|
||||
*/
|
||||
export function installRoute({ ctx, store, dsbot }) {
|
||||
const web = typeof ctx.get === 'function' ? ctx.get('webServer', false) : undefined
|
||||
|
|
@ -19,19 +90,152 @@ export function installRoute({ ctx, store, dsbot }) {
|
|||
console.warn('sansheng: 没有 webServer 服务,右栏数据接口不可用(工具与门禁不受影响)。')
|
||||
return
|
||||
}
|
||||
ctx.effect(() => web.register({
|
||||
kind: 'exact',
|
||||
path: '/sansheng/state',
|
||||
handler: async (req, res) => {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
send(res, 405, { error: 'method not allowed' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
send(res, 200, buildStatePayload({ store, dsbot }))
|
||||
} catch (error) {
|
||||
send(res, 500, { error: `读取三省六部状态失败:${error?.message ?? error}` })
|
||||
}
|
||||
},
|
||||
}), 'sansheng: 右栏数据接口')
|
||||
const register = (path, handler) => {
|
||||
try {
|
||||
const dispose = web.register({ kind: 'exact', path, handler })
|
||||
if (typeof ctx.effect === 'function') ctx.effect(() => dispose)
|
||||
return dispose
|
||||
} catch (error) {
|
||||
console.warn(`sansheng: 注册 ${path} 失败:${error?.message ?? error}`)
|
||||
return () => {}
|
||||
}
|
||||
}
|
||||
|
||||
register('/sansheng/state', async (req, res) => {
|
||||
if (!methodGuard(req, res, ['GET', 'HEAD'])) return
|
||||
try {
|
||||
const params = query(req)
|
||||
const payload = buildStatePayload({ store, dsbot })
|
||||
const current = resolveCurrentProject(payload, { workspaceId: params.workspaceId, sessionId: params.sessionId })
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
send(res, 200, {
|
||||
...payload,
|
||||
current: current.project ?? null,
|
||||
currentMatch: current.matchedBy,
|
||||
health: { status: health.status, error: health.error ?? null },
|
||||
})
|
||||
} catch (error) {
|
||||
send(res, 500, { error: `读取三省六部状态失败:${error?.message ?? error}` })
|
||||
}
|
||||
})
|
||||
|
||||
register('/sansheng/health', async (req, res) => {
|
||||
if (!methodGuard(req, res, ['GET', 'HEAD'])) return
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
const bots = dsbot.snapshot?.() ?? {}
|
||||
send(res, health.status === 'broken' ? 503 : 200, {
|
||||
store: health,
|
||||
governance: (() => {
|
||||
try { return typeof ctx.get('sansheng-governance', false)?.checkDelivery === 'function' } catch { return false }
|
||||
})(),
|
||||
dsbot: {
|
||||
path: dsbot.file,
|
||||
bots: Object.keys(bots.bots ?? {}).length,
|
||||
rooms: Object.keys(bots.rooms ?? {}).length,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
register('/sansheng/project/resolve', async (req, res) => {
|
||||
if (!methodGuard(req, res, ['POST'])) return
|
||||
try {
|
||||
const body = await readBody(req)
|
||||
const project = findProjectForWorkspace({ store, workspaceId: body.workspaceId, path: body.path })
|
||||
if (!project) return send(res, 200, { missing: true, workspaceId: body.workspaceId ?? null })
|
||||
send(res, 200, { missing: false, project: projectSummary(project) })
|
||||
} catch (error) {
|
||||
send(res, error.statusCode ?? 500, { error: String(error?.message ?? error) })
|
||||
}
|
||||
})
|
||||
|
||||
register('/sansheng/provision', async (req, res) => {
|
||||
if (!methodGuard(req, res, ['POST'])) return
|
||||
try {
|
||||
const body = await readBody(req)
|
||||
const result = await provisionProject({
|
||||
ctx,
|
||||
store,
|
||||
dsbot,
|
||||
args: {
|
||||
project: body.name ?? body.project,
|
||||
workDir: body.path ?? body.workDir,
|
||||
workspaceId: body.workspaceId,
|
||||
hostWorkspaceId: body.workspaceId,
|
||||
projectTreeId: body.projectTreeId,
|
||||
models: body.models,
|
||||
maxReworks: body.maxReworks,
|
||||
},
|
||||
actor: { kind: 'user' },
|
||||
})
|
||||
if (!result.ok) return send(res, 400, { ok: false, error: result.text })
|
||||
send(res, 200, { ok: true, text: result.text, project: projectSummary(result.project) })
|
||||
} catch (error) {
|
||||
send(res, error.statusCode ?? 500, { error: String(error?.message ?? error) })
|
||||
}
|
||||
})
|
||||
|
||||
register('/sansheng/config', async (req, res) => {
|
||||
if (!methodGuard(req, res, ['POST'])) return
|
||||
try {
|
||||
const body = await readBody(req)
|
||||
const project = store.resolveProject(body.projectId ?? body.project)
|
||||
if (!project) return send(res, 404, { ok: false, error: '找不到项目。' })
|
||||
const result = await updateProjectConfig({
|
||||
ctx,
|
||||
store,
|
||||
args: {
|
||||
projectId: project.id,
|
||||
models: body.models,
|
||||
maxReworks: body.maxReworks,
|
||||
autoRework: body.autoRework,
|
||||
include: body.include,
|
||||
exclude: body.exclude,
|
||||
},
|
||||
})
|
||||
send(res, result.ok ? 200 : 400, { ok: result.ok, text: result.text, error: result.ok ? undefined : result.text })
|
||||
} catch (error) {
|
||||
send(res, error.statusCode ?? 500, { error: String(error?.message ?? error) })
|
||||
}
|
||||
})
|
||||
|
||||
register('/sansheng/control', async (req, res) => {
|
||||
if (!methodGuard(req, res, ['POST'])) return
|
||||
try {
|
||||
const body = await readBody(req)
|
||||
const project = store.resolveProject(body.projectId ?? body.project)
|
||||
if (!project) return send(res, 404, { ok: false, error: '找不到项目。' })
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
if (!rt || typeof rt.goalControl !== 'function') return send(res, 503, { ok: false, error: 'DS-Bot 运行时不可用。' })
|
||||
const room = dsbot.roomOf(project.roomId)
|
||||
const goal = room?.goal
|
||||
if (!goal) return send(res, 409, { ok: false, error: '项目没有进行中的目标。' })
|
||||
const action = String(body.action ?? '')
|
||||
const map = { pause: 'pause', resume: 'resume', stop: 'stop', cancel: 'stop' }
|
||||
if (!map[action]) return send(res, 400, { ok: false, error: 'action 必须是 pause / resume / stop / cancel。' })
|
||||
if (action === 'cancel' && body.confirm !== true) return send(res, 400, { ok: false, error: '取消需要 confirm=true。' })
|
||||
const result = await rt.goalControl(project.roomId, { goalId: goal.id, action: map[action], ...(action === 'cancel' ? { stopWork: true } : {}) })
|
||||
if (result?.error) return send(res, 409, { ok: false, error: result.error })
|
||||
send(res, 200, { ok: true, text: action === 'pause' ? '已暂停' : action === 'resume' ? '已恢复' : '已请求停止' })
|
||||
} catch (error) {
|
||||
send(res, error.statusCode ?? 500, { error: String(error?.message ?? error) })
|
||||
}
|
||||
})
|
||||
|
||||
register('/sansheng/reconcile', async (req, res) => {
|
||||
if (!methodGuard(req, res, ['POST'])) return
|
||||
try {
|
||||
const body = await readBody(req)
|
||||
const project = store.resolveProject(body.projectId ?? body.project)
|
||||
if (!project) return send(res, 404, { ok: false, error: '找不到项目。' })
|
||||
const verdict = String(body.verdict ?? '')
|
||||
if (verdict !== 'done' && verdict !== 'not-done') return send(res, 400, { ok: false, error: 'verdict 必须是 done 或 not-done。' })
|
||||
const result = await store.resolveDispatch(String(body.id ?? ''), verdict, 'user')
|
||||
if (!result) return send(res, 404, { ok: false, error: '找不到派发记录。' })
|
||||
if (!result.changed) return send(res, 409, { ok: false, error: `当前状态 ${result.record.status},不需要核实。` })
|
||||
await store.addEvent({ kind: 'reconcile', projectId: project.id, summary: `${body.id} → ${verdict}`, action: result.record.action })
|
||||
send(res, 200, { ok: true, status: result.record.status })
|
||||
} catch (error) {
|
||||
send(res, error.statusCode ?? 500, { error: String(error?.message ?? error) })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,68 @@
|
|||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
||||
import { dirname } from 'node:path'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { ROLE_IDS } from './roles.js'
|
||||
|
||||
const VERSION = 2
|
||||
const VERSION = 3
|
||||
export const REVIEW_LIMIT = 400
|
||||
export const DISPATCH_LIMIT = 600
|
||||
export const REWORK_LIMIT = 200
|
||||
export const EVENT_LIMIT = 300
|
||||
export const ARTIFACT_LIMIT = 800
|
||||
|
||||
export class SanshengStoreError extends Error {
|
||||
constructor(code, message) {
|
||||
super(message)
|
||||
this.name = 'SanshengStoreError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyState() {
|
||||
return { version: VERSION, projects: {}, reviews: [], dispatches: [], reworks: [], events: [] }
|
||||
return {
|
||||
version: VERSION,
|
||||
seq: 0,
|
||||
projects: {},
|
||||
reviews: [],
|
||||
dispatches: [],
|
||||
reworks: [],
|
||||
artifacts: {},
|
||||
leases: {},
|
||||
events: [],
|
||||
}
|
||||
}
|
||||
|
||||
function isObject(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizeProject(project) {
|
||||
if (!isObject(project)) return undefined
|
||||
return {
|
||||
schemaVersion: VERSION,
|
||||
submissionSeq: 0,
|
||||
delivery: { include: [], exclude: [] },
|
||||
...project,
|
||||
models: isObject(project.models) ? project.models : {},
|
||||
bots: isObject(project.bots) ? project.bots : {},
|
||||
}
|
||||
}
|
||||
|
||||
function normalize(raw) {
|
||||
const state = raw !== null && typeof raw === 'object' ? raw : {}
|
||||
const state = isObject(raw) ? raw : {}
|
||||
const projects = {}
|
||||
for (const [id, project] of Object.entries(isObject(state.projects) ? state.projects : {})) {
|
||||
const next = normalizeProject(project)
|
||||
if (next) projects[id] = next
|
||||
}
|
||||
return {
|
||||
version: VERSION,
|
||||
projects: state.projects !== null && typeof state.projects === 'object' ? state.projects : {},
|
||||
seq: Number.isFinite(state.seq) ? state.seq : 0,
|
||||
projects,
|
||||
reviews: Array.isArray(state.reviews) ? state.reviews : [],
|
||||
dispatches: Array.isArray(state.dispatches) ? state.dispatches : [],
|
||||
reworks: Array.isArray(state.reworks) ? state.reworks : [],
|
||||
artifacts: isObject(state.artifacts) ? state.artifacts : {},
|
||||
leases: isObject(state.leases) ? state.leases : {},
|
||||
events: Array.isArray(state.events) ? state.events : [],
|
||||
}
|
||||
}
|
||||
|
|
@ -40,72 +83,168 @@ async function writeJsonAtomic(file, value) {
|
|||
await rename(tmp, file)
|
||||
}
|
||||
|
||||
function registryOf(state) {
|
||||
const rooms = {}
|
||||
const bots = {}
|
||||
for (const [projectId, project] of Object.entries(state.projects ?? {})) {
|
||||
if (project.roomId) rooms[project.roomId] = projectId
|
||||
for (const role of ROLE_IDS) {
|
||||
const botId = project.bots?.[role]
|
||||
if (botId) bots[botId] = projectId
|
||||
}
|
||||
}
|
||||
return { version: 1, rooms, bots, updatedAt: Date.now() }
|
||||
}
|
||||
|
||||
function clone(value) {
|
||||
return structuredClone(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* 三省六部的补充记录:项目绑定(ProjectBinding)、审查记录(ReviewRecord)、
|
||||
* 派发记录(DispatchRecord)、返工记录(ReworkRecord)与审计事件。
|
||||
* 派发记录(DispatchRecord)、成果快照(ArtifactSnapshot)、写租约(WriteLease)与审计事件。
|
||||
* 原生 group_goal 仍是阶段进度的唯一权威;这里只存它没有的东西。
|
||||
* 写入串行化,内存状态先更新再落盘,同步的 tools.guard 立即可见。
|
||||
*
|
||||
* 写入串行化。每次事务先克隆内存状态,落盘失败时回滚内存,避免"内存成功、磁盘失败"。
|
||||
* 另写一份只含 room/bot → project 的 registry 提示文件:主状态损坏时仍能识别受治理群并拒绝写操作。
|
||||
*/
|
||||
export class SanshengStore {
|
||||
#file
|
||||
#registryFile
|
||||
#state
|
||||
#registry
|
||||
#ready
|
||||
#queue = Promise.resolve()
|
||||
#health
|
||||
|
||||
constructor(file) {
|
||||
this.#file = file
|
||||
this.#registryFile = join(dirname(file), 'registry.json')
|
||||
this.#state = emptyState()
|
||||
this.#registry = { version: 1, rooms: {}, bots: {}, updatedAt: 0 }
|
||||
this.#ready = undefined
|
||||
this.#health = { status: 'missing', path: file, error: null }
|
||||
}
|
||||
|
||||
get file() {
|
||||
return this.#file
|
||||
}
|
||||
|
||||
get registryFile() {
|
||||
return this.#registryFile
|
||||
}
|
||||
|
||||
async load() {
|
||||
this.#ready ??= readJsonFile(this.#file).then(raw => {
|
||||
this.#state = normalize(raw)
|
||||
this.#ready ??= (async () => {
|
||||
let projectError
|
||||
try {
|
||||
const raw = await readJsonFile(this.#file)
|
||||
if (raw === undefined) {
|
||||
this.#state = emptyState()
|
||||
this.#health = { status: 'missing', path: this.#file, error: null }
|
||||
} else {
|
||||
this.#state = normalize(raw)
|
||||
this.#health = { status: 'ok', path: this.#file, error: null }
|
||||
}
|
||||
} catch (error) {
|
||||
projectError = error
|
||||
this.#state = emptyState()
|
||||
this.#health = { status: 'broken', path: this.#file, error: String(error?.message ?? error) }
|
||||
}
|
||||
try {
|
||||
const raw = await readJsonFile(this.#registryFile)
|
||||
if (isObject(raw)) {
|
||||
this.#registry = {
|
||||
version: 1,
|
||||
rooms: isObject(raw.rooms) ? raw.rooms : {},
|
||||
bots: isObject(raw.bots) ? raw.bots : {},
|
||||
updatedAt: raw.updatedAt ?? 0,
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// registry 只是提示文件;读不了时按无提示处理,不影响主状态。
|
||||
}
|
||||
if (this.#health.status === 'ok') await this.#writeRegistry().catch(() => {})
|
||||
if (projectError) throw projectError
|
||||
return this.#state
|
||||
})
|
||||
})()
|
||||
return this.#ready
|
||||
}
|
||||
|
||||
health() {
|
||||
return { ...this.#health, registry: this.#registryFile }
|
||||
}
|
||||
|
||||
/** 同步快照;guard 只能同步读取。 */
|
||||
peek() {
|
||||
return this.#state
|
||||
}
|
||||
|
||||
registryPeek() {
|
||||
return this.#registry
|
||||
}
|
||||
|
||||
async #writeRegistry() {
|
||||
await writeJsonAtomic(this.#registryFile, registryOf(this.#state))
|
||||
this.#registry = registryOf(this.#state)
|
||||
}
|
||||
|
||||
async transact(mutate) {
|
||||
const run = this.#queue.then(async () => {
|
||||
await this.load()
|
||||
const result = await mutate(this.#state)
|
||||
if (this.#state.reviews.length > REVIEW_LIMIT) {
|
||||
this.#state.reviews = this.#state.reviews.slice(-REVIEW_LIMIT)
|
||||
const before = clone(this.#state)
|
||||
try {
|
||||
const result = await mutate(this.#state)
|
||||
if (this.#state.reviews.length > REVIEW_LIMIT) {
|
||||
this.#state.reviews = this.#state.reviews.slice(-REVIEW_LIMIT)
|
||||
}
|
||||
if (this.#state.dispatches.length > DISPATCH_LIMIT) {
|
||||
this.#state.dispatches = this.#state.dispatches.slice(-DISPATCH_LIMIT)
|
||||
}
|
||||
if (this.#state.reworks.length > REWORK_LIMIT) {
|
||||
this.#state.reworks = this.#state.reworks.slice(-REWORK_LIMIT)
|
||||
}
|
||||
if (this.#state.events.length > EVENT_LIMIT) {
|
||||
this.#state.events = this.#state.events.slice(-EVENT_LIMIT)
|
||||
}
|
||||
const artifactIds = Object.keys(this.#state.artifacts)
|
||||
if (artifactIds.length > ARTIFACT_LIMIT) {
|
||||
const keep = new Set(artifactIds.sort((a, b) => (this.#state.artifacts[a].createdAt ?? 0) - (this.#state.artifacts[b].createdAt ?? 0)).slice(-ARTIFACT_LIMIT))
|
||||
for (const id of artifactIds) if (!keep.has(id)) delete this.#state.artifacts[id]
|
||||
}
|
||||
await writeJsonAtomic(this.#file, this.#state)
|
||||
try {
|
||||
await this.#writeRegistry()
|
||||
} catch {
|
||||
// registry 失败不改变业务事务结果;下次 load 会重建。
|
||||
}
|
||||
this.#health = { status: 'ok', path: this.#file, error: null }
|
||||
return result
|
||||
} catch (error) {
|
||||
this.#state = before
|
||||
throw error
|
||||
}
|
||||
if (this.#state.dispatches.length > DISPATCH_LIMIT) {
|
||||
this.#state.dispatches = this.#state.dispatches.slice(-DISPATCH_LIMIT)
|
||||
}
|
||||
if (this.#state.reworks.length > REWORK_LIMIT) {
|
||||
this.#state.reworks = this.#state.reworks.slice(-REWORK_LIMIT)
|
||||
}
|
||||
if (this.#state.events.length > EVENT_LIMIT) {
|
||||
this.#state.events = this.#state.events.slice(-EVENT_LIMIT)
|
||||
}
|
||||
await writeJsonAtomic(this.#file, this.#state)
|
||||
return result
|
||||
})
|
||||
this.#queue = run.then(() => undefined, () => undefined)
|
||||
return run
|
||||
}
|
||||
|
||||
nextSeq() {
|
||||
return this.#state.seq + 1
|
||||
}
|
||||
|
||||
projectByRoom(roomId) {
|
||||
if (!roomId) return undefined
|
||||
return Object.values(this.#state.projects).find(project => project.roomId === roomId)
|
||||
}
|
||||
|
||||
projectsByBot(botId) {
|
||||
if (!botId) return []
|
||||
return Object.values(this.#state.projects).filter(project => ROLE_IDS.some(role => project.bots?.[role] === botId))
|
||||
}
|
||||
|
||||
projectByBot(botId) {
|
||||
if (!botId) return undefined
|
||||
return Object.values(this.#state.projects).find(project => ROLE_IDS.some(role => project.bots?.[role] === botId))
|
||||
return this.projectsByBot(botId)[0]
|
||||
}
|
||||
|
||||
projectById(id) {
|
||||
|
|
@ -121,11 +260,64 @@ export class SanshengStore {
|
|||
?? projects.find(project => project.name?.toLocaleLowerCase() === key.toLocaleLowerCase())
|
||||
}
|
||||
|
||||
/** 主状态读不了时,registry 仍能说明某群/某 Bot 属于受治理项目。 */
|
||||
registryProjectForRoom(roomId) {
|
||||
return roomId ? this.#registry.rooms?.[roomId] : undefined
|
||||
}
|
||||
|
||||
registryProjectForBot(botId) {
|
||||
return botId ? this.#registry.bots?.[botId] : undefined
|
||||
}
|
||||
|
||||
async #validateProject(project) {
|
||||
if (!isObject(project) || typeof project.id !== 'string' || project.id === '') {
|
||||
throw new SanshengStoreError('invalid-project', '项目绑定缺少 id。')
|
||||
}
|
||||
const bots = ROLE_IDS.map(role => project.bots?.[role]).filter(Boolean)
|
||||
if (new Set(bots).size !== bots.length) {
|
||||
throw new SanshengStoreError('roles-duplicated', '丞相/尚书/工部必须是三个不同的 Bot。')
|
||||
}
|
||||
for (const other of Object.values(this.#state.projects)) {
|
||||
if (other.id === project.id) continue
|
||||
if (project.roomId && other.roomId === project.roomId) {
|
||||
throw new SanshengStoreError('room-taken', `群 ${project.roomId} 已绑定项目「${other.name}」。`)
|
||||
}
|
||||
for (const role of ROLE_IDS) {
|
||||
const botId = project.bots?.[role]
|
||||
if (botId && ROLE_IDS.some(otherRole => other.bots?.[otherRole] === botId)) {
|
||||
throw new SanshengStoreError('bot-taken', `Bot ${botId} 已属于项目「${other.name}」,一个 Bot 只能属于一个项目。`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async saveProject(project) {
|
||||
return this.transact(state => {
|
||||
return this.transact(async state => {
|
||||
await this.#validateProject(project)
|
||||
const previous = state.projects[project.id] ?? {}
|
||||
state.projects[project.id] = { ...previous, ...project, updatedAt: Date.now() }
|
||||
return state.projects[project.id]
|
||||
const next = {
|
||||
schemaVersion: VERSION,
|
||||
submissionSeq: 0,
|
||||
delivery: { include: [], exclude: [] },
|
||||
...previous,
|
||||
...project,
|
||||
models: { ...(previous.models ?? {}), ...(project.models ?? {}) },
|
||||
bots: { ...(previous.bots ?? {}), ...(project.bots ?? {}) },
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
state.projects[project.id] = next
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
async updateProject(id, patch) {
|
||||
return this.transact(async state => {
|
||||
const project = state.projects[id]
|
||||
if (!project) throw new SanshengStoreError('not-found', `项目 ${id} 不存在。`)
|
||||
const next = { ...project, ...patch, updatedAt: Date.now() }
|
||||
await this.#validateProject(next)
|
||||
state.projects[id] = next
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -133,6 +325,7 @@ export class SanshengStore {
|
|||
return this.transact(state => {
|
||||
const existed = state.projects[id] !== undefined
|
||||
delete state.projects[id]
|
||||
delete state.leases[id]
|
||||
return existed
|
||||
})
|
||||
}
|
||||
|
|
@ -140,26 +333,92 @@ export class SanshengStore {
|
|||
/** 相同 eventKey 的审查只记一次(重试/重复事件幂等)。 */
|
||||
async addReview(review) {
|
||||
return this.transact(state => {
|
||||
const existing = state.reviews.find(item => item.eventKey === review.eventKey)
|
||||
const existing = review.eventKey === undefined
|
||||
? undefined
|
||||
: state.reviews.find(item => item.eventKey === review.eventKey)
|
||||
if (existing) return { review: existing, duplicate: true }
|
||||
state.reviews.push(review)
|
||||
return { review, duplicate: false }
|
||||
state.seq += 1
|
||||
const record = { ...review, seq: review.seq ?? state.seq }
|
||||
state.reviews.push(record)
|
||||
return { review: record, duplicate: false }
|
||||
})
|
||||
}
|
||||
|
||||
reviewsFor(match = {}) {
|
||||
return this.#state.reviews
|
||||
.filter(item => Object.entries(match).every(([key, value]) => item[key] === value))
|
||||
.sort((a, b) => (b.at ?? 0) - (a.at ?? 0))
|
||||
.sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0))
|
||||
}
|
||||
|
||||
/** 最新判决:先限定审查对象与合法审查身份,再取 seq/at 最大的一条。 */
|
||||
latestReviewFor({ projectId, goalId, kind, stageIndex, reviewerRole } = {}) {
|
||||
const matches = this.#state.reviews.filter(review => {
|
||||
if (projectId !== undefined && review.projectId !== projectId) return false
|
||||
if (goalId !== undefined && review.goalId !== goalId) return false
|
||||
if (kind !== undefined && review.kind !== kind) return false
|
||||
if (stageIndex !== undefined && (review.stageIndex ?? null) !== (stageIndex ?? null)) return false
|
||||
if (reviewerRole !== undefined && review.reviewerRole !== reviewerRole) return false
|
||||
return true
|
||||
})
|
||||
if (matches.length === 0) return undefined
|
||||
return matches.sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0) || (b.at ?? 0) - (a.at ?? 0))[0]
|
||||
}
|
||||
|
||||
/** 抓取成果后作为一次"提交代次"落库;旧审查因代次推进自动失效。 */
|
||||
async commitArtifact(projectId, snapshot) {
|
||||
return this.transact(state => {
|
||||
const project = state.projects[projectId]
|
||||
if (!project) throw new SanshengStoreError('not-found', `项目 ${projectId} 不存在。`)
|
||||
state.seq += 1
|
||||
const submissionSeq = (project.submissionSeq ?? 0) + 1
|
||||
project.submissionSeq = submissionSeq
|
||||
const record = { ...snapshot, id: snapshot.id, submissionSeq, seq: state.seq }
|
||||
state.artifacts[record.id] = record
|
||||
return { snapshot: record, submissionSeq }
|
||||
})
|
||||
}
|
||||
|
||||
artifactById(id) {
|
||||
return id ? this.#state.artifacts[id] : undefined
|
||||
}
|
||||
|
||||
artifactsFor(projectId, limit = 10) {
|
||||
return Object.values(this.#state.artifacts)
|
||||
.filter(item => projectId === undefined || item.projectId === projectId)
|
||||
.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0))
|
||||
.slice(0, limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 派发意图:先落盘再调用原生工具。进程中途消失时它停在 intent,
|
||||
* 派发意图:先落盘再调用原生工具。进程中途消失时它停在 prepared/in_flight,
|
||||
* 下次启动对账会把它标成 unknown(待核实),而不是假装成功或盲目重发。
|
||||
*/
|
||||
async beginDispatch(record) {
|
||||
return this.transact(state => {
|
||||
state.dispatches.push({ ...record, status: 'intent', at: record.at ?? Date.now() })
|
||||
if (record.requestId) {
|
||||
const existing = state.dispatches.find(item => item.requestId === record.requestId)
|
||||
if (existing) {
|
||||
if (existing.payloadDigest !== record.payloadDigest) {
|
||||
throw new SanshengStoreError('payload-conflict', `requestId ${record.requestId} 已用于另一份 payload,拒绝重复投递。`)
|
||||
}
|
||||
return { record: existing, replay: true }
|
||||
}
|
||||
}
|
||||
state.seq += 1
|
||||
const entry = { ...record, status: 'prepared', at: record.at ?? Date.now(), seq: state.seq }
|
||||
state.dispatches.push(entry)
|
||||
return { record: entry, replay: false }
|
||||
})
|
||||
}
|
||||
|
||||
async markDispatchInFlight(id) {
|
||||
return this.transact(state => {
|
||||
const record = state.dispatches.find(item => item.id === id)
|
||||
if (!record) return undefined
|
||||
if (record.status === 'prepared') {
|
||||
record.status = 'in_flight'
|
||||
record.sentAt = Date.now()
|
||||
}
|
||||
return record
|
||||
})
|
||||
}
|
||||
|
|
@ -173,12 +432,12 @@ export class SanshengStore {
|
|||
})
|
||||
}
|
||||
|
||||
/** 重启对账:仍在 intent 的派发视为「结果未知」,保留待人工/尚书核实。 */
|
||||
/** 重启对账:仍停在 prepared/in_flight 的派发视为「结果未知」,保留待人工/尚书核实。 */
|
||||
async reconcileDispatches(bootId) {
|
||||
return this.transact(state => {
|
||||
let marked = 0
|
||||
for (const record of state.dispatches) {
|
||||
if (record.status !== 'intent') continue
|
||||
if (record.status !== 'prepared' && record.status !== 'in_flight' && record.status !== 'intent') continue
|
||||
record.status = 'unknown'
|
||||
record.note = '宿主在派发途中退出;结果未知,需核实后再决定是否重发。'
|
||||
record.reconciledBy = bootId
|
||||
|
|
@ -195,7 +454,7 @@ export class SanshengStore {
|
|||
const record = state.dispatches.find(item => item.id === id)
|
||||
if (!record) return undefined
|
||||
if (record.status !== 'unknown') return { record, changed: false }
|
||||
record.status = verdict === 'done' ? 'confirmed' : 'failed'
|
||||
record.status = verdict === 'done' ? 'confirmed' : 'rejected'
|
||||
record.resolvedBy = by
|
||||
record.resolvedAt = Date.now()
|
||||
record.note = verdict === 'done' ? '核实:原生操作已执行。' : '核实:原生操作没有执行。'
|
||||
|
|
@ -215,7 +474,8 @@ export class SanshengStore {
|
|||
|
||||
async addEvent(entry) {
|
||||
return this.transact(state => {
|
||||
state.events.push({ ...entry, at: entry.at ?? Date.now() })
|
||||
state.seq += 1
|
||||
state.events.push({ ...entry, seq: state.seq, at: entry.at ?? Date.now() })
|
||||
return entry
|
||||
})
|
||||
}
|
||||
|
|
@ -238,4 +498,36 @@ export class SanshengStore {
|
|||
.slice(-limit)
|
||||
.reverse()
|
||||
}
|
||||
|
||||
/** 每项目最多一个活动写任务:租约由服务端持有、过期可回收。 */
|
||||
async acquireLease(projectId, { holder, taskId = null, ttlMs = 30 * 60 * 1000 } = {}) {
|
||||
return this.transact(state => {
|
||||
const project = state.projects[projectId]
|
||||
if (!project) throw new SanshengStoreError('not-found', `项目 ${projectId} 不存在。`)
|
||||
const now = Date.now()
|
||||
const current = state.leases[projectId]
|
||||
if (current && current.expiresAt > now && current.holder !== holder) {
|
||||
return { ok: false, lease: current, reason: `项目正在被 ${current.holder} 写入(任务 ${current.taskId ?? '未命名'}),请等它释放。` }
|
||||
}
|
||||
const lease = { projectId, holder, taskId, acquiredAt: now, expiresAt: now + ttlMs, renewedAt: now }
|
||||
state.leases[projectId] = lease
|
||||
return { ok: true, lease }
|
||||
})
|
||||
}
|
||||
|
||||
async releaseLease(projectId, holder) {
|
||||
return this.transact(state => {
|
||||
const current = state.leases[projectId]
|
||||
if (!current || current.holder !== holder) return { ok: false, reason: '租约不存在或不属于该持有者。' }
|
||||
delete state.leases[projectId]
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
|
||||
leaseOf(projectId) {
|
||||
const lease = this.#state.leases?.[projectId]
|
||||
if (!lease) return undefined
|
||||
if (lease.expiresAt <= Date.now()) return undefined
|
||||
return lease
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,20 @@
|
|||
import { ROLE_LABEL } from './roles.js'
|
||||
|
||||
export const ROOM_NOTICE = '三省六部规则:丞相定目标并做最终验收;尚书是群管理员,唯一用 group_goal 起草、派工、通过阶段与完成目标的人;工部只按工单执行并回报。阶段通过前先记录尚书审查;目标完成前先记录丞相验收。'
|
||||
|
||||
export function clampInt(value, fallback, min, max) {
|
||||
const number = Number(value)
|
||||
if (!Number.isInteger(number)) return fallback
|
||||
return Math.min(max, Math.max(min, number))
|
||||
}
|
||||
|
||||
export function instructionsFor(role, project, groupName) {
|
||||
const common = `你属于「${project}」项目,项目群是「${groupName}」。三省六部分工:丞相定目标与最终验收,尚书调度阶段与工单,工部执行并回报。`
|
||||
if (role === 'lead') {
|
||||
return `${common}\n你是丞相,负责把用户需求变成明确目标、验收标准与约束,并在最后验收整体交付。\n- 目标由尚书用 group_goal 起草和推进;你不要直接改目标。\n- 每个阶段由尚书核查通过;全部阶段完成后,你核对整体成果与用户要求,成功时用 sansheng_review action=goal_pass 记录验收,不通过时用 action=goal_reject 写明问题。\n- 验收看证据(改动、测试输出、结果),不走过场,也不替尚书做阶段审查。`
|
||||
}
|
||||
if (role === 'shangshu') {
|
||||
return `${common}\n你是尚书,项目群管理员,也是唯一操作目标的人。\n- 用 group_goal 起草/启动/修订目标,按阶段把工单派给工部(派工用 @工部名 写进群里),跟踪进度。\n- 每个阶段结束后亲自核查证据:通过前先 sansheng_review action=stage_pass(带 evidence),再 group_goal pass;不通过就 action=stage_reject 记账后 group_goal rework。\n- 返工最多 3 轮、按整个目标累计;预算用尽时停下来和用户确认,改写目标用 revise 或 stop。\n- 全部阶段通过后交给丞相验收;丞相记录 goal_pass 之后,你才 group_goal complete。不要替丞相验收。`
|
||||
}
|
||||
return `${common}\n你是工部,负责执行与回报。\n- 只做工单里的任务,按该阶段的验收标准交付;交付时给出证据:改了哪些文件、跑了什么测试、结果如何。\n- 在项目群里 @尚书 回报进度和阻塞;不修改目标,不做阶段/目标验收。\n- 遇到需求不清或范围变化,交回尚书与丞相对齐,不自行扩大范围。`
|
||||
}
|
||||
|
|
@ -1,17 +1,17 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { goalDigest, sha256, stageDigest } from './digest.js'
|
||||
import { captureArtifactSnapshot, summarizeSnapshot } from './artifact.js'
|
||||
import { artifactDigestOf, reviewSubjectDigest, sha256 } from './digest.js'
|
||||
import { budgetOf } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import { bindProject, provisionProject, updateProjectConfig } from './provision.js'
|
||||
import { describeDispatch } from './records.js'
|
||||
import { ROLE_COLOR, ROLE_IDS, ROLE_LABEL } from './roles.js'
|
||||
import { ROLE_IDS, ROLE_LABEL } from './roles.js'
|
||||
|
||||
const TEXT_OUTPUT = {
|
||||
schema: { type: 'string' },
|
||||
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
||||
}
|
||||
|
||||
const ROOM_NOTICE = '三省六部规则:丞相定目标并做最终验收;尚书是群管理员,唯一用 group_goal 起草、派工、通过阶段与完成目标的人;工部只按工单执行并回报。阶段通过前先记录尚书审查;目标完成前先记录丞相验收。'
|
||||
|
||||
function registerTextTool(ctx, name, description, parameters, handler) {
|
||||
return ctx.tools.register({
|
||||
name,
|
||||
|
|
@ -20,7 +20,9 @@ function registerTextTool(ctx, name, description, parameters, handler) {
|
|||
output: TEXT_OUTPUT,
|
||||
async execute(args, exec) {
|
||||
try {
|
||||
return await handler(args ?? {}, exec)
|
||||
const result = await handler(args ?? {}, exec)
|
||||
if (result !== null && typeof result === 'object' && typeof result.text === 'string') return result.text
|
||||
return result
|
||||
} catch (error) {
|
||||
return `三省六部:${error?.message ?? error}`
|
||||
}
|
||||
|
|
@ -28,28 +30,11 @@ function registerTextTool(ctx, name, description, parameters, handler) {
|
|||
})
|
||||
}
|
||||
|
||||
function clampInt(value, fallback, min, max) {
|
||||
const number = Number(value)
|
||||
if (!Number.isInteger(number)) return fallback
|
||||
return Math.min(max, Math.max(min, number))
|
||||
}
|
||||
|
||||
function shortId(id) {
|
||||
const text = String(id ?? '')
|
||||
return text.length <= 14 ? text : `…${text.slice(-12)}`
|
||||
}
|
||||
|
||||
function instructionsFor(role, project, groupName) {
|
||||
const common = `你属于「${project}」项目,项目群是「${groupName}」。三省六部分工:丞相定目标与最终验收,尚书调度阶段与工单,工部执行并回报。`
|
||||
if (role === 'lead') {
|
||||
return `${common}\n你是丞相,负责把用户需求变成明确目标、验收标准与约束,并在最后验收整体交付。\n- 目标由尚书用 group_goal 起草和推进;你不要直接改目标。\n- 每个阶段由尚书核查通过;全部阶段完成后,你核对整体成果与用户要求,成功时用 sansheng_review action=goal_pass 记录验收,不通过时用 action=goal_reject 写明问题。\n- 验收看证据(改动、测试输出、结果),不走过场,也不替尚书做阶段审查。`
|
||||
}
|
||||
if (role === 'shangshu') {
|
||||
return `${common}\n你是尚书,项目群管理员,也是唯一操作目标的人。\n- 用 group_goal 起草/启动/修订目标,按阶段把工单派给工部(派工用 @工部名 写进群里),跟踪进度。\n- 每个阶段结束后亲自核查证据:通过前先 sansheng_review action=stage_pass(带 evidence),再 group_goal pass;不通过就 action=stage_reject 记账后 group_goal rework。\n- 返工最多 3 轮、按整个目标累计;预算用尽时停下来和用户确认,改写目标用 revise 或 stop。\n- 全部阶段通过后交给丞相验收;丞相记录 goal_pass 之后,你才 group_goal complete。不要替丞相验收。`
|
||||
}
|
||||
return `${common}\n你是工部,负责执行与回报。\n- 只做工单里的任务,按该阶段的验收标准交付;交付时给出证据:改了哪些文件、跑了什么测试、结果如何。\n- 在项目群里 @尚书 回报进度和阻塞;不修改目标,不做阶段/目标验收。\n- 遇到需求不清或范围变化,交回尚书与丞相对齐,不自行扩大范围。`
|
||||
}
|
||||
|
||||
function projectBots(dsbot, project) {
|
||||
return ROLE_IDS.map(role => ({ role, id: project.bots?.[role], bot: dsbot.botOf(project.bots?.[role]) }))
|
||||
}
|
||||
|
|
@ -59,10 +44,11 @@ function projectLines(dsbot, store, project) {
|
|||
const goal = room?.goal
|
||||
const bots = projectBots(dsbot, project).map(item => `${ROLE_LABEL[item.role]}=${item.bot?.name ?? item.id ?? '?'}`).join(',')
|
||||
const lines = [
|
||||
`项目「${project.name}」${project.id}`,
|
||||
`项目「${project.name}」${project.id}${project.workspaceId ? ` · 工作区 ${shortId(project.workspaceId)}` : ''}`,
|
||||
` 群:${room?.name ?? project.roomId}(${shortId(project.roomId)}) ${room ? `管理员=${dsbot.botOf(room.admin)?.name ?? '无'}` : '群已不存在'}`,
|
||||
` Bot:${bots}`,
|
||||
` 模型:${ROLE_IDS.map(role => `${ROLE_LABEL[role]}=${project.models?.[role] ?? dsbot.botOf(project.bots?.[role])?.model ?? '默认'}`).join(',')} 返工预算:${project.maxReworks ?? 3}`,
|
||||
` 工作目录:${project.workDir ?? '未设置'} 成果代次:${project.submissionSeq ?? 0}`,
|
||||
]
|
||||
const unknown = store.unknownDispatches(project.id)
|
||||
const recent = store.dispatchesFor(project.id, 3)
|
||||
|
|
@ -73,6 +59,13 @@ function projectLines(dsbot, store, project) {
|
|||
if (reworks.length > 0) {
|
||||
lines.push(` 返工记录:${reworks.map(item => `阶段${item.stageIndex} ${item.reason ?? ''}(${item.budgetUsed}/${item.budgetMax})`).join(';')}`)
|
||||
}
|
||||
const lease = typeof store.leaseOf === 'function' ? store.leaseOf(project.id) : undefined
|
||||
if (lease) lines.push(` 写租约:${lease.holder}(任务 ${lease.taskId ?? '未命名'},${new Date(lease.expiresAt).toLocaleString('zh-CN')} 到期)`)
|
||||
const artifacts = typeof store.artifactsFor === 'function' ? store.artifactsFor(project.id, 1) : []
|
||||
if (artifacts.length > 0) {
|
||||
const summary = summarizeSnapshot(artifacts[0])
|
||||
lines.push(` 最近成果:${summary.kind} ${String(summary.digest).slice(0, 12)}… · ${summary.fileCount} 个文件 · 代次 ${artifacts[0].submissionSeq ?? '?'}`)
|
||||
}
|
||||
if (!goal) {
|
||||
lines.push(' 目标:还没有(尚书用 group_goal draft/start 起草)')
|
||||
return lines
|
||||
|
|
@ -84,166 +77,29 @@ function projectLines(dsbot, store, project) {
|
|||
return lines
|
||||
}
|
||||
|
||||
async function provision({ ctx, store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
if (actor.kind === 'bot') return '只有用户能创建项目;Bot 在现有项目群里工作。'
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
if (!rt || typeof rt.createBot !== 'function') {
|
||||
return '没有找到 DS-Bot 运行时(dsbot-runtime 服务)。请先安装并启用 ds-bot,再重启 DSH;并用带 ctx.provide 的基线补丁(见 docs/p0/README.md)。'
|
||||
}
|
||||
await rt.load()
|
||||
|
||||
const projectName = String(args.project ?? '').trim()
|
||||
if (projectName === '') return '请提供 project(项目名)。'
|
||||
if (projectName.length > 40) return '项目名最多 40 个字符。'
|
||||
const existing = Object.values(store.peek().projects).find(project => project.name === projectName)
|
||||
if (existing) return `项目「${projectName}」已经存在(${existing.id},群 ${existing.roomId})。用 sansheng_status 查看。`
|
||||
|
||||
const botNames = {
|
||||
lead: String(args.leadName ?? '丞相').trim(),
|
||||
shangshu: String(args.shangshuName ?? '尚书').trim(),
|
||||
gongbu: String(args.gongbuName ?? '工部').trim(),
|
||||
}
|
||||
for (const role of ROLE_IDS) {
|
||||
if (botNames[role] === '') return `缺少${ROLE_LABEL[role]}的名字。`
|
||||
if (botNames[role].length > 40) return `${ROLE_LABEL[role]}的名字最多 40 个字符。`
|
||||
}
|
||||
if (new Set(ROLE_IDS.map(role => botNames[role])).size !== 3) return '三个 Bot 的名字必须不同。'
|
||||
|
||||
const models = {}
|
||||
for (const role of ROLE_IDS) {
|
||||
const raw = args.models?.[role]
|
||||
if (raw === undefined || raw === null || String(raw).trim() === '') continue
|
||||
try {
|
||||
models[role] = await rt.resolveModel(String(raw).trim())
|
||||
} catch (error) {
|
||||
return `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}`
|
||||
/** 统一项目归属解析:Bot 只能操作自己的项目;用户必须显式给 project。 */
|
||||
function resolveProjectForCall({ store, actor, args, allowUserNoProject = false }) {
|
||||
if (actor?.kind === 'unknown') return { error: actor.reason ?? '无法确认调用者身份。' }
|
||||
if (actor?.kind === 'bot') {
|
||||
if (actor.projectConflict) return { error: `Bot「${actor.botName ?? actor.botId}」同时属于多个项目,请先清理绑定。` }
|
||||
if (!actor.project) return { error: '这个 Bot 不属于任何三省六部项目。' }
|
||||
if (args.project !== undefined && String(args.project).trim() !== '') {
|
||||
const named = store.resolveProject(args.project)
|
||||
if (!named) return { error: `找不到项目「${args.project}」。` }
|
||||
if (named.id !== actor.project.id) return { error: `项目冲突:当前 Bot 属于「${actor.project.name}」,显式指定的却是「${named.name}」;已拒绝,不会跨项目操作。` }
|
||||
}
|
||||
return { project: actor.project }
|
||||
}
|
||||
|
||||
const groupName = String(args.groupName ?? `${projectName} · 三省六部`).trim().slice(0, 40)
|
||||
const workDir = args.workDir === undefined || args.workDir === null || String(args.workDir).trim() === ''
|
||||
? undefined
|
||||
: String(args.workDir).trim()
|
||||
const maxReworks = clampInt(args.maxReworks, 3, 1, 10)
|
||||
|
||||
const created = []
|
||||
let room
|
||||
try {
|
||||
for (const role of ROLE_IDS) {
|
||||
const bot = await rt.createBot({
|
||||
name: botNames[role],
|
||||
role: ROLE_LABEL[role],
|
||||
instructions: instructionsFor(role, projectName, groupName),
|
||||
color: ROLE_COLOR[role],
|
||||
brief: `「${projectName}」项目的${ROLE_LABEL[role]}。`,
|
||||
model: models[role],
|
||||
...(workDir === undefined ? {} : { workDir }),
|
||||
})
|
||||
created.push(bot.id)
|
||||
}
|
||||
room = await rt.createRoom({
|
||||
members: created,
|
||||
name: groupName,
|
||||
admin: created[1],
|
||||
mode: 'admin',
|
||||
createdBy: null,
|
||||
notice: ROOM_NOTICE,
|
||||
})
|
||||
} catch (error) {
|
||||
for (const id of created) {
|
||||
try { await rt.deleteBot(id) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
return `创建失败:${error?.message ?? error}。已回滚新建的 Bot。`
|
||||
if (args.project !== undefined && String(args.project).trim() !== '') {
|
||||
const project = store.resolveProject(args.project)
|
||||
if (!project) return { error: `找不到项目「${args.project}」。` }
|
||||
return { project }
|
||||
}
|
||||
|
||||
const project = {
|
||||
id: `prj-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
name: projectName,
|
||||
workspaceId: args.workspaceId === undefined ? null : String(args.workspaceId),
|
||||
workDir: workDir ?? null,
|
||||
roomId: room.id,
|
||||
bots: { lead: created[0], shangshu: created[1], gongbu: created[2] },
|
||||
models,
|
||||
maxReworks,
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
try {
|
||||
await store.saveProject(project)
|
||||
} catch (error) {
|
||||
if (typeof rt.deleteRoom === 'function') {
|
||||
try { await rt.deleteRoom(room.id) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
for (const id of created) {
|
||||
try { await rt.deleteBot(id) } catch { /* 回滚尽力而为 */ }
|
||||
}
|
||||
return `保存项目绑定失败:${error?.message ?? error}。已回滚群与 Bot。`
|
||||
}
|
||||
|
||||
return [
|
||||
`已创建项目「${projectName}」${project.id}。`,
|
||||
`群「${room.name}」:管理员=尚书 ${botNames.shangshu}。`,
|
||||
`Bot:丞相 ${botNames.lead} / 尚书 ${botNames.shangshu} / 工部 ${botNames.gongbu}。`,
|
||||
`模型:${ROLE_IDS.map(role => `${ROLE_LABEL[role]}=${models[role] ?? 'DS Bot 默认'}`).join(',')}。`,
|
||||
`返工预算 ${maxReworks} 轮(按整个目标累计)。`,
|
||||
'下一步:在项目群发需求,让丞相对齐目标;尚书用 group_goal 起草/启动,并按阶段 @工部 派工。',
|
||||
].join('\n')
|
||||
if (allowUserNoProject) return { project: undefined }
|
||||
return { error: '请用 project 参数指定项目名或 id。' }
|
||||
}
|
||||
|
||||
async function bind({ store, dsbot, args }) {
|
||||
const roomRef = String(args.room ?? '').trim()
|
||||
if (roomRef === '') return '请提供 room(项目群名或 id)。'
|
||||
const state = dsbot.snapshot()
|
||||
const rooms = Object.values(state.rooms ?? {})
|
||||
const room = rooms.find(item => item.id === roomRef)
|
||||
?? rooms.find(item => item.name === roomRef)
|
||||
?? rooms.find(item => item.name?.toLocaleLowerCase() === roomRef.toLocaleLowerCase())
|
||||
if (!room) return `找不到群「${roomRef}」。确认群名,或先在 DS Bot 里建群。`
|
||||
const existing = store.projectByRoom(room.id)
|
||||
if (existing) return `群「${room.name}」已绑定项目「${existing.name}」(${existing.id})。`
|
||||
|
||||
const findBot = ref => {
|
||||
const key = String(ref ?? '').trim()
|
||||
if (key === '') return undefined
|
||||
return state.bots?.[key] ?? dsbot.botByName(key)
|
||||
}
|
||||
const bots = {}
|
||||
for (const role of ROLE_IDS) {
|
||||
let bot = findBot(args[role])
|
||||
if (!bot) {
|
||||
bot = Object.values(state.bots ?? {}).find(item =>
|
||||
(room.members ?? []).includes(item.id) && (item.role === ROLE_LABEL[role] || item.name === ROLE_LABEL[role]))
|
||||
}
|
||||
if (!bot) return `没找到${ROLE_LABEL[role]} Bot:请用 ${role} 参数给名字或 id,或先把它加入群。`
|
||||
if (!(room.members ?? []).includes(bot.id)) return `${ROLE_LABEL[role]}「${bot.name}」不在群「${room.name}」里。`
|
||||
bots[role] = bot.id
|
||||
}
|
||||
if (new Set(Object.values(bots)).size !== 3) return '丞相/尚书/工部必须是三个不同的 Bot。'
|
||||
if (room.admin !== bots.shangshu) {
|
||||
const admin = room.admin ? state.bots?.[room.admin]?.name ?? room.admin : '无'
|
||||
return `群管理员当前是 ${admin},必须是尚书。先在 DS Bot 的群设置里把管理员改成${ROLE_LABEL.shangshu},再绑定。`
|
||||
}
|
||||
|
||||
const project = {
|
||||
id: `prj-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
name: String(args.project ?? room.name).trim().slice(0, 40),
|
||||
workspaceId: args.workspaceId === undefined ? null : String(args.workspaceId),
|
||||
workDir: args.workDir === undefined || args.workDir === null ? null : String(args.workDir),
|
||||
roomId: room.id,
|
||||
bots,
|
||||
models: args.models ?? {},
|
||||
maxReworks: clampInt(args.maxReworks, 3, 1, 10),
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
await store.saveProject(project)
|
||||
return [
|
||||
`已把群「${room.name}」绑定为项目「${project.name}」(${project.id})。`,
|
||||
`丞相=${state.bots?.[bots.lead]?.name},尚书=${state.bots?.[bots.shangshu]?.name}(管理员),工部=${state.bots?.[bots.gongbu]?.name}。`,
|
||||
'从下一次 group_goal 起,角色、审查记录与返工预算开始生效。',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function status({ store, dsbot, args }) {
|
||||
function statusText({ store, dsbot, args }) {
|
||||
const projects = args.project === undefined || String(args.project).trim() === ''
|
||||
? Object.values(store.peek().projects)
|
||||
: [store.resolveProject(args.project)].filter(Boolean)
|
||||
|
|
@ -254,6 +110,8 @@ function status({ store, dsbot, args }) {
|
|||
: `找不到项目「${args.project}」。用 sansheng_status 不带参数列出全部。`
|
||||
}
|
||||
const blocks = projects.map(project => projectLines(dsbot, store, project).join('\n'))
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
if (health.status !== 'ok') blocks.push(`治理状态:${health.status}(${health.error ?? '状态文件不存在'})。受治理写操作会停止,请先恢复。`)
|
||||
const unknown = store.unknownDispatches(args.project === undefined ? undefined : projects[0]?.id)
|
||||
if (unknown.length > 0) {
|
||||
blocks.push(`有 ${unknown.length} 条派发待核实(宿主退出时没拿到回执):${unknown.slice(0, 5).map(item => item.id).join('、')}。用 sansheng_reconcile id=… verdict=done|not-done 核对。`)
|
||||
|
|
@ -261,11 +119,245 @@ function status({ store, dsbot, args }) {
|
|||
return blocks.join('\n\n')
|
||||
}
|
||||
|
||||
async function review({ store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession: exec.__isBotSession })
|
||||
const resolved = resolveProjectForCall({ store, actor, args })
|
||||
if (resolved.error) return resolved.error
|
||||
const project = resolved.project
|
||||
|
||||
const room = dsbot.roomOf(project.roomId)
|
||||
const goal = room?.goal
|
||||
if (!goal) return `项目「${project.name}」的目标还没起草,先让尚书用 group_goal draft/start。`
|
||||
|
||||
const action = String(args.action ?? '')
|
||||
const stageAction = action === 'stage_pass' || action === 'stage_reject'
|
||||
const goalAction = action === 'goal_pass' || action === 'goal_reject'
|
||||
if (!stageAction && !goalAction) return 'action 必须是 stage_pass / stage_reject / goal_pass / goal_reject。'
|
||||
|
||||
if (actor.kind === 'bot') {
|
||||
const needed = stageAction ? 'shangshu' : 'lead'
|
||||
if (actor.role !== needed) {
|
||||
return `${action} 只能由${ROLE_LABEL[needed]}记录;当前身份是${actor.role ? ROLE_LABEL[actor.role] : '非项目成员'}。`
|
||||
}
|
||||
} else if (actor.kind === 'unknown') {
|
||||
return actor.reason
|
||||
}
|
||||
|
||||
const evidence = String(args.evidence ?? '').trim()
|
||||
const reason = String(args.reason ?? '').trim()
|
||||
|
||||
if (stageAction) {
|
||||
if (goal.status !== 'active') return `目标当前是 ${goal.status},不能记录阶段审查。`
|
||||
const stageIndex = Number.isInteger(args.stage) ? args.stage : goal.current + 1
|
||||
if (stageIndex < 1 || stageIndex > (goal.stages?.length ?? 0)) return `阶段号 ${stageIndex} 超出范围(1-${goal.stages?.length ?? 0})。`
|
||||
if (stageIndex !== goal.current + 1) {
|
||||
const current = goal.stages?.[goal.current]
|
||||
return `只能审查当前阶段 ${goal.current + 1}${current ? `「${current.title}」` : ''};已通过的阶段不能补记审查。`
|
||||
}
|
||||
const stage = goal.stages[stageIndex - 1]
|
||||
if (action === 'stage_pass' && evidence === '') return '通过阶段必须写 evidence:测试输出、改动文件或检查结果。'
|
||||
if (action === 'stage_reject' && reason === '') return '驳回阶段必须写 reason:缺什么、怎么改。'
|
||||
const subject = reviewSubjectDigest('stage', goal, stageIndex)
|
||||
let artifact = null
|
||||
let submissionSeq = project.submissionSeq ?? 0
|
||||
if (project.workDir) {
|
||||
try {
|
||||
const snapshot = await captureArtifactSnapshot({ project, goal, stageIndex, scope: 'stage' })
|
||||
const committed = await store.commitArtifact(project.id, snapshot)
|
||||
artifact = committed.snapshot
|
||||
submissionSeq = committed.submissionSeq
|
||||
} catch (error) {
|
||||
return `无法生成成果快照:${error?.message ?? error}。审查未记录。`
|
||||
}
|
||||
}
|
||||
const record = {
|
||||
id: `rev-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'stage',
|
||||
stageIndex,
|
||||
stageTitle: stage.title,
|
||||
reviewSubjectDigest: subject,
|
||||
digest: subject,
|
||||
artifactSnapshotId: artifact?.id ?? null,
|
||||
artifactDigest: artifactDigestOf(artifact),
|
||||
submissionSeq,
|
||||
verdict: action === 'stage_pass' ? 'pass' : 'reject',
|
||||
reviewerRole: actor.kind === 'bot' ? 'shangshu' : 'user',
|
||||
reviewerBotId: actor.botId ?? null,
|
||||
reviewerSessionId: actor.sessionId ?? null,
|
||||
evidence: evidence === '' ? null : evidence,
|
||||
reason: reason === '' ? null : reason,
|
||||
at: Date.now(),
|
||||
}
|
||||
record.eventKey = sha256(JSON.stringify({
|
||||
projectId: record.projectId, goalId: record.goalId, goalRevision: record.goalRevision,
|
||||
kind: record.kind, stageIndex, subject, artifactDigest: record.artifactDigest,
|
||||
submissionSeq, verdict: record.verdict,
|
||||
reviewerRole: record.reviewerRole, reviewerBotId: record.reviewerBotId,
|
||||
}))
|
||||
const result = await store.addReview(record)
|
||||
if (result.duplicate) return `同样的阶段审查已记录(${result.review.id}),没有重复写入。`
|
||||
if (record.verdict === 'pass') {
|
||||
return `已记录尚书阶段审查 ${record.id}:阶段 ${stageIndex}「${stage.title}」通过,目标版本 ${goal.revision},成果代次 ${submissionSeq}${artifact ? `,快照 ${artifact.id}` : ''}。现在可以 group_goal pass(evidence 用同一份证据)。`
|
||||
}
|
||||
const budget = budgetOf(goal, project, store.peek().reworks)
|
||||
return `已记录尚书阶段审查 ${record.id}:阶段 ${stageIndex}「${stage.title}」驳回,目标版本 ${goal.revision},成果代次 ${submissionSeq}。可以 group_goal rework;返工将计为 ${budget.used + 1}/${budget.max}。`
|
||||
}
|
||||
|
||||
if (goal.status !== 'active') return `目标当前是 ${goal.status},不能做目标验收。`
|
||||
const stages = goal.stages ?? []
|
||||
if (stages.length === 0 || stages.some(stage => stage.status !== 'passed')) {
|
||||
const open = stages.findIndex(stage => stage.status !== 'passed')
|
||||
return `还有阶段没通过(第 ${open + 1} 阶段${stages[open]?.title ? `「${stages[open].title}」` : ''}),丞相不能做整体验收。`
|
||||
}
|
||||
if (action === 'goal_pass' && evidence === '') return '目标验收通过必须写 evidence:整体交付与验收标准的对照。'
|
||||
if (action === 'goal_reject' && reason === '') return '目标验收驳回必须写 reason:不满足哪条验收标准。'
|
||||
const subject = reviewSubjectDigest('goal', goal)
|
||||
let artifact = null
|
||||
let submissionSeq = project.submissionSeq ?? 0
|
||||
if (project.workDir) {
|
||||
try {
|
||||
const snapshot = await captureArtifactSnapshot({ project, goal, stageIndex: null, scope: 'goal' })
|
||||
const committed = await store.commitArtifact(project.id, snapshot)
|
||||
artifact = committed.snapshot
|
||||
submissionSeq = committed.submissionSeq
|
||||
} catch (error) {
|
||||
return `无法生成成果快照:${error?.message ?? error}。审查未记录。`
|
||||
}
|
||||
}
|
||||
const record = {
|
||||
id: `rev-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'goal',
|
||||
stageIndex: null,
|
||||
stageTitle: null,
|
||||
reviewSubjectDigest: subject,
|
||||
digest: subject,
|
||||
artifactSnapshotId: artifact?.id ?? null,
|
||||
artifactDigest: artifactDigestOf(artifact),
|
||||
submissionSeq,
|
||||
verdict: action === 'goal_pass' ? 'pass' : 'reject',
|
||||
reviewerRole: actor.kind === 'bot' ? 'lead' : 'user',
|
||||
reviewerBotId: actor.botId ?? null,
|
||||
reviewerSessionId: actor.sessionId ?? null,
|
||||
evidence: evidence === '' ? null : evidence,
|
||||
reason: reason === '' ? null : reason,
|
||||
at: Date.now(),
|
||||
}
|
||||
record.eventKey = sha256(JSON.stringify({
|
||||
projectId: record.projectId, goalId: record.goalId, goalRevision: record.goalRevision,
|
||||
kind: record.kind, stageIndex: null, subject, artifactDigest: record.artifactDigest,
|
||||
submissionSeq, verdict: record.verdict,
|
||||
reviewerRole: record.reviewerRole, reviewerBotId: record.reviewerBotId,
|
||||
}))
|
||||
const result = await store.addReview(record)
|
||||
if (result.duplicate) return `同样的目标验收已记录(${result.review.id}),没有重复写入。`
|
||||
return record.verdict === 'pass'
|
||||
? `已记录丞相目标验收 ${record.id}(目标版本 ${goal.revision},成果代次 ${submissionSeq}${artifact ? `,快照 ${artifact.id}` : ''})。尚书现在可以 group_goal complete。`
|
||||
: `已记录丞相目标验收驳回 ${record.id}(目标版本 ${goal.revision})。让尚书 revise 目标或继续返工后重新验收。`
|
||||
}
|
||||
|
||||
async function submit({ store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession: exec.__isBotSession })
|
||||
const resolved = resolveProjectForCall({ store, actor, args })
|
||||
if (resolved.error) return resolved.error
|
||||
const project = resolved.project
|
||||
if (!project.workDir) return `项目「${project.name}」没有设置工作目录,无法生成成果快照。先在 sansheng_provision/bind 时给 workDir,或用 sansheng_config 配置。`
|
||||
if (actor.kind === 'bot' && actor.role !== 'gongbu' && actor.role !== 'shangshu') {
|
||||
return '只有工部或尚书的项目 Bot 能提交成果;丞相只做验收。'
|
||||
}
|
||||
const holder = actor.botId ?? 'user'
|
||||
const lease = await store.acquireLease(project.id, { holder, taskId: args.task ?? null })
|
||||
if (!lease.ok) return `写入被拒绝:${lease.reason}`
|
||||
const room = dsbot.roomOf(project.roomId)
|
||||
const goal = room?.goal
|
||||
let snapshot
|
||||
try {
|
||||
snapshot = await captureArtifactSnapshot({
|
||||
project,
|
||||
goal,
|
||||
stageIndex: args.stage ?? null,
|
||||
scope: args.scope === 'goal' ? 'goal' : 'stage',
|
||||
})
|
||||
} catch (error) {
|
||||
return `无法生成成果快照:${error?.message ?? error}`
|
||||
}
|
||||
const committed = await store.commitArtifact(project.id, snapshot)
|
||||
const summary = summarizeSnapshot(committed.snapshot)
|
||||
return [
|
||||
`已提交成果快照 ${committed.snapshot.id}(代次 ${committed.submissionSeq})。`,
|
||||
`类型=${summary.kind},文件=${summary.fileCount},总量=${summary.totalBytes} 字节${summary.truncated ? '(已截断,超过上限)' : ''}。`,
|
||||
`摘要=${summary.digest}`,
|
||||
'后续 sansheng_review 会自动绑定本次提交;审查后如成果再变化,旧审批会失效。',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
async function config({ ctx, store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession: exec.__isBotSession })
|
||||
if (actor.kind === 'bot') return '模型/配置只能由用户修改;Bot 不能改项目配置。'
|
||||
const resolved = resolveProjectForCall({ store, actor, args })
|
||||
if (resolved.error) return resolved.error
|
||||
const result = await updateProjectConfig({ ctx, store, args: { ...args, projectId: resolved.project.id } })
|
||||
return result.text
|
||||
}
|
||||
|
||||
async function control({ ctx, store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession: exec.__isBotSession })
|
||||
if (actor.kind === 'bot') return '暂停/恢复/停止由用户在 UI 操作;Bot 用 group_goal pause/resume/stop 并按角色权限执行。'
|
||||
const resolved = resolveProjectForCall({ store, actor, args })
|
||||
if (resolved.error) return resolved.error
|
||||
const project = resolved.project
|
||||
const rt = ctx.get('dsbot-runtime', false)
|
||||
if (!rt || typeof rt.goalControl !== 'function') return 'DS-Bot 运行时没有 goalControl,无法执行目标控制。'
|
||||
const room = dsbot.roomOf(project.roomId)
|
||||
const goal = room?.goal
|
||||
if (!goal) return `项目「${project.name}」没有进行中的目标。`
|
||||
const action = String(args.action ?? '')
|
||||
const map = { pause: 'pause', resume: 'resume', stop: 'stop', cancel: 'stop' }
|
||||
const nativeAction = map[action]
|
||||
if (!nativeAction) return 'action 必须是 pause / resume / stop / cancel。'
|
||||
if (action === 'cancel' && !args.confirm) return '取消当前执行会同时停止目标工作;确认请传 confirm=true。'
|
||||
try {
|
||||
const result = await rt.goalControl(project.roomId, { goalId: goal.id, action: nativeAction, ...(action === 'cancel' ? { stopWork: true } : {}) })
|
||||
if (result?.error) return `原生控制失败:${result.error}`
|
||||
} catch (error) {
|
||||
return `原生控制失败:${error?.message ?? error}`
|
||||
}
|
||||
const status = action === 'pause' ? '已暂停(目标保留,可恢复)' : action === 'resume' ? '已恢复' : '已停止目标并请求停止当前执行'
|
||||
return `项目「${project.name}」:${status}。停止请求与已停止是两件事,稍后用 sansheng_status 核实原生状态。`
|
||||
}
|
||||
|
||||
async function lease({ store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession: exec.__isBotSession })
|
||||
const resolved = resolveProjectForCall({ store, actor, args })
|
||||
if (resolved.error) return resolved.error
|
||||
const project = resolved.project
|
||||
const action = String(args.action ?? 'status')
|
||||
const holder = actor.botId ?? 'user'
|
||||
if (action === 'acquire') {
|
||||
const result = await store.acquireLease(project.id, { holder, taskId: args.task ?? null, ttlMs: args.ttlMs ?? 30 * 60 * 1000 })
|
||||
if (!result.ok) return `写入租约被拒绝:${result.reason}`
|
||||
return `已取得「${project.name}」写租约:${holder},任务 ${args.task ?? '未命名'},到期 ${new Date(result.lease.expiresAt).toLocaleString('zh-CN')}。`
|
||||
}
|
||||
if (action === 'release') {
|
||||
const result = await store.releaseLease(project.id, holder)
|
||||
return result.ok ? `已释放「${project.name}」写租约。` : `释放失败:${result.reason}`
|
||||
}
|
||||
const current = store.leaseOf(project.id)
|
||||
return current
|
||||
? `「${project.name}」当前写租约:${current.holder}(任务 ${current.taskId ?? '未命名'},${new Date(current.expiresAt).toLocaleString('zh-CN')} 到期)。`
|
||||
: `「${project.name}」当前没有活动写租约。`
|
||||
}
|
||||
|
||||
async function reconcile({ store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
const project = args.project === undefined || String(args.project).trim() === ''
|
||||
? actor.project
|
||||
: store.resolveProject(args.project)
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession: exec.__isBotSession })
|
||||
const resolved = resolveProjectForCall({ store, actor, args, allowUserNoProject: true })
|
||||
if (resolved.error) return resolved.error
|
||||
const project = resolved.project
|
||||
const id = String(args.id ?? '').trim()
|
||||
if (id === '') {
|
||||
const list = store.unknownDispatches(project?.id)
|
||||
|
|
@ -294,117 +386,11 @@ async function reconcile({ store, dsbot, args, exec }) {
|
|||
await store.addEvent({ kind: 'reconcile', projectId: record.projectId, summary: `${id} → ${verdict}`, action: record.action })
|
||||
return verdict === 'done'
|
||||
? `已核实 ${id}:原生操作确实执行过,记录改为已确认。`
|
||||
: `已核实 ${id}:原生操作没有执行,记录改为未执行;需要时再重新发起。`
|
||||
: `已核实 ${id}:原生操作没有执行,记录改为被拒绝;需要时再重新发起。`
|
||||
}
|
||||
|
||||
async function review({ store, dsbot, args, exec }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id })
|
||||
let project = actor.project
|
||||
if (!project && args.project !== undefined) project = store.resolveProject(args.project)
|
||||
if (!project) return '找不到项目:请在项目群里调用,或用 project 参数指定。'
|
||||
|
||||
const room = dsbot.roomOf(project.roomId)
|
||||
const goal = room?.goal
|
||||
if (!goal) return `项目「${project.name}」的目标还没起草,先让尚书用 group_goal draft/start。`
|
||||
|
||||
const action = String(args.action ?? '')
|
||||
const stageAction = action === 'stage_pass' || action === 'stage_reject'
|
||||
const goalAction = action === 'goal_pass' || action === 'goal_reject'
|
||||
if (!stageAction && !goalAction) return 'action 必须是 stage_pass / stage_reject / goal_pass / goal_reject。'
|
||||
|
||||
if (actor.kind === 'bot') {
|
||||
const needed = stageAction ? 'shangshu' : 'lead'
|
||||
if (actor.role !== needed) {
|
||||
return `${action} 只能由${ROLE_LABEL[needed]}记录;当前身份是${actor.role ? ROLE_LABEL[actor.role] : '非项目成员'}。`
|
||||
}
|
||||
}
|
||||
|
||||
const evidence = String(args.evidence ?? '').trim()
|
||||
const reason = String(args.reason ?? '').trim()
|
||||
|
||||
if (stageAction) {
|
||||
if (goal.status !== 'active') return `目标当前是 ${goal.status},不能记录阶段审查。`
|
||||
const stageIndex = Number.isInteger(args.stage) ? args.stage : goal.current + 1
|
||||
if (stageIndex < 1 || stageIndex > (goal.stages?.length ?? 0)) return `阶段号 ${stageIndex} 超出范围(1-${goal.stages?.length ?? 0})。`
|
||||
if (stageIndex !== goal.current + 1) {
|
||||
const current = goal.stages?.[goal.current]
|
||||
return `只能审查当前阶段 ${goal.current + 1}${current ? `「${current.title}」` : ''};已通过的阶段不能补记审查。`
|
||||
}
|
||||
const stage = goal.stages[stageIndex - 1]
|
||||
if (action === 'stage_pass' && evidence === '') return '通过阶段必须写 evidence:测试输出、改动文件或检查结果。'
|
||||
if (action === 'stage_reject' && reason === '') return '驳回阶段必须写 reason:缺什么、怎么改。'
|
||||
const digest = stageDigest(goal, stageIndex)
|
||||
const record = {
|
||||
id: `rev-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'stage',
|
||||
stageIndex,
|
||||
stageTitle: stage.title,
|
||||
digest,
|
||||
verdict: action === 'stage_pass' ? 'pass' : 'reject',
|
||||
reviewerRole: actor.kind === 'bot' ? 'shangshu' : 'user',
|
||||
reviewerBotId: actor.botId ?? null,
|
||||
reviewerSessionId: actor.sessionId ?? null,
|
||||
evidence: evidence === '' ? null : evidence,
|
||||
reason: reason === '' ? null : reason,
|
||||
at: Date.now(),
|
||||
}
|
||||
record.eventKey = sha256(JSON.stringify({
|
||||
projectId: record.projectId, goalId: record.goalId, goalRevision: record.goalRevision,
|
||||
kind: record.kind, stageIndex, digest, verdict: record.verdict,
|
||||
reviewerRole: record.reviewerRole, reviewerBotId: record.reviewerBotId,
|
||||
}))
|
||||
const result = await store.addReview(record)
|
||||
if (result.duplicate) return `同样的阶段审查已记录(${result.review.id}),没有重复写入。`
|
||||
if (record.verdict === 'pass') {
|
||||
return `已记录尚书阶段审查 ${record.id}:阶段 ${stageIndex}「${stage.title}」通过,目标版本 ${goal.revision}。现在可以 group_goal pass(evidence 用同一份证据)。`
|
||||
}
|
||||
const budget = budgetOf(goal, project, store.peek().reworks)
|
||||
return `已记录尚书阶段审查 ${record.id}:阶段 ${stageIndex}「${stage.title}」驳回,目标版本 ${goal.revision}。可以 group_goal rework;返工将计为 ${budget.used + 1}/${budget.max}。`
|
||||
}
|
||||
|
||||
const oneGoal = goal
|
||||
if (oneGoal.status !== 'active') return `目标当前是 ${oneGoal.status},不能做目标验收。`
|
||||
const stages = oneGoal.stages ?? []
|
||||
if (stages.length === 0 || stages.some(stage => stage.status !== 'passed')) {
|
||||
const open = stages.findIndex(stage => stage.status !== 'passed')
|
||||
return `还有阶段没通过(第 ${open + 1} 阶段${stages[open]?.title ? `「${stages[open].title}」` : ''}),丞相不能做整体验收。`
|
||||
}
|
||||
if (action === 'goal_pass' && evidence === '') return '目标验收通过必须写 evidence:整体交付与验收标准的对照。'
|
||||
if (action === 'goal_reject' && reason === '') return '目标验收驳回必须写 reason:不满足哪条验收标准。'
|
||||
const digest = goalDigest(oneGoal)
|
||||
const record = {
|
||||
id: `rev-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
|
||||
projectId: project.id,
|
||||
goalId: oneGoal.id,
|
||||
goalRevision: oneGoal.revision,
|
||||
kind: 'goal',
|
||||
stageIndex: null,
|
||||
stageTitle: null,
|
||||
digest,
|
||||
verdict: action === 'goal_pass' ? 'pass' : 'reject',
|
||||
reviewerRole: actor.kind === 'bot' ? 'lead' : 'user',
|
||||
reviewerBotId: actor.botId ?? null,
|
||||
reviewerSessionId: actor.sessionId ?? null,
|
||||
evidence: evidence === '' ? null : evidence,
|
||||
reason: reason === '' ? null : reason,
|
||||
at: Date.now(),
|
||||
}
|
||||
record.eventKey = sha256(JSON.stringify({
|
||||
projectId: record.projectId, goalId: record.goalId, goalRevision: record.goalRevision,
|
||||
kind: record.kind, stageIndex: null, digest, verdict: record.verdict,
|
||||
reviewerRole: record.reviewerRole, reviewerBotId: record.reviewerBotId,
|
||||
}))
|
||||
const result = await store.addReview(record)
|
||||
if (result.duplicate) return `同样的目标验收已记录(${result.review.id}),没有重复写入。`
|
||||
return record.verdict === 'pass'
|
||||
? `已记录丞相目标验收 ${record.id}(目标版本 ${oneGoal.revision})。尚书现在可以 group_goal complete。`
|
||||
: `已记录丞相目标验收驳回 ${record.id}(目标版本 ${oneGoal.revision})。让尚书 revise 目标或继续返工后重新验收。`
|
||||
}
|
||||
|
||||
export function installTools({ ctx, store, dsbot }) {
|
||||
export function installTools({ ctx, store, dsbot, isBotSession }) {
|
||||
const wrappedExec = exec => ({ ...(exec ?? {}), __isBotSession: isBotSession })
|
||||
const disposers = [
|
||||
registerTextTool(ctx,
|
||||
'sansheng_provision',
|
||||
|
|
@ -416,11 +402,13 @@ export function installTools({ ctx, store, dsbot }) {
|
|||
properties: {
|
||||
project: { type: 'string', description: '项目名,如“官网改版”。' },
|
||||
groupName: { type: 'string', description: '项目群名,默认“项目名 · 三省六部”。' },
|
||||
leadName: { type: 'string', description: '丞相 Bot 名,默认“丞相”。' },
|
||||
leadName: { type: 'string', description: '丞相 Bot 名,默认“丞相”(重名时自动加项目后缀)。' },
|
||||
shangshuName: { type: 'string', description: '尚书 Bot 名,默认“尚书”。' },
|
||||
gongbuName: { type: 'string', description: '工部 Bot 名,默认“工部”。' },
|
||||
workDir: { type: 'string', description: '三个 Bot 的工作目录(可选)。' },
|
||||
workspaceId: { type: 'string', description: '工作区 id(可选,仅登记用)。' },
|
||||
workDir: { type: 'string', description: '三个 Bot 的工作目录(强烈建议每项目独立目录)。' },
|
||||
workspaceId: { type: 'string', description: '宿主工作区 id(项目树 ID 映射,推荐)。' },
|
||||
hostWorkspaceId: { type: 'string', description: '宿主 workspace id(与 workspaceId 相同或更精确)。' },
|
||||
projectTreeId: { type: 'string', description: '项目树节点 id(可选)。' },
|
||||
models: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
|
|
@ -431,31 +419,39 @@ export function installTools({ ctx, store, dsbot }) {
|
|||
},
|
||||
},
|
||||
maxReworks: { type: 'integer', minimum: 1, maximum: 10, description: '返工预算,按整个目标累计,默认 3。' },
|
||||
autoRework: { type: 'boolean', description: '是否自动把驳回任务交给工部,默认 true。' },
|
||||
include: { type: 'array', items: { type: 'string' }, description: '成果快照包含的路径前缀(空=整个工作目录)。' },
|
||||
exclude: { type: 'array', items: { type: 'string' }, description: '成果快照额外排除的路径/模式。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => provision({ ctx, store, dsbot, args, exec })),
|
||||
(args, exec) => provisionProject({ ctx, store, dsbot, args, actor: resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession }) }).then(result => result.text)),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_bind',
|
||||
'把已有的 DS Bot 群绑定为三省六部项目:校验三个角色都在群里、群管理员是尚书。',
|
||||
'把已有的 DS Bot 群绑定为三省六部项目:校验三个角色都在群里、群管理员是尚书、Bot 与群未被其他项目占用。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['room'],
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名,默认用群名。' },
|
||||
room: { type: 'string', description: '项目群名或群 id。' },
|
||||
room: { type: 'string', description: '项目群名或群 id(支持带引号群名)。' },
|
||||
lead: { type: 'string', description: '丞相 Bot 名或 id(可选,默认按角色名找)。' },
|
||||
shangshu: { type: 'string', description: '尚书 Bot 名或 id(可选)。' },
|
||||
gongbu: { type: 'string', description: '工部 Bot 名或 id(可选)。' },
|
||||
workDir: { type: 'string', description: '项目工作目录(登记用)。' },
|
||||
workspaceId: { type: 'string', description: '工作区 id(登记用)。' },
|
||||
workDir: { type: 'string', description: '项目工作目录(成果快照的根)。' },
|
||||
workspaceId: { type: 'string', description: '宿主工作区 id(项目树映射)。' },
|
||||
maxReworks: { type: 'integer', minimum: 1, maximum: 10, description: '返工预算,默认 3。' },
|
||||
},
|
||||
},
|
||||
args => bind({ store, dsbot, args })),
|
||||
async (args, exec) => {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession })
|
||||
if (actor.kind === 'bot') return '只有用户能把群绑定为项目;Bot 不能改项目绑定。'
|
||||
const result = await bindProject({ store, dsbot, rt: ctx.get('dsbot-runtime', false), args })
|
||||
return result.text
|
||||
}),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_status',
|
||||
'查看三省六部项目状态:三角色 Bot、项目群、目标阶段、返工预算。',
|
||||
'查看三省六部项目状态:三角色 Bot、项目群、目标阶段、返工预算、写租约与成果代次。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
|
|
@ -463,23 +459,89 @@ export function installTools({ ctx, store, dsbot }) {
|
|||
project: { type: 'string', description: '项目名或 id;省略则列出全部。' },
|
||||
},
|
||||
},
|
||||
args => status({ store, dsbot, args })),
|
||||
args => statusText({ store, dsbot, args })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_review',
|
||||
'记录审查:尚书记录阶段通过/驳回,丞相记录目标验收通过/驳回。门禁要求通过阶段前有尚书 stage_pass、完成目标前有丞相 goal_pass,且证据与当前目标版本一致。',
|
||||
'记录审查:尚书记录阶段通过/驳回,丞相记录目标验收通过/驳回。会自动生成并绑定成果快照;门禁要求最新判决、验收标准、成果摘要与提交代次都匹配当前版本。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['action'],
|
||||
properties: {
|
||||
action: { type: 'string', enum: ['stage_pass', 'stage_reject', 'goal_pass', 'goal_reject'], description: '审查类型。' },
|
||||
project: { type: 'string', description: '项目名或 id;在项目群内可省略。' },
|
||||
project: { type: 'string', description: '项目名或 id;Bot 在项目群内可省略,用户必须指定。' },
|
||||
stage: { type: 'integer', minimum: 1, description: '阶段号,默认当前阶段。' },
|
||||
evidence: { type: 'string', description: 'stage_pass/goal_pass 必填:测试输出、改动文件、验收对照。' },
|
||||
reason: { type: 'string', description: 'stage_reject/goal_reject 必填:缺什么、怎么改。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => review({ store, dsbot, args, exec })),
|
||||
(args, exec) => review({ store, dsbot, args, exec: wrappedExec(exec) })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_submit',
|
||||
'提交当前项目成果:服务端生成成果快照并推进提交代次;审查会绑定最新快照。项目有 workDir 时必做。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名或 id;Bot 可省略。' },
|
||||
stage: { type: 'integer', minimum: 1, description: '阶段号(可选)。' },
|
||||
scope: { type: 'string', enum: ['stage', 'goal'], description: '快照范围,默认 stage。' },
|
||||
task: { type: 'string', description: '写任务标识(用于写租约)。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => submit({ store, dsbot, args, exec: wrappedExec(exec) })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_config',
|
||||
'修改项目配置(模型/返工预算/自动返工/交付范围),只影响本项目;只有用户可调用。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名或 id。' },
|
||||
models: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
lead: { type: 'string' },
|
||||
shangshu: { type: 'string' },
|
||||
gongbu: { type: 'string' },
|
||||
},
|
||||
},
|
||||
maxReworks: { type: 'integer', minimum: 1, maximum: 10 },
|
||||
autoRework: { type: 'boolean' },
|
||||
include: { type: 'array', items: { type: 'string' } },
|
||||
exclude: { type: 'array', items: { type: 'string' } },
|
||||
},
|
||||
},
|
||||
(args, exec) => config({ ctx, store, dsbot, args, exec: wrappedExec(exec) })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_control',
|
||||
'用户控制目标:pause / resume / stop / cancel。stop 保留目标记录;cancel 同时请求停止当前执行。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['project', 'action'],
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名或 id。' },
|
||||
action: { type: 'string', enum: ['pause', 'resume', 'stop', 'cancel'] },
|
||||
confirm: { type: 'boolean', description: 'cancel 必须传 true。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => control({ ctx, store, dsbot, args, exec: wrappedExec(exec) })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_lease',
|
||||
'项目写租约:acquire / release / status。第一版每项目最多一个活动写任务。',
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目名或 id。' },
|
||||
action: { type: 'string', enum: ['acquire', 'release', 'status'], description: '默认 status。' },
|
||||
task: { type: 'string', description: 'acquire 的任务标识。' },
|
||||
ttlMs: { type: 'integer', minimum: 60000, maximum: 86400000 },
|
||||
},
|
||||
},
|
||||
(args, exec) => lease({ store, dsbot, args, exec: wrappedExec(exec) })),
|
||||
registerTextTool(ctx,
|
||||
'sansheng_reconcile',
|
||||
'核对重启前未拿到回执的派发记录:不带 id 列出待核实项;带 id 与 verdict 标记为已执行或未执行。核实前先看原生目标状态,不要盲目重发。',
|
||||
|
|
@ -492,7 +554,7 @@ export function installTools({ ctx, store, dsbot }) {
|
|||
verdict: { type: 'string', enum: ['done', 'not-done'], description: 'done=原生操作确实执行过;not-done=没有执行。' },
|
||||
},
|
||||
},
|
||||
(args, exec) => reconcile({ store, dsbot, args, exec })),
|
||||
(args, exec) => reconcile({ store, dsbot, args, exec: wrappedExec(exec) })),
|
||||
]
|
||||
return disposers
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,137 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { buildStatePayload, resolveCurrentProject } from '../src/api.js'
|
||||
|
||||
function fakeStore({ project, reviews = [], unknown = 0, artifacts = [] } = {}) {
|
||||
return {
|
||||
peek: () => ({ version: 3, seq: 10, projects: { [project.id]: project }, reviews, dispatches: [], reworks: [], artifacts: {}, leases: {}, events: [] }),
|
||||
unknownDispatches: () => Array.from({ length: unknown }, (_, index) => ({ id: `dsp-${index}` })),
|
||||
dispatchesFor: () => [],
|
||||
reviewsFor: match => reviews
|
||||
.filter(item => Object.entries(match).every(([key, value]) => item[key] === value))
|
||||
.sort((a, b) => (b.seq ?? 0) - (a.seq ?? 0)),
|
||||
artifactsFor: () => artifacts,
|
||||
leaseOf: () => undefined,
|
||||
}
|
||||
}
|
||||
|
||||
const project = {
|
||||
id: 'prj-1', name: '示例项目', workspaceId: 'ws-1', hostWorkspaceId: 'ws-1', workDir: 'C:/work',
|
||||
roomId: 'room-1', bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' }, models: {}, maxReworks: 3,
|
||||
}
|
||||
|
||||
const bots = {
|
||||
'b-lead': { id: 'b-lead', name: '丞相', sessionId: 'sess-lead' },
|
||||
'b-shang': { id: 'b-shang', name: '尚书', sessionId: 'sess-shang' },
|
||||
'b-gong': { id: 'b-gong', name: '工部', sessionId: 'sess-gong' },
|
||||
}
|
||||
|
||||
function goalAt({ status = 'active', current = 0, stageStatus = 'active', taskStatus = 'working' } = {}) {
|
||||
return {
|
||||
id: 'goal-1', revision: 4, status, title: '目标', objective: '做出来', acceptance: '测试通过', current,
|
||||
stages: [
|
||||
{ id: 's1', title: '骨架', acceptance: '能开', status: stageStatus, reworks: 0, tasks: [{ id: 't1', botId: 'b-gong', task: '写', status: taskStatus }] },
|
||||
{ id: 's2', title: '内容', acceptance: '齐全', status: 'pending', reworks: 0, tasks: [] },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function build({ goal, reviews = [], unknown = 0, artifacts = [] } = {}) {
|
||||
const room = goal === undefined ? { id: 'room-1', name: '群' } : { id: 'room-1', name: '群', goal }
|
||||
const dsbot = {
|
||||
botOf: id => bots[id],
|
||||
roomOf: id => (id === 'room-1' ? room : undefined),
|
||||
}
|
||||
return buildStatePayload({ store: fakeStore({ project, reviews, unknown, artifacts }), dsbot, now: 1 }).projects[0]
|
||||
}
|
||||
|
||||
test('角色卡带真实会话 id,可点击打开', () => {
|
||||
const card = build({ goal: goalAt() })
|
||||
assert.equal(card.roles.find(item => item.role === 'lead').sessionId, 'sess-lead')
|
||||
assert.equal(card.roles.every(item => item.clickable), true)
|
||||
})
|
||||
|
||||
test('阶段执行中 → phase=执行中', () => {
|
||||
const card = build({ goal: goalAt({ taskStatus: 'working' }) })
|
||||
assert.equal(card.phase, '执行中')
|
||||
assert.equal(card.currentStage.index, 1)
|
||||
})
|
||||
|
||||
test('阶段任务全部完成 → phase=待审查', () => {
|
||||
const card = build({ goal: goalAt({ taskStatus: 'done' }) })
|
||||
assert.equal(card.phase, '待审查')
|
||||
})
|
||||
|
||||
test('最新阶段驳回 → phase=返工中,且 attention 指向返工', () => {
|
||||
const goal = goalAt({ taskStatus: 'done' })
|
||||
const reviews = [{
|
||||
id: 'rev-1', seq: 1, projectId: 'prj-1', goalId: 'goal-1', kind: 'stage', stageIndex: 1,
|
||||
verdict: 'reject', reviewerRole: 'shangshu', reason: '缺测试', at: 1,
|
||||
}]
|
||||
const card = build({ goal, reviews })
|
||||
assert.equal(card.phase, '返工中')
|
||||
assert.equal(card.attention.some(item => item.role === 'gongbu'), true)
|
||||
})
|
||||
|
||||
test('历史驳回之后又有更新通过,不再显示旧返工', () => {
|
||||
const goal = goalAt({ taskStatus: 'done' })
|
||||
const reviews = [
|
||||
{ id: 'r1', seq: 1, projectId: 'prj-1', goalId: 'goal-1', kind: 'stage', stageIndex: 1, verdict: 'reject', reviewerRole: 'shangshu', reason: '旧问题', at: 1 },
|
||||
{ id: 'r2', seq: 2, projectId: 'prj-1', goalId: 'goal-1', kind: 'stage', stageIndex: 1, verdict: 'pass', reviewerRole: 'shangshu', at: 2 },
|
||||
]
|
||||
const card = build({ goal, reviews })
|
||||
assert.equal(card.phase, '待审查')
|
||||
assert.equal(card.attention.some(item => item.reason.includes('旧问题')), false)
|
||||
})
|
||||
|
||||
test('全部阶段通过 → phase=待审查,丞相卡为 attention', () => {
|
||||
const goal = {
|
||||
...goalAt(),
|
||||
current: 2,
|
||||
stages: [
|
||||
{ id: 's1', title: '一', status: 'passed', tasks: [] },
|
||||
{ id: 's2', title: '二', status: 'passed', tasks: [] },
|
||||
],
|
||||
}
|
||||
const card = build({ goal })
|
||||
assert.equal(card.phase, '待审查')
|
||||
assert.equal(card.roles.find(item => item.role === 'lead').tone, 'attention')
|
||||
})
|
||||
|
||||
test('暂停 / 完成 / 无目标 / 有未知派发的 phase', () => {
|
||||
assert.equal(build({ goal: goalAt({ status: 'paused' }) }).phase, '暂停')
|
||||
assert.equal(build({ goal: goalAt({ status: 'complete' }) }).phase, '已完成')
|
||||
assert.equal(build({ goal: undefined }).phase, '待执行')
|
||||
assert.equal(build({ goal: goalAt(), unknown: 2 }).phase, '待核实')
|
||||
})
|
||||
|
||||
test('成果快照摘要出现在当前项目卡片,历史审查可折叠数据存在', () => {
|
||||
const card = build({
|
||||
goal: goalAt(),
|
||||
artifacts: [{ id: 'art-1', digest: 'abc', kind: 'git', fileCount: 3, totalBytes: 100, submissionSeq: 2, createdAt: 1 }],
|
||||
reviews: [{ id: 'r1', seq: 1, projectId: 'prj-1', goalId: 'goal-1', kind: 'goal', verdict: 'pass', reviewerRole: 'lead', at: 1 }],
|
||||
})
|
||||
assert.equal(card.submissionSeq, 2)
|
||||
assert.equal(card.lastSubmission.digest, 'abc')
|
||||
assert.equal(card.reviewsHistory.length, 1)
|
||||
})
|
||||
|
||||
test('DS Bot 没有 sessionId 字段时用 Bot id 作为私聊会话 id', () => {
|
||||
const card = buildStatePayload({
|
||||
store: fakeStore({ project }),
|
||||
dsbot: {
|
||||
botOf: id => ({ 'b-lead': { id: 'b-lead', name: '丞相' }, 'b-shang': { id: 'b-shang', name: '尚书' }, 'b-gong': { id: 'b-gong', name: '工部' } })[id],
|
||||
roomOf: () => ({ id: 'room-1', name: '群', goal: goalAt() }),
|
||||
},
|
||||
now: 1,
|
||||
}).projects[0]
|
||||
assert.equal(card.roles.find(item => item.role === 'lead').sessionId, 'b-lead')
|
||||
assert.equal(card.roles.every(item => item.clickable), true)
|
||||
})
|
||||
|
||||
test('resolveCurrentProject 按 workspaceId 优先,其次 session', () => {
|
||||
const payload = { projects: [{ id: 'prj-1', workspaceId: 'ws-1', roles: [{ sessionId: 'sess-1' }] }] }
|
||||
assert.equal(resolveCurrentProject(payload, { workspaceId: 'ws-1' }).project.id, 'prj-1')
|
||||
assert.equal(resolveCurrentProject(payload, { sessionId: 'sess-1' }).project.id, 'prj-1')
|
||||
assert.equal(resolveCurrentProject(payload, { workspaceId: 'ws-x', sessionId: 'sess-x' }).project, undefined)
|
||||
})
|
||||
|
|
@ -0,0 +1,293 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
DEFAULT_EXCLUDES,
|
||||
captureArtifactSnapshot,
|
||||
captureArtifactSnapshotSync,
|
||||
deliveryPolicyOf,
|
||||
summarizeSnapshot,
|
||||
verifyArtifactSnapshot,
|
||||
verifyArtifactSnapshotSync,
|
||||
} from '../src/artifact.js'
|
||||
|
||||
const GIT_AVAILABLE = (() => {
|
||||
try {
|
||||
execFileSync('git', ['--version'], { stdio: 'ignore' })
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})()
|
||||
|
||||
function git(cwd, args) {
|
||||
return execFileSync('git', args, {
|
||||
cwd,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
}
|
||||
|
||||
function projectFor(workDir, delivery = {}) {
|
||||
return { id: 'prj-artifact-test', workDir, delivery }
|
||||
}
|
||||
|
||||
async function tempDir(label) {
|
||||
return mkdtemp(join(tmpdir(), `sansheng-artifact-${label}-`))
|
||||
}
|
||||
|
||||
async function cleanup(dir) {
|
||||
await rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 })
|
||||
}
|
||||
|
||||
test('DEFAULT_EXCLUDES 覆盖默认目录与敏感文件模式', () => {
|
||||
assert.ok(Array.isArray(DEFAULT_EXCLUDES))
|
||||
for (const name of [
|
||||
'.git', 'node_modules', '.venv', 'venv', '__pycache__', 'dist', 'build',
|
||||
'coverage', '.next', '.cache', '.turbo', 'target', 'out',
|
||||
]) {
|
||||
assert.ok(DEFAULT_EXCLUDES.includes(name), `缺少目录排除 ${name}`)
|
||||
}
|
||||
for (const pattern of [
|
||||
'*.log', '*.tmp', '.env*', '*.pem', '*.key', '*.p12', 'id_rsa*',
|
||||
'credentials*', '.DS_Store', 'Thumbs.db',
|
||||
]) {
|
||||
assert.ok(DEFAULT_EXCLUDES.includes(pattern), `缺少文件排除 ${pattern}`)
|
||||
}
|
||||
assert.ok(DEFAULT_EXCLUDES.dirs.includes('node_modules'))
|
||||
assert.ok(DEFAULT_EXCLUDES.files.includes('.env*'))
|
||||
})
|
||||
|
||||
test('deliveryPolicyOf 合并默认值与项目 delivery', () => {
|
||||
const policy = deliveryPolicyOf({
|
||||
delivery: {
|
||||
include: ['src', './src', 'docs/'],
|
||||
exclude: ['secret.txt', '*.bak', 'secret.txt'],
|
||||
maxFileBytes: 1024,
|
||||
maxFiles: 7,
|
||||
},
|
||||
})
|
||||
assert.deepEqual(policy.include, ['src', 'docs'])
|
||||
assert.ok(policy.exclude.includes('secret.txt'))
|
||||
assert.ok(policy.exclude.includes('*.bak'))
|
||||
assert.ok(policy.exclude.includes('.git'))
|
||||
assert.ok(policy.exclude.includes('*.log'))
|
||||
assert.equal(policy.maxFileBytes, 1024)
|
||||
assert.equal(policy.maxFiles, 7)
|
||||
|
||||
const defaults = deliveryPolicyOf({})
|
||||
assert.deepEqual(defaults.include, [])
|
||||
assert.equal(defaults.maxFileBytes, 4 * 1024 * 1024)
|
||||
assert.equal(defaults.maxFiles, 5000)
|
||||
assert.ok(defaults.exclude.includes('node_modules'))
|
||||
})
|
||||
|
||||
test('非 Git 目录:快照稳定,内容/交付文件变化会改变摘要', async () => {
|
||||
const dir = await tempDir('plain')
|
||||
try {
|
||||
await writeFile(join(dir, 'a.txt'), 'alpha', 'utf8')
|
||||
await writeFile(join(dir, 'b.txt'), 'beta', 'utf8')
|
||||
const project = projectFor(dir)
|
||||
const goal = { id: 'goal-plain' }
|
||||
|
||||
const first = await captureArtifactSnapshot({ project, goal, stageIndex: 1, now: 1000 })
|
||||
const again = await captureArtifactSnapshot({ project, goal, stageIndex: 1, now: 2000 })
|
||||
assert.equal(first.kind, 'files')
|
||||
assert.equal(first.exists, true)
|
||||
assert.equal(first.fileCount, 2)
|
||||
assert.equal(first.totalBytes, 9)
|
||||
assert.deepEqual(first.files.map(file => file.path), ['a.txt', 'b.txt'])
|
||||
assert.equal(first.digest, again.digest)
|
||||
assert.notEqual(first.id, again.id)
|
||||
|
||||
// 默认排除的目录与敏感文件不影响快照。
|
||||
await mkdir(join(dir, 'node_modules', 'pkg'), { recursive: true })
|
||||
await writeFile(join(dir, 'node_modules', 'pkg', 'index.js'), 'console.log(1)', 'utf8')
|
||||
await writeFile(join(dir, '.env'), 'SECRET=1', 'utf8')
|
||||
await writeFile(join(dir, '.env.local'), 'SECRET=2', 'utf8')
|
||||
const ignored = await captureArtifactSnapshot({ project, goal, stageIndex: 1 })
|
||||
assert.equal(ignored.digest, first.digest)
|
||||
assert.equal(ignored.fileCount, 2)
|
||||
assert.ok(!ignored.files.some(file => file.path === '.env'))
|
||||
assert.ok(!ignored.files.some(file => file.path.startsWith('node_modules/')))
|
||||
|
||||
// 修改已交付文件 → 摘要变化。
|
||||
await writeFile(join(dir, 'a.txt'), 'alpha changed', 'utf8')
|
||||
const modified = await captureArtifactSnapshot({ project, goal, stageIndex: 1 })
|
||||
assert.notEqual(modified.digest, first.digest)
|
||||
const before = first.files.find(file => file.path === 'a.txt')
|
||||
const after = modified.files.find(file => file.path === 'a.txt')
|
||||
assert.notEqual(after.sha256, before.sha256)
|
||||
|
||||
// 新增交付文件 → 摘要变化。
|
||||
await writeFile(join(dir, 'c.txt'), 'gamma', 'utf8')
|
||||
const added = await captureArtifactSnapshot({ project, goal, stageIndex: 1 })
|
||||
assert.notEqual(added.digest, modified.digest)
|
||||
assert.ok(added.files.some(file => file.path === 'c.txt'))
|
||||
|
||||
// sync 与 async 对同一目录必须给出同一摘要。
|
||||
const sync = captureArtifactSnapshotSync({ project, goal, stageIndex: 1 })
|
||||
assert.equal(sync.digest, added.digest)
|
||||
assert.deepEqual(sync.files, added.files)
|
||||
assert.equal(sync.kind, added.kind)
|
||||
|
||||
const verify = await verifyArtifactSnapshot({ snapshot: added, project })
|
||||
assert.equal(verify.ok, true)
|
||||
assert.equal(verifyArtifactSnapshotSync({ snapshot: added, project }).ok, true)
|
||||
|
||||
await writeFile(join(dir, 'c.txt'), 'gamma2', 'utf8')
|
||||
const stale = await verifyArtifactSnapshot({ snapshot: added, project })
|
||||
assert.equal(stale.ok, false)
|
||||
assert.match(stale.reason, /成果已变化/)
|
||||
assert.equal(verifyArtifactSnapshotSync({ snapshot: added, project }).ok, false)
|
||||
} finally {
|
||||
await cleanup(dir)
|
||||
}
|
||||
})
|
||||
|
||||
test('include 前缀限制交付范围,maxFiles 超限标记 truncated', async () => {
|
||||
const dir = await tempDir('include')
|
||||
try {
|
||||
await mkdir(join(dir, 'src', 'nested'), { recursive: true })
|
||||
await mkdir(join(dir, 'docs'), { recursive: true })
|
||||
await writeFile(join(dir, 'src', 'a.js'), 'a', 'utf8')
|
||||
await writeFile(join(dir, 'src', 'nested', 'b.js'), 'b', 'utf8')
|
||||
await writeFile(join(dir, 'docs', 'readme.md'), 'doc', 'utf8')
|
||||
await writeFile(join(dir, 'root.txt'), 'root', 'utf8')
|
||||
|
||||
const project = projectFor(dir, { include: ['src'] })
|
||||
const snapshot = await captureArtifactSnapshot({ project, goal: { id: 'goal-include' }, stageIndex: 1 })
|
||||
assert.deepEqual(snapshot.files.map(file => file.path), ['src/a.js', 'src/nested/b.js'])
|
||||
assert.ok(!snapshot.files.some(file => file.path.startsWith('docs/')))
|
||||
assert.ok(!snapshot.files.some(file => file.path === 'root.txt'))
|
||||
|
||||
const limited = await captureArtifactSnapshot({
|
||||
project,
|
||||
goal: { id: 'goal-include' },
|
||||
stageIndex: 1,
|
||||
policy: { ...deliveryPolicyOf(project), maxFiles: 1 },
|
||||
})
|
||||
assert.equal(limited.fileCount, 1)
|
||||
assert.equal(limited.truncated, true)
|
||||
assert.equal(limited.digest.length, 64)
|
||||
} finally {
|
||||
await cleanup(dir)
|
||||
}
|
||||
})
|
||||
|
||||
test('Git 目录:记录 baseCommit,tracked/untracked 变化会改变摘要', { skip: GIT_AVAILABLE ? false : 'git 不可用' }, async () => {
|
||||
const dir = await tempDir('git')
|
||||
try {
|
||||
git(dir, ['init'])
|
||||
git(dir, ['config', 'user.name', 'Artifact Test'])
|
||||
git(dir, ['config', 'user.email', 'artifact@example.com'])
|
||||
await writeFile(join(dir, 'tracked.txt'), 'one\n', 'utf8')
|
||||
git(dir, ['add', '.'])
|
||||
git(dir, ['commit', '-m', 'initial'])
|
||||
|
||||
const project = projectFor(dir)
|
||||
const goal = { id: 'goal-git' }
|
||||
const head = git(dir, ['rev-parse', 'HEAD']).trim()
|
||||
|
||||
const first = await captureArtifactSnapshot({ project, goal, stageIndex: 1 })
|
||||
const second = await captureArtifactSnapshot({ project, goal, stageIndex: 1 })
|
||||
assert.equal(first.kind, 'git')
|
||||
assert.equal(first.exists, true)
|
||||
assert.equal(first.baseCommit, head)
|
||||
assert.equal(first.fileCount, 0)
|
||||
assert.equal(first.digest, second.digest)
|
||||
|
||||
const sync = captureArtifactSnapshotSync({ project, goal, stageIndex: 1 })
|
||||
assert.equal(sync.digest, first.digest)
|
||||
|
||||
// 修改 tracked 文件 → diffDigest 与总摘要变化。
|
||||
await writeFile(join(dir, 'tracked.txt'), 'two\n', 'utf8')
|
||||
const modified = await captureArtifactSnapshot({ project, goal, stageIndex: 1 })
|
||||
assert.notEqual(modified.digest, first.digest)
|
||||
assert.equal(modified.baseCommit, first.baseCommit)
|
||||
assert.notEqual(modified.diffDigest, first.diffDigest)
|
||||
assert.notEqual(modified.statusDigest, first.statusDigest)
|
||||
|
||||
// 新增未跟踪交付文件 → files 记录内容摘要,总摘要变化。
|
||||
await writeFile(join(dir, 'untracked.txt'), 'new\n', 'utf8')
|
||||
const added = await captureArtifactSnapshot({ project, goal, stageIndex: 1 })
|
||||
assert.notEqual(added.digest, modified.digest)
|
||||
assert.ok(added.files.some(file => file.path === 'untracked.txt'))
|
||||
const untracked = added.files.find(file => file.path === 'untracked.txt')
|
||||
assert.equal(untracked.sha256.length, 64)
|
||||
|
||||
assert.equal((await verifyArtifactSnapshot({ snapshot: added, project })).ok, true)
|
||||
await writeFile(join(dir, 'untracked.txt'), 'changed\n', 'utf8')
|
||||
const stale = await verifyArtifactSnapshot({ snapshot: added, project })
|
||||
assert.equal(stale.ok, false)
|
||||
assert.match(stale.reason, /成果已变化/)
|
||||
} finally {
|
||||
await cleanup(dir)
|
||||
}
|
||||
})
|
||||
|
||||
test('workDir 为空/不存在:unscoped 与 missing 同类通过、跨类失败', async () => {
|
||||
const dir = await tempDir('unscoped')
|
||||
try {
|
||||
const projectId = 'prj-state-test'
|
||||
const unscopedProject = { id: projectId, workDir: '' }
|
||||
const missingProject = { id: projectId, workDir: join(dir, 'not-here') }
|
||||
const goal = { id: 'goal-state' }
|
||||
|
||||
const unscoped = await captureArtifactSnapshot({ project: unscopedProject, goal, stageIndex: 1 })
|
||||
const unscopedAgain = await captureArtifactSnapshot({ project: unscopedProject, goal, stageIndex: 1 })
|
||||
assert.equal(unscoped.kind, 'unscoped')
|
||||
assert.equal(unscoped.exists, false)
|
||||
assert.equal(unscoped.fileCount, 0)
|
||||
assert.equal(unscoped.digest, unscopedAgain.digest)
|
||||
assert.equal(captureArtifactSnapshotSync({ project: unscopedProject, goal, stageIndex: 1 }).digest, unscoped.digest)
|
||||
|
||||
const missing = await captureArtifactSnapshot({ project: missingProject, goal, stageIndex: 1 })
|
||||
assert.equal(missing.kind, 'missing')
|
||||
assert.equal(missing.exists, false)
|
||||
assert.equal(missing.fileCount, 0)
|
||||
assert.equal(captureArtifactSnapshotSync({ project: missingProject, goal, stageIndex: 1 }).digest, missing.digest)
|
||||
|
||||
assert.equal((await verifyArtifactSnapshot({ snapshot: unscoped, project: unscopedProject })).ok, true)
|
||||
assert.equal((await verifyArtifactSnapshot({ snapshot: missing, project: missingProject })).ok, true)
|
||||
assert.equal(verifyArtifactSnapshotSync({ snapshot: missing, project: missingProject }).ok, true)
|
||||
|
||||
const missingAgainstUnscoped = await verifyArtifactSnapshot({ snapshot: missing, project: unscopedProject })
|
||||
assert.equal(missingAgainstUnscoped.ok, false)
|
||||
assert.match(missingAgainstUnscoped.reason, /成果来源已变化/)
|
||||
const unscopedAgainstMissing = await verifyArtifactSnapshot({ snapshot: unscoped, project: missingProject })
|
||||
assert.equal(unscopedAgainstMissing.ok, false)
|
||||
assert.match(unscopedAgainstMissing.reason, /成果来源已变化/)
|
||||
} finally {
|
||||
await cleanup(dir)
|
||||
}
|
||||
})
|
||||
|
||||
test('summarizeSnapshot 返回固定字段集', async () => {
|
||||
const dir = await tempDir('summary')
|
||||
try {
|
||||
await writeFile(join(dir, 'a.txt'), 'alpha', 'utf8')
|
||||
const snapshot = await captureArtifactSnapshot({ project: projectFor(dir), goal: { id: 'goal-summary' }, stageIndex: 1 })
|
||||
const summary = summarizeSnapshot(snapshot)
|
||||
assert.deepEqual(Object.keys(summary).sort(), [
|
||||
'baseCommit', 'diffDigest', 'digest', 'exists', 'fileCount', 'kind', 'totalBytes', 'truncated',
|
||||
])
|
||||
assert.deepEqual(summary, {
|
||||
digest: snapshot.digest,
|
||||
kind: snapshot.kind,
|
||||
fileCount: snapshot.fileCount,
|
||||
totalBytes: snapshot.totalBytes,
|
||||
truncated: snapshot.truncated,
|
||||
baseCommit: snapshot.baseCommit,
|
||||
diffDigest: snapshot.diffDigest,
|
||||
exists: snapshot.exists,
|
||||
})
|
||||
assert.equal(summary.fileCount, 1)
|
||||
assert.equal(summary.kind, 'files')
|
||||
} finally {
|
||||
await cleanup(dir)
|
||||
}
|
||||
})
|
||||
|
|
@ -3,8 +3,9 @@ import { readFile } from 'node:fs/promises'
|
|||
import { test } from 'node:test'
|
||||
|
||||
/**
|
||||
* 在 Node 里加载浏览器端插件:伪造 __ModuleLoader__、React 与最小 DOM,
|
||||
* 验证 1) 注册了右栏页签与三个插槽,2) 无数据时渲染空态提示,3) 头部按钮能打开页签。
|
||||
* 在 Node 里加载浏览器端插件:伪造 __ModuleLoader__、React 与最小 DOM。
|
||||
* 覆盖:右栏注册、项目上下文推导、原生上下文菜单、状态轮询与错误保留、
|
||||
* 配置/初始化折叠表单、角色卡会话打开和过期响应丢弃。
|
||||
*/
|
||||
|
||||
function reactStub() {
|
||||
|
|
@ -46,7 +47,7 @@ function domStub() {
|
|||
return { document, styles }
|
||||
}
|
||||
|
||||
async function loadClient() {
|
||||
async function loadClient({ fetch: customFetch } = {}) {
|
||||
const source = await readFile(new URL('../client.js', import.meta.url), 'utf8')
|
||||
const { document, styles } = domStub()
|
||||
let captured
|
||||
|
|
@ -66,20 +67,34 @@ async function loadClient() {
|
|||
setItem(key, value) { this.store.set(key, String(value)) },
|
||||
},
|
||||
}
|
||||
const fetchImpl = typeof customFetch === 'function'
|
||||
? customFetch
|
||||
: () => Promise.reject(new Error('测试里不联网'))
|
||||
const run = new Function('window', 'document', 'fetch', 'nextTick', source)
|
||||
run(window, document, () => Promise.reject(new Error('测试里不联网')), () => {})
|
||||
run(window, document, fetchImpl, () => {})
|
||||
return { module: captured.factory((name) => (name === 'react' ? reactStub() : (() => { throw new Error(name) })())), captured, document, styles, window }
|
||||
}
|
||||
|
||||
function fakeCtx({ better } = {}) {
|
||||
function fakeCtx(options = {}) {
|
||||
const { better, contextMenus, uiWorkspace, workspaces, sessions, toast } = options
|
||||
const tabs = []
|
||||
const slots = []
|
||||
const menuRegistrations = []
|
||||
const toasts = []
|
||||
const services = {
|
||||
sidebarRightTabs: { register(options) { tabs.push(options); return () => {} } },
|
||||
sidebarRightTabs: { register(registration) { tabs.push(registration); return () => {} } },
|
||||
sidebarRight: { openTabIn(sessionId, kind) { services.sidebarRight.opened = [sessionId, kind] } },
|
||||
}
|
||||
if (better) services.betterSidebar = { openTab(options, target) { services.betterSidebar.opened = [options, target] } }
|
||||
return {
|
||||
if (better) services.betterSidebar = { openTab(registration, target) { services.betterSidebar.opened = [registration, target] } }
|
||||
if (contextMenus) {
|
||||
services.contextMenus = contextMenus === true
|
||||
? { register(registration) { menuRegistrations.push(registration); return () => {} } }
|
||||
: contextMenus
|
||||
}
|
||||
if (uiWorkspace) services.uiWorkspace = uiWorkspace
|
||||
if (workspaces) services.workspaces = workspaces.list ? workspaces : { list: { getSnapshot: () => workspaces } }
|
||||
if (sessions) services.sessions = sessions.list ? sessions : { list: { getSnapshot: () => sessions } }
|
||||
const ctx = {
|
||||
effect(fn) { return fn() },
|
||||
sidebarRightTabs: services.sidebarRightTabs,
|
||||
get(name, fallback) { return services[name] ?? fallback },
|
||||
|
|
@ -96,15 +111,63 @@ function fakeCtx({ better } = {}) {
|
|||
tabs,
|
||||
slotsList: slots,
|
||||
services,
|
||||
menuRegistrations,
|
||||
toasts,
|
||||
}
|
||||
if (contextMenus) ctx.contextMenus = services.contextMenus
|
||||
if (typeof toast === 'function') ctx.toast = toast
|
||||
return ctx
|
||||
}
|
||||
|
||||
function textOf(node) {
|
||||
if (node === null || node === undefined || node === false) return ''
|
||||
function flush() {
|
||||
return new Promise(resolve => setTimeout(resolve, 0))
|
||||
}
|
||||
|
||||
function textOf(node, depth = 0) {
|
||||
if (node === null || node === undefined || node === false || node === true) return ''
|
||||
if (typeof node === 'string' || typeof node === 'number') return String(node)
|
||||
if (Array.isArray(node)) return node.map(textOf).join(' ')
|
||||
const children = node.props?.children
|
||||
return [node.type, textOf(children)].join(' ')
|
||||
if (Array.isArray(node)) return node.map(item => textOf(item, depth)).join(' ')
|
||||
if (typeof node === 'function') return node.name || ''
|
||||
if (typeof node === 'object' && node.type) {
|
||||
if (typeof node.type === 'function') {
|
||||
if (depth > 8) return node.type.name || ''
|
||||
try {
|
||||
return textOf(node.type(node.props ?? {}), depth + 1)
|
||||
} catch (error) {
|
||||
return node.type.name || ''
|
||||
}
|
||||
}
|
||||
return [String(node.type), textOf(node.props?.children, depth + 1)].join(' ')
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function findAll(node, predicate, out = []) {
|
||||
if (node === null || node === undefined || typeof node !== 'object') return out
|
||||
if (Array.isArray(node)) {
|
||||
for (const item of node) findAll(item, predicate, out)
|
||||
return out
|
||||
}
|
||||
if (predicate(node)) out.push(node)
|
||||
if (node.props && node.props.children !== undefined) findAll(node.props.children, predicate, out)
|
||||
return out
|
||||
}
|
||||
|
||||
function projectFixture(overrides = {}) {
|
||||
return {
|
||||
id: 'prj-1',
|
||||
name: '示例项目',
|
||||
phase: '执行中',
|
||||
workspaceId: 'ws-1',
|
||||
models: { lead: 'model-lead', shangshu: 'model-shang', gongbu: 'model-gong' },
|
||||
roles: [
|
||||
{ role: 'lead', label: '丞相', name: '丞相 Bot', model: 'model-lead', line: '目标进行中', detail: '目标说明', tone: 'active', sessionId: 'sess-lead', exists: true },
|
||||
{ role: 'shangshu', label: '尚书', name: '尚书 Bot', model: 'model-shang', line: '阶段 0/2', detail: '返工 0/3', tone: 'idle', sessionId: 'sess-shang', exists: true },
|
||||
{ role: 'gongbu', label: '工部', name: '工部 Bot', model: 'model-gong', line: '无工单', detail: '', tone: 'idle', sessionId: 'sess-gong', exists: true },
|
||||
],
|
||||
reviewsHistory: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
test('客户端模块导出页签常量与依赖注入', async () => {
|
||||
|
|
@ -114,6 +177,8 @@ test('客户端模块导出页签常量与依赖注入', async () => {
|
|||
assert.deepEqual(module.inject, ['slots', 'sidebarRightTabs', 'sidebarRight'])
|
||||
assert.equal(module.TAB_ID, 'sansheng-roles')
|
||||
assert.equal(module.TAB_KIND, 'sansheng-roles')
|
||||
assert.equal(typeof module.workspaceIdOf, 'function')
|
||||
assert.equal(typeof module.__test.isStale, 'function')
|
||||
})
|
||||
|
||||
test('apply 注册右栏页签与三个插槽,并只注入一次样式', async () => {
|
||||
|
|
@ -133,12 +198,15 @@ test('apply 注册右栏页签与三个插槽,并只注入一次样式', async
|
|||
'sidebar.right.pane.tab',
|
||||
'sidebar.right.pane.tab.title',
|
||||
'conversation.session.header.actions',
|
||||
'sidebar.footer.action',
|
||||
])
|
||||
const pane = ctx.slotsList[0].spec
|
||||
assert.equal(pane.key, 'sansheng-roles')
|
||||
const header = ctx.slotsList[2].spec
|
||||
assert.equal(header.id, 'sansheng-roles:open')
|
||||
assert.equal(header.order, 60)
|
||||
const footer = ctx.slotsList[3].spec
|
||||
assert.equal(footer.id, 'sansheng-roles:footer')
|
||||
|
||||
assert.equal(styles.size, 1, '样式只注入一次')
|
||||
module.apply(fakeCtx())
|
||||
|
|
@ -199,3 +267,278 @@ test('没有当前会话时提示页签是会话级的', async () => {
|
|||
tree.props.onClick()
|
||||
assert.equal(ctx.services.sidebarRight.opened, undefined)
|
||||
})
|
||||
|
||||
test('workspaceIdOf 按 retainedBy.mainView 反查当前会话所属项目,不拿第一个项目冒充', async () => {
|
||||
const { module } = await loadClient()
|
||||
const ctx = fakeCtx({
|
||||
workspaces: {
|
||||
items: [
|
||||
{ workspaceId: 'ws-first', sessionIds: ['sess-first'] },
|
||||
{ workspaceId: 'ws-current', sessionIds: ['sess-current'] },
|
||||
],
|
||||
},
|
||||
sessions: {
|
||||
byId: {
|
||||
'sess-first': { id: 'sess-first', retainedBy: { mainView: 0 } },
|
||||
'sess-current': { id: 'sess-current', retainedBy: { mainView: 1 } },
|
||||
},
|
||||
},
|
||||
})
|
||||
assert.equal(module.workspaceIdOf(ctx), 'ws-current')
|
||||
const noSelection = fakeCtx({
|
||||
workspaces: { items: [{ workspaceId: 'ws-first', sessionIds: ['sess-first'] }] },
|
||||
sessions: { byId: { 'sess-first': { id: 'sess-first' } } },
|
||||
})
|
||||
assert.equal(module.workspaceIdOf(noSelection), null, '没有明确选择时返回 null')
|
||||
})
|
||||
|
||||
test('apply 注册 workspace 与 session 两个原生上下文菜单', async () => {
|
||||
const { module } = await loadClient()
|
||||
const ctx = fakeCtx({ contextMenus: true })
|
||||
module.apply(ctx)
|
||||
|
||||
assert.equal(ctx.menuRegistrations.length, 2)
|
||||
const workspaceMenu = ctx.menuRegistrations.find(item => item.target === 'workspace')
|
||||
const sessionMenu = ctx.menuRegistrations.find(item => item.target === 'session')
|
||||
assert.ok(workspaceMenu, '注册 workspace 菜单')
|
||||
assert.ok(sessionMenu, '注册 session 菜单')
|
||||
assert.equal(workspaceMenu.id, 'sansheng.workspace.open')
|
||||
assert.equal(workspaceMenu.order, 260)
|
||||
assert.deepEqual(workspaceMenu.observe(), [])
|
||||
assert.equal(sessionMenu.id, 'sansheng.session.open')
|
||||
assert.equal(sessionMenu.order, 260)
|
||||
|
||||
const items = sessionMenu.resolve({ sessionId: 'sess-9', displayTitle: '会话九' })
|
||||
assert.equal(items.length, 1)
|
||||
assert.equal(items[0].id, 'sansheng-open')
|
||||
assert.equal(items[0].label, '打开三省六部')
|
||||
items[0].run()
|
||||
assert.deepEqual(ctx.services.sidebarRight.opened, ['sess-9', 'sansheng-roles'])
|
||||
})
|
||||
|
||||
test('没有 contextMenus 服务时安静跳过,不报错、不虚报注册', async () => {
|
||||
const { module } = await loadClient()
|
||||
const ctx = fakeCtx()
|
||||
assert.doesNotThrow(() => module.apply(ctx))
|
||||
assert.equal(ctx.menuRegistrations.length, 0)
|
||||
})
|
||||
|
||||
test('workspace 菜单按 /sansheng/state 的 current 显示已绑定或初始化文案', async () => {
|
||||
let payload = { generatedAt: 1, current: { id: 'prj-1', name: '示例项目' }, projects: [] }
|
||||
const calls = []
|
||||
const fetch = async (url, options) => {
|
||||
calls.push({ url, options })
|
||||
return { ok: true, status: 200, json: async () => payload }
|
||||
}
|
||||
const { module } = await loadClient({ fetch })
|
||||
const ctx = fakeCtx({ contextMenus: true })
|
||||
module.apply(ctx)
|
||||
const workspaceMenu = ctx.menuRegistrations.find(item => item.target === 'workspace')
|
||||
|
||||
const bound = await workspaceMenu.resolve({ workspaceId: 'ws-1', path: 'C:\\work\\a', displayTitle: 'A' })
|
||||
assert.equal(bound[0].label, '三省六部')
|
||||
assert.match(calls[0].url, /^\/sansheng\/state\?workspaceId=ws-1$/)
|
||||
|
||||
payload = { generatedAt: 2, current: null, projects: [] }
|
||||
const unbound = await workspaceMenu.resolve({ workspaceId: 'ws-2', path: 'C:\\work\\b', displayTitle: 'B' })
|
||||
assert.equal(unbound[0].label, '初始化三省六部')
|
||||
})
|
||||
|
||||
test('workspace 菜单 run 打开项目第一个会话并展开右栏', async () => {
|
||||
const opened = []
|
||||
const fetch = async () => ({ ok: true, status: 200, json: async () => ({ generatedAt: 1, current: { id: 'prj-1' }, projects: [] }) })
|
||||
const { module } = await loadClient({ fetch })
|
||||
const ctx = fakeCtx({
|
||||
contextMenus: true,
|
||||
workspaces: { items: [{ workspaceId: 'ws-1', sessionIds: ['sess-w'] }] },
|
||||
uiWorkspace: { openSession(sessionId) { opened.push(sessionId) } },
|
||||
})
|
||||
module.apply(ctx)
|
||||
const workspaceMenu = ctx.menuRegistrations.find(item => item.target === 'workspace')
|
||||
const items = await workspaceMenu.resolve({ workspaceId: 'ws-1', path: 'C:\\work', displayTitle: 'A' })
|
||||
items[0].run()
|
||||
await flush()
|
||||
assert.deepEqual(opened, ['sess-w'])
|
||||
assert.deepEqual(ctx.services.sidebarRight.opened, ['sess-w', 'sansheng-roles'])
|
||||
})
|
||||
|
||||
test('空项目 openWorkbench 通过 startSession 新建会话后再展开右栏', async () => {
|
||||
const opened = []
|
||||
const workspace = { workspaceId: 'ws-empty', sessionIds: [] }
|
||||
const { module } = await loadClient()
|
||||
const ctx = fakeCtx({
|
||||
workspaces: { items: [workspace] },
|
||||
uiWorkspace: {
|
||||
selection: { getSnapshot: () => ({ sessionId: 'sess-old-other-workspace' }) },
|
||||
startSession(workspaceId) { workspace.sessionIds.push('sess-new') },
|
||||
openSession(sessionId) { opened.push(sessionId) },
|
||||
},
|
||||
})
|
||||
const result = await module.__test.openWorkbench(ctx, 'ws-empty')
|
||||
assert.equal(result.ok, true)
|
||||
assert.deepEqual(opened, ['sess-new'])
|
||||
assert.deepEqual(ctx.services.sidebarRight.opened, ['sess-new', 'sansheng-roles'])
|
||||
})
|
||||
|
||||
test('轮询请求带 workspaceId 与 sessionId,断连时保留上次数据并显示上次状态', async () => {
|
||||
const ctx = fakeCtx({
|
||||
workspaces: { items: [{ workspaceId: 'ws-9', sessionIds: ['sess-9'] }] },
|
||||
sessions: { byId: { 'sess-9': { id: 'sess-9', retainedBy: { mainView: 1 } } } },
|
||||
})
|
||||
const calls = []
|
||||
let failing = false
|
||||
const payload = { generatedAt: 1, current: { id: 'prj-9', name: 'A', phase: '执行中' }, projects: [] }
|
||||
const fetch = async url => {
|
||||
calls.push(url)
|
||||
if (failing) throw new Error('网络断了')
|
||||
return { ok: true, status: 200, json: async () => payload }
|
||||
}
|
||||
const states = []
|
||||
const poller = (await loadClient()).module.__test.createStatePoller({
|
||||
ctx,
|
||||
fetchImpl: fetch,
|
||||
onChange: state => states.push(state),
|
||||
intervalMs: 60000,
|
||||
})
|
||||
poller.start()
|
||||
await flush()
|
||||
assert.equal(calls.length, 1)
|
||||
assert.equal(calls[0], '/sansheng/state?workspaceId=ws-9&sessionId=sess-9')
|
||||
assert.equal(states.at(-1).data.current.name, 'A')
|
||||
|
||||
failing = true
|
||||
poller.refresh()
|
||||
await flush()
|
||||
const last = states.at(-1)
|
||||
assert.equal(last.data.current.name, 'A', '断连不丢上次数据')
|
||||
assert.match(last.error, /网络断了/)
|
||||
assert.equal(last.updatedAt > 0, true)
|
||||
poller.stop()
|
||||
})
|
||||
|
||||
test('旧缓存错误提示文案明确显示“连接中断 · 显示上次状态”', async () => {
|
||||
const { module } = await loadClient()
|
||||
const project = projectFixture()
|
||||
const tree = module.__test.RolesView({
|
||||
ctx: fakeCtx(),
|
||||
data: { current: project, projects: [project] },
|
||||
error: 'HTTP 500',
|
||||
loading: false,
|
||||
updatedAt: Date.now() - 5000,
|
||||
context: { workspaceId: 'ws-1', sessionId: 'sess-1' },
|
||||
activeId: '',
|
||||
onPick: () => {},
|
||||
onRefresh: () => {},
|
||||
})
|
||||
const text = textOf(tree)
|
||||
assert.match(text, /连接中断 · 显示上次状态/)
|
||||
assert.match(text, /HTTP 500/)
|
||||
})
|
||||
|
||||
test('项目配置默认折叠(details 无 open 属性),且历史审查最多 5 条', async () => {
|
||||
const { module } = await loadClient()
|
||||
const project = projectFixture({
|
||||
reviewsHistory: Array.from({ length: 7 }, (_, index) => ({
|
||||
id: 'rev-' + index,
|
||||
kind: index % 2 === 0 ? 'stage' : 'goal',
|
||||
verdict: 'pass',
|
||||
reviewerRole: 'shangshu',
|
||||
at: 1000 + index,
|
||||
})),
|
||||
})
|
||||
const tree = module.__test.RolesView({
|
||||
ctx: fakeCtx(),
|
||||
data: { current: project, projects: [project] },
|
||||
error: null,
|
||||
loading: false,
|
||||
updatedAt: Date.now(),
|
||||
context: { workspaceId: 'ws-1', sessionId: 'sess-1' },
|
||||
activeId: '',
|
||||
onPick: () => {},
|
||||
onRefresh: () => {},
|
||||
})
|
||||
const configNode = findAll(tree, node => node.type === module.__test.ConfigPanel)[0]
|
||||
assert.ok(configNode, '渲染项目配置')
|
||||
const configTree = configNode.type(configNode.props)
|
||||
const configDetails = findAll(configTree, node => node.type === 'details')
|
||||
assert.equal(configDetails.length, 1)
|
||||
assert.equal(configDetails[0].props.open, undefined, '配置表单默认收起')
|
||||
assert.match(textOf(configTree), /项目配置/)
|
||||
|
||||
const historyNode = findAll(tree, node => node.type === module.__test.HistoryPanel)[0]
|
||||
assert.ok(historyNode)
|
||||
const historyTree = historyNode.type(historyNode.props)
|
||||
const historyDetails = findAll(historyTree, node => node.type === 'details')
|
||||
assert.equal(historyDetails[0].props.open, undefined, '历史审查默认收起')
|
||||
const items = findAll(historyTree, node => node.props && node.props.className === 'ss-history-item')
|
||||
assert.equal(items.length, 5, '最多列 5 条历史审查')
|
||||
})
|
||||
|
||||
test('角色卡可点击打开真实会话;缺会话显示“会话缺失,点此修复”和原因', async () => {
|
||||
const { module } = await loadClient()
|
||||
const opened = []
|
||||
const toasts = []
|
||||
const ctx = fakeCtx({ uiWorkspace: { openSession(sessionId) { opened.push(sessionId) } }, toast: text => toasts.push(text) })
|
||||
const project = projectFixture()
|
||||
const tree = module.__test.RoleCard({ ctx, project, card: project.roles[0] })
|
||||
tree.props.onClick()
|
||||
assert.deepEqual(opened, ['sess-lead'])
|
||||
|
||||
const missing = module.__test.RoleCard({
|
||||
ctx,
|
||||
project,
|
||||
card: { role: 'shangshu', label: '尚书', name: '尚书 Bot', model: 'm', line: '状态', detail: '', tone: 'warn', exists: true, sessionId: null, reason: '绑定会话已被删除' },
|
||||
})
|
||||
const text = textOf(missing)
|
||||
assert.match(text, /会话缺失,点此修复/)
|
||||
assert.match(text, /绑定会话已被删除/)
|
||||
const repair = findAll(missing, node => node.props && node.props.className === 'ss-repair')[0]
|
||||
repair.props.onClick({ stopPropagation() {} })
|
||||
assert.equal(toasts.length, 1)
|
||||
assert.match(toasts[0], /绑定会话已被删除/)
|
||||
})
|
||||
|
||||
test('配置保存 POST body 只含 projectId 与三个模型;isStale 丢弃旧请求', async () => {
|
||||
const calls = []
|
||||
const fetch = async (url, options) => {
|
||||
calls.push({ url, options })
|
||||
return { ok: true, status: 200, json: async () => ({}) }
|
||||
}
|
||||
const { module } = await loadClient({ fetch })
|
||||
const project = projectFixture()
|
||||
const tree = module.__test.ConfigPanel({ ctx: fakeCtx(), project, onRefresh: () => {} })
|
||||
const form = findAll(tree, node => node.type === 'form')[0]
|
||||
await form.props.onSubmit({ preventDefault() {} })
|
||||
assert.equal(calls[0].url, '/sansheng/config')
|
||||
assert.equal(calls[0].options.method, 'POST')
|
||||
const body = JSON.parse(calls[0].options.body)
|
||||
assert.deepEqual(body, {
|
||||
projectId: 'prj-1',
|
||||
models: { lead: 'model-lead', shangshu: 'model-shang', gongbu: 'model-gong' },
|
||||
})
|
||||
|
||||
assert.equal(module.__test.isStale(1, 2), true)
|
||||
assert.equal(module.__test.isStale(2, 2), false)
|
||||
assert.equal(module.__test.stateUrlOf({ workspaceId: 'ws-1', sessionId: 'sess-1' }), '/sansheng/state?workspaceId=ws-1&sessionId=sess-1')
|
||||
})
|
||||
|
||||
test('初始化项目提交 POST /sansheng/provision 且 body 含 workspaceId/path/name/models', async () => {
|
||||
const calls = []
|
||||
const fetch = async (url, options) => {
|
||||
calls.push({ url, options })
|
||||
return { ok: true, status: 200, json: async () => ({ project: { id: 'prj-new' } }) }
|
||||
}
|
||||
const { module } = await loadClient({ fetch })
|
||||
const tree = module.__test.InitPanel({
|
||||
ctx: fakeCtx(),
|
||||
context: { workspaceId: 'ws-new', path: 'C:\\work\\new', displayTitle: '新项目' },
|
||||
onDone: () => {},
|
||||
})
|
||||
const form = findAll(tree, node => node.type === 'form')[0]
|
||||
await form.props.onSubmit({ preventDefault() {} })
|
||||
assert.equal(calls[0].url, '/sansheng/provision')
|
||||
const body = JSON.parse(calls[0].options.body)
|
||||
assert.deepEqual(body, { workspaceId: 'ws-new', path: 'C:\\work\\new', name: '新项目', models: {} })
|
||||
const text = textOf(tree)
|
||||
assert.match(text, /此项目尚未初始化/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,172 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { installObserver } from '../src/observe.js'
|
||||
import { newBootId } from '../src/records.js'
|
||||
import { SanshengStore } from '../src/store.js'
|
||||
|
||||
async function tempStore() {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-dispatch-'))
|
||||
const store = new SanshengStore(join(dir, 'state.json'))
|
||||
await store.load()
|
||||
return { dir, store, cleanup: () => rm(dir, { recursive: true, force: true }) }
|
||||
}
|
||||
|
||||
const PROJECT = {
|
||||
id: 'prj-dispatch',
|
||||
name: '派发项目',
|
||||
roomId: 'room-1',
|
||||
bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' },
|
||||
maxReworks: 3,
|
||||
}
|
||||
|
||||
function goalAt({ revision = 4, reworks = 0 } = {}) {
|
||||
return {
|
||||
id: 'goal-1',
|
||||
revision,
|
||||
status: 'active',
|
||||
current: 0,
|
||||
objective: '交付',
|
||||
acceptance: '测试',
|
||||
constraints: [],
|
||||
stages: [{
|
||||
id: 's1', title: '阶段一', acceptance: '能跑', status: 'active', reworks,
|
||||
tasks: [{ id: 't1', botId: 'b-gong', task: '做', status: 'done', note: '' }],
|
||||
feedback: '缺测试',
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
function fakeEnv({ goal = goalAt(), deliver } = {}) {
|
||||
const room = {
|
||||
id: 'room-1', name: '派发项目 · 三省六部', admin: 'b-shang',
|
||||
members: ['b-lead', 'b-shang', 'b-gong'],
|
||||
sessions: { 'b-gong': 'sess-gong' },
|
||||
goal,
|
||||
}
|
||||
const bots = {
|
||||
'b-lead': { id: 'b-lead', name: '丞相' },
|
||||
'b-shang': { id: 'b-shang', name: '尚书' },
|
||||
'b-gong': { id: 'b-gong', name: '工部' },
|
||||
}
|
||||
const dsbot = {
|
||||
selfOf: id => (id === 'sess-shang' ? 'b-shang' : undefined),
|
||||
roomOfSession: id => (id === 'sess-shang' ? 'room-1' : undefined),
|
||||
roomOf: () => room,
|
||||
botOf: id => bots[id],
|
||||
isMain: () => false,
|
||||
pickRoom: () => ({ error: 'no room' }),
|
||||
}
|
||||
const calls = []
|
||||
const rt = {
|
||||
deliver: async payload => {
|
||||
calls.push(payload)
|
||||
if (deliver) await deliver(payload)
|
||||
},
|
||||
}
|
||||
const ctx = { handlers: {}, on(event, handler) { this.handlers[event] = handler }, get() { return rt } }
|
||||
return { room, dsbot, ctx, calls }
|
||||
}
|
||||
|
||||
const exec = { name: 'group_goal', arguments: { action: 'rework', reason: '缺测试' }, agent: { id: 'sess-shang' } }
|
||||
|
||||
test('R01:业务拒绝字符串不记 confirmed,也不触发返工投递', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
const { dsbot, ctx, calls } = fakeEnv({ goal: goalAt() })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
const result = await ctx.handlers['tools/execute'](exec, async () => ({
|
||||
content: [{ type: 'text', text: 'Only 尚书, the admin of "派发项目", or a Main Bot changes its goal.' }],
|
||||
}))
|
||||
assert.match(result.content[0].text, /Only 尚书/)
|
||||
const record = store.peek().dispatches.at(-1)
|
||||
assert.equal(record.status, 'rejected', '业务拒绝不能当成功')
|
||||
assert.match(record.nativeResult.text, /Only 尚书/)
|
||||
assert.equal(calls.length, 0, '业务拒绝不触发返工')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('R02:同 requestId 同 payload 重放不重复写,不同 payload 拒绝', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
const base = { id: 'dsp-1', requestId: 'req-1', payloadDigest: 'aaa', projectId: PROJECT.id, action: 'pass' }
|
||||
const first = await store.beginDispatch(base)
|
||||
assert.equal(first.replay, false)
|
||||
const second = await store.beginDispatch({ ...base, id: 'dsp-2' })
|
||||
assert.equal(second.replay, true)
|
||||
assert.equal(second.record.id, 'dsp-1')
|
||||
assert.equal(store.peek().dispatches.length, 1)
|
||||
await assert.rejects(
|
||||
() => store.beginDispatch({ ...base, id: 'dsp-3', payloadDigest: 'bbb' }),
|
||||
error => error.code === 'payload-conflict',
|
||||
)
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('R03:发送中重启后标为 unknown,已确认记录不被改写', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
await store.beginDispatch({ id: 'dsp-1', requestId: 'req-1', payloadDigest: 'a', projectId: PROJECT.id, action: 'pass' })
|
||||
await store.markDispatchInFlight('dsp-1')
|
||||
await store.beginDispatch({ id: 'dsp-2', requestId: 'req-2', payloadDigest: 'b', projectId: PROJECT.id, action: 'pass' })
|
||||
await store.finishDispatch('dsp-2', { status: 'confirmed' })
|
||||
const marked = await store.reconcileDispatches('boot-x')
|
||||
assert.equal(marked, 1)
|
||||
assert.equal(store.peek().dispatches.find(item => item.id === 'dsp-1').status, 'unknown')
|
||||
assert.equal(store.peek().dispatches.find(item => item.id === 'dsp-2').status, 'confirmed')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('R05:同一返工版本重复观测只投递一次', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
const before = goalAt({ revision: 4, reworks: 0 })
|
||||
const { dsbot, ctx, calls } = fakeEnv({ goal: before })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
const run = async () => {
|
||||
dsbot.roomOf().goal = goalAt({ revision: 4, reworks: 0 })
|
||||
return ctx.handlers['tools/execute'](exec, async () => {
|
||||
dsbot.roomOf().goal = goalAt({ revision: 5, reworks: 1 })
|
||||
return { content: [{ type: 'text', text: '已驳回' }] }
|
||||
})
|
||||
}
|
||||
await run()
|
||||
// 第二次模拟同一次返工回执重放:同样的目标版本与结果
|
||||
await run()
|
||||
assert.equal(calls.length, 1, '重复回执不能再次投递')
|
||||
assert.equal(store.reworksFor(PROJECT.id).length, 1)
|
||||
const auto = store.peek().dispatches.filter(item => item.action === 'auto_rework')
|
||||
assert.equal(auto.length, 1, '同一返工版本只应有一条派发记录')
|
||||
assert.equal(auto[0].status, 'confirmed')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('R04:事务失败回滚内存状态,不留下虚假成功', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
const project = { ...PROJECT }
|
||||
await store.saveProject(project)
|
||||
await assert.rejects(
|
||||
() => store.saveProject({ ...project, id: 'prj-other', name: '另一个', roomId: 'room-other' }),
|
||||
error => error.code === 'bot-taken',
|
||||
)
|
||||
assert.equal(Object.keys(store.peek().projects).length, 1)
|
||||
assert.equal(store.projectById('prj-other'), undefined)
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
|
@ -50,12 +50,36 @@ test('会话与群成员可反查,且能按名字选群', async () => {
|
|||
assert.equal(dsbot.roomsOfBot('bot-gong').length, 1)
|
||||
assert.equal(dsbot.pickRoom('bot-gong', '示例 · 三省六部').room.id, 'room-1')
|
||||
assert.equal(dsbot.pickRoom('bot-gong', 'room-1').room.id, 'room-1')
|
||||
assert.equal(dsbot.pickRoom('bot-gong', '「示例 · 三省六部」').room.id, 'room-1', '带引号群名与原生解析一致')
|
||||
assert.equal(dsbot.pickRoom('bot-gong', '"示例 · 三省六部"').room.id, 'room-1')
|
||||
assert.match(dsbot.pickRoom('bot-gong', '不存在').error, /不在名为/)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('Main Bot 可解析自己不在其中的群(与原生可见性一致)', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-state-'))
|
||||
try {
|
||||
const file = join(dir, 'state.json')
|
||||
const other = {
|
||||
...state,
|
||||
rooms: {
|
||||
...state.rooms,
|
||||
'room-2': { id: 'room-2', name: '其他项目群', members: ['bot-shang'], admin: 'bot-shang', sessions: {} },
|
||||
},
|
||||
}
|
||||
await writeFile(file, JSON.stringify(other), 'utf8')
|
||||
const dsbot = new DsBotState(file)
|
||||
assert.equal(dsbot.pickRoom('bot-lead', '其他项目群').room.id, 'room-2')
|
||||
assert.match(dsbot.pickRoom('bot-gong', '其他项目群').error, /不在名为/)
|
||||
assert.equal(dsbot.isBotSession('sess-shang'), true)
|
||||
assert.equal(dsbot.isBotSession('user-random'), false)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('文件不存在时返回空快照而非抛错', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-state-'))
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,118 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { installGates } from '../src/gates.js'
|
||||
|
||||
function makeCtx() {
|
||||
const guards = []
|
||||
return {
|
||||
tools: { guard(fn) { guards.push(fn); return () => {} } },
|
||||
guards,
|
||||
}
|
||||
}
|
||||
|
||||
function makeStore(overrides = {}) {
|
||||
const project = {
|
||||
id: 'prj-1', name: '项目A', roomId: 'room-1',
|
||||
bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' }, maxReworks: 3,
|
||||
}
|
||||
return {
|
||||
peek: () => ({ reviews: [], reworks: [], projects: { 'prj-1': project }, artifacts: {} }),
|
||||
projectByRoom: roomId => (roomId === 'room-1' ? project : undefined),
|
||||
projectsByBot: botId => (botId === 'b-shang' ? [project] : []),
|
||||
projectByBot: botId => (botId === 'b-shang' ? project : undefined),
|
||||
registryProjectForBot: () => 'prj-1',
|
||||
registryProjectForRoom: roomId => (roomId === 'room-1' ? 'prj-1' : undefined),
|
||||
health: () => ({ status: 'ok' }),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeDsbot({ selfOf = id => (id === 'sess-shang' ? 'b-shang' : undefined), roomOfSession = () => undefined, pickRoom = () => ({ error: 'not found' }), rooms = {} } = {}) {
|
||||
return {
|
||||
selfOf,
|
||||
roomOfSession,
|
||||
pickRoom,
|
||||
isMain: () => false,
|
||||
botOf: id => ({ 'b-shang': { id: 'b-shang', name: '尚书' }, 'b-lead': { id: 'b-lead', name: '丞相' }, 'b-gong': { id: 'b-gong', name: '工部' } })[id],
|
||||
roomOf: id => rooms[id],
|
||||
}
|
||||
}
|
||||
|
||||
const exec = { name: 'group_goal', arguments: { action: 'pass', group: '某个群' }, agent: { id: 'sess-shang' } }
|
||||
|
||||
test('F01:项目 Bot 指名解析不到的群时拒绝,而不是放行', () => {
|
||||
const ctx = makeCtx()
|
||||
installGates({ ctx, store: makeStore(), dsbot: makeDsbot(), isBotSession: () => true })
|
||||
const reason = ctx.guards[0](exec)
|
||||
assert.equal(typeof reason, 'string')
|
||||
assert.match(reason, /无法解析群/)
|
||||
})
|
||||
|
||||
test('Bot 会话身份过期(unknown)时拒绝,不按用户放行', () => {
|
||||
const ctx = makeCtx()
|
||||
installGates({
|
||||
ctx,
|
||||
store: makeStore(),
|
||||
dsbot: makeDsbot({ selfOf: () => undefined }),
|
||||
isBotSession: () => true,
|
||||
})
|
||||
const reason = ctx.guards[0]({ ...exec, arguments: { action: 'pass' } })
|
||||
assert.equal(typeof reason, 'string')
|
||||
assert.match(reason, /找不到对应身份/)
|
||||
})
|
||||
|
||||
test('非受治理群保持原生行为(无群上下文时放行)', () => {
|
||||
const ctx = makeCtx()
|
||||
installGates({
|
||||
ctx,
|
||||
store: makeStore({ projectByRoom: () => undefined, projectsByBot: () => [], projectByBot: () => undefined, registryProjectForBot: () => undefined }),
|
||||
dsbot: makeDsbot({ selfOf: id => (id === 'sess-main' ? 'b-main' : undefined) }),
|
||||
isBotSession: () => true,
|
||||
})
|
||||
const reason = ctx.guards[0]({ name: 'group_goal', arguments: { action: 'pass' }, agent: { id: 'sess-main' } })
|
||||
assert.equal(reason, undefined)
|
||||
})
|
||||
|
||||
test('G07:主状态损坏但 registry 证明群受治理时拒绝', () => {
|
||||
const ctx = makeCtx()
|
||||
const store = makeStore({
|
||||
health: () => ({ status: 'broken', error: '坏文件' }),
|
||||
projectByRoom: () => undefined,
|
||||
peek: () => ({ reviews: [], reworks: [], projects: {}, artifacts: {} }),
|
||||
})
|
||||
installGates({
|
||||
ctx,
|
||||
store,
|
||||
dsbot: makeDsbot({ roomOfSession: () => 'room-1', rooms: { 'room-1': { id: 'room-1', name: '群', members: ['b-shang'], admin: 'b-shang' } } }),
|
||||
isBotSession: () => true,
|
||||
})
|
||||
const reason = ctx.guards[0]({ name: 'group_goal', arguments: { action: 'pass' }, agent: { id: 'sess-shang' } })
|
||||
assert.equal(typeof reason, 'string')
|
||||
assert.match(reason, /治理状态不可读/)
|
||||
})
|
||||
|
||||
test('跨项目:A 的 Bot 在 B 的群里操作被拒绝', () => {
|
||||
const ctx = makeCtx()
|
||||
const projectA = { id: 'prj-a', name: 'A', roomId: 'room-a', bots: { shangshu: 'b-shang' }, maxReworks: 3 }
|
||||
const projectB = { id: 'prj-b', name: 'B', roomId: 'room-b', bots: { shangshu: 'b-other' }, maxReworks: 3 }
|
||||
const store = {
|
||||
peek: () => ({ reviews: [], reworks: [], projects: { a: projectA, b: projectB }, artifacts: {} }),
|
||||
projectByRoom: roomId => (roomId === 'room-b' ? projectB : undefined),
|
||||
projectsByBot: () => [projectA],
|
||||
projectByBot: () => projectA,
|
||||
registryProjectForBot: () => 'prj-a',
|
||||
health: () => ({ status: 'ok' }),
|
||||
}
|
||||
installGates({
|
||||
ctx,
|
||||
store,
|
||||
dsbot: makeDsbot({
|
||||
roomOfSession: () => 'room-b',
|
||||
rooms: { 'room-b': { id: 'room-b', name: 'B 群', members: ['b-other'], admin: 'b-other' } },
|
||||
}),
|
||||
isBotSession: () => true,
|
||||
})
|
||||
const reason = ctx.guards[0]({ name: 'group_goal', arguments: { action: 'pass' }, agent: { id: 'sess-shang' } })
|
||||
assert.equal(typeof reason, 'string')
|
||||
assert.match(reason, /不能修改项目「B」的目标/)
|
||||
})
|
||||
|
|
@ -132,13 +132,12 @@ test('尚书通过阶段前必须有同一版本的阶段审查', () => {
|
|||
assert.equal(ok.allow, true)
|
||||
})
|
||||
|
||||
test('审查记录版本过期后失效', () => {
|
||||
test('账本 revision 增长但审查对象未变时,审查仍有效(A05 无死锁)', () => {
|
||||
const goal = makeGoal()
|
||||
const stale = stageReview(goal, 1, 'pass')
|
||||
const valid = stageReview(goal, 1, 'pass')
|
||||
goal.revision = 6
|
||||
const result = decide({ goal, reviews: [stale] })
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'no-stage-review')
|
||||
const result = decide({ goal, reviews: [valid] })
|
||||
assert.equal(result.allow, true)
|
||||
})
|
||||
|
||||
test('审查后任务状态变了也算证据过期', () => {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,299 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { apply } from '../index.js'
|
||||
import { installGovernance } from '../src/governance.js'
|
||||
import { resolveActor } from '../src/identity.js'
|
||||
import { SanshengStore, SanshengStoreError } from '../src/store.js'
|
||||
|
||||
function fakeCtx(services = {}) {
|
||||
const tools = []
|
||||
const provided = {}
|
||||
return {
|
||||
tools: {
|
||||
register(def) { tools.push(def); return () => {} },
|
||||
guard() { return () => {} },
|
||||
},
|
||||
on() { return () => {} },
|
||||
effect(fn) { return typeof fn === 'function' ? fn() : undefined },
|
||||
get(name, fallback) { return services[name] ?? fallback },
|
||||
provide(name, value) { provided[name] = value },
|
||||
toolsList: tools,
|
||||
provided,
|
||||
}
|
||||
}
|
||||
|
||||
function fakeRuntime() {
|
||||
const calls = { bots: [], rooms: [], deletedBots: [], deletedRooms: [], updated: [] }
|
||||
const bots = new Map()
|
||||
const rooms = new Map()
|
||||
let counter = 0
|
||||
const rt = {
|
||||
async load() {},
|
||||
findBot(ref) {
|
||||
if (bots.has(ref)) return bots.get(ref)
|
||||
return [...bots.values()].find(bot => bot.name === ref)
|
||||
},
|
||||
async resolveModel(ref) {
|
||||
if (ref === 'bad') throw new Error('模型不存在')
|
||||
return ref
|
||||
},
|
||||
async createBot(options) {
|
||||
if ([...bots.values()].some(bot => bot.name === options.name)) throw new Error(`A Bot named ${options.name} already exists`)
|
||||
counter += 1
|
||||
const bot = { id: `bot-${counter}`, name: options.name, model: options.model, sessionId: `sess-${counter}` }
|
||||
bots.set(bot.id, bot)
|
||||
calls.bots.push({ ...options, id: bot.id })
|
||||
return bot
|
||||
},
|
||||
botOf(id) { return bots.get(id) },
|
||||
async updateBot(id, patch) {
|
||||
const bot = bots.get(id)
|
||||
if (!bot) throw new Error('Unknown Bot')
|
||||
Object.assign(bot, patch)
|
||||
calls.updated.push({ id, patch })
|
||||
return bot
|
||||
},
|
||||
async deleteBot(id) {
|
||||
calls.deletedBots.push(id)
|
||||
bots.delete(id)
|
||||
},
|
||||
async createRoom(options) {
|
||||
const room = { id: `room-${rooms.size + 1}`, name: options.name, members: options.members, admin: options.admin, sessions: {}, goal: undefined }
|
||||
rooms.set(room.id, room)
|
||||
calls.rooms.push(options)
|
||||
return room
|
||||
},
|
||||
async deleteRoom(id) {
|
||||
calls.deletedRooms.push(id)
|
||||
rooms.delete(id)
|
||||
},
|
||||
goalControl: async () => ({}),
|
||||
}
|
||||
return { rt, calls, bots, rooms }
|
||||
}
|
||||
|
||||
async function setup() {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-isolation-'))
|
||||
const { rt, calls, bots, rooms } = fakeRuntime()
|
||||
const ctx = fakeCtx({ 'dsbot-runtime': rt })
|
||||
const statePath = join(dir, 'state.json')
|
||||
const dsbotStatePath = join(dir, 'bot-state.json')
|
||||
await apply(ctx, { statePath, dsbotStatePath })
|
||||
const tool = name => ctx.toolsList.find(def => def.name === name)
|
||||
const store = new SanshengStore(statePath)
|
||||
await store.load()
|
||||
const env = {
|
||||
dir, rt, calls, bots, rooms, ctx, tool, store, statePath, dsbotStatePath,
|
||||
reload: async () => {
|
||||
const next = new SanshengStore(statePath)
|
||||
await next.load()
|
||||
env.store = next
|
||||
return next
|
||||
},
|
||||
cleanup: () => rm(dir, { recursive: true, force: true }),
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
const userExec = { agent: { id: 'user-session' } }
|
||||
|
||||
test('I01:连续创建 A/B 默认参数均成功,Bot 名唯一且角色独立', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
const a = await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||||
const b = await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||||
await env.reload()
|
||||
assert.match(a, /已创建项目「项目A」/)
|
||||
assert.match(b, /已创建项目「项目B」/)
|
||||
|
||||
const namesA = env.calls.bots.slice(0, 3).map(bot => bot.name)
|
||||
const namesB = env.calls.bots.slice(3, 6).map(bot => bot.name)
|
||||
assert.equal(new Set([...namesA, ...namesB]).size, 6, '六个 Bot 名必须全局唯一')
|
||||
assert.notDeepEqual(namesA, namesB)
|
||||
|
||||
const projects = Object.values(env.store.peek().projects)
|
||||
assert.equal(projects.length, 2)
|
||||
const botIds = projects.flatMap(project => Object.values(project.bots))
|
||||
assert.equal(new Set(botIds).size, 6, '两个项目不共享角色 Bot')
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('I02:把 A 的尚书绑到 B 所在的群明确拒绝', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||||
await env.reload()
|
||||
const projectA = Object.values(env.store.peek().projects)[0]
|
||||
// 手工造一个群:成员是 A 的三个 Bot,管理员是 A 的尚书
|
||||
const room = await env.rt.createRoom({
|
||||
name: '另一个群', members: Object.values(projectA.bots), admin: projectA.bots.shangshu,
|
||||
})
|
||||
const botState = {
|
||||
version: 1,
|
||||
mainBotIds: [],
|
||||
bots: Object.fromEntries(Object.entries(projectA.bots).map(([role, id]) => [id, { id, name: env.bots.get(id)?.name ?? role, role }])),
|
||||
rooms: { [room.id]: { id: room.id, name: room.name, members: Object.values(projectA.bots), admin: projectA.bots.shangshu, sessions: {} } },
|
||||
}
|
||||
const { writeFile } = await import('node:fs/promises')
|
||||
await writeFile(env.dsbotStatePath, JSON.stringify(botState), 'utf8')
|
||||
const result = await env.tool('sansheng_bind').execute({
|
||||
project: '项目B', room: room.id,
|
||||
lead: projectA.bots.lead, shangshu: projectA.bots.shangshu, gongbu: projectA.bots.gongbu,
|
||||
}, userExec)
|
||||
assert.match(result, /已属于项目|只能属于一个项目/)
|
||||
assert.equal(Object.values(env.store.peek().projects).length, 1, '不能产生半绑定')
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('I03:显式 project 与 Bot 所属项目冲突时拒绝', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||||
await env.reload()
|
||||
const [a, b] = Object.values(env.store.peek().projects)
|
||||
// 让 A 的尚书会话记录审查,但显式要求写到 B
|
||||
const room = { goal: { id: 'goal-1', revision: 1, status: 'active', stages: [] } }
|
||||
const dsbot = {
|
||||
botOf: id => ({ name: id }),
|
||||
roomOf: id => (id === a.roomId ? room : undefined),
|
||||
roomOfSession: () => a.roomId,
|
||||
selfOf: () => a.bots.shangshu,
|
||||
isMain: () => false,
|
||||
}
|
||||
const fakeStore = {
|
||||
...env.store,
|
||||
projectsByBot: id => (id === a.bots.shangshu ? [a] : []),
|
||||
projectByBot: id => (id === a.bots.shangshu ? a : undefined),
|
||||
projectByRoom: id => (id === a.roomId ? a : id === b.roomId ? b : undefined),
|
||||
peek: () => ({ reviews: [], artifacts: {}, projects: { [a.id]: a, [b.id]: b }, reworks: [] }),
|
||||
resolveProject: ref => (ref === b.name ? b : ref === a.name ? a : undefined),
|
||||
}
|
||||
const actor = resolveActor({ dsbot, store: fakeStore, sessionId: 'sess-shang', isBotSession: () => true })
|
||||
assert.equal(actor.project.id, a.id)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('I03b:A 的尚书显式指定项目 B 记录审查时拒绝,不落 B 的记录', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||||
await env.reload()
|
||||
const [a, b] = Object.values(env.store.peek().projects)
|
||||
const goal = { id: 'goal-a', revision: 3, status: 'active', current: 0, objective: 'A', acceptance: 'A', constraints: [], stages: [{ id: 's1', title: '一', acceptance: 'x', status: 'active', tasks: [] }] }
|
||||
// 让插件内的 DsBotState 看到 A 的群与尚书会话
|
||||
const { writeFile } = await import('node:fs/promises')
|
||||
await writeFile(env.dsbotStatePath, JSON.stringify({
|
||||
version: 1,
|
||||
mainBotIds: [],
|
||||
bots: Object.fromEntries(Object.entries(a.bots).map(([role, id]) => [id, { id, name: env.bots.get(id)?.name ?? role, role, sessionId: role === 'shangshu' ? 'sess-a-shang' : `sess-${role}` }])),
|
||||
rooms: { [a.roomId]: { id: a.roomId, name: 'A 群', members: Object.values(a.bots), admin: a.bots.shangshu, sessions: {}, goal } },
|
||||
}), 'utf8')
|
||||
const result = await env.tool('sansheng_review').execute(
|
||||
{ action: 'stage_pass', project: b.id, stage: 1, evidence: '测试' },
|
||||
{ agent: { id: 'sess-a-shang' } },
|
||||
)
|
||||
assert.match(result, /项目冲突|不能跨项目/)
|
||||
assert.equal(env.store.peek().reviews.length, 0, '不能把 A 的审查写进 B')
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Store 层拒绝重复 Bot/重复群绑定', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
const project = {
|
||||
id: 'prj-1', name: 'A', roomId: 'room-1',
|
||||
bots: { lead: 'b1', shangshu: 'b2', gongbu: 'b3' }, maxReworks: 3,
|
||||
}
|
||||
await env.store.saveProject(project)
|
||||
await assert.rejects(
|
||||
() => env.store.saveProject({ ...project, id: 'prj-2', name: 'B' }),
|
||||
error => error instanceof SanshengStoreError && error.code === 'room-taken',
|
||||
)
|
||||
await assert.rejects(
|
||||
() => env.store.saveProject({ ...project, id: 'prj-3', name: 'C', roomId: 'room-3' }),
|
||||
error => error instanceof SanshengStoreError && error.code === 'bot-taken',
|
||||
)
|
||||
await assert.rejects(
|
||||
() => env.store.saveProject({ ...project, id: 'prj-4', name: 'D', roomId: 'room-4', bots: { lead: 'x', shangshu: 'x', gongbu: 'y' } }),
|
||||
error => error instanceof SanshengStoreError && error.code === 'roles-duplicated',
|
||||
)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('I04:修改 A 模型配置只更新 A 的 Bot 与绑定', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||||
await env.reload()
|
||||
const [a, b] = Object.values(env.store.peek().projects)
|
||||
const result = await env.tool('sansheng_config').execute({
|
||||
project: a.id, models: { lead: 'magpie/new-lead' },
|
||||
}, userExec)
|
||||
assert.match(result, /已更新项目/)
|
||||
const updatedIds = env.calls.updated.map(item => item.id)
|
||||
assert.deepEqual(updatedIds, [a.bots.lead], '只更新 A 的丞相 Bot')
|
||||
const reloaded = new SanshengStore(env.statePath)
|
||||
await reloaded.load()
|
||||
assert.equal(reloaded.projectById(a.id).models.lead, 'magpie/new-lead')
|
||||
assert.equal(reloaded.projectById(b.id).models.lead, undefined)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('I05/I06:治理服务拒绝跨项目投递与 team 记忆', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||||
await env.tool('sansheng_provision').execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||||
await env.reload()
|
||||
const [a, b] = Object.values(env.store.peek().projects)
|
||||
const gov = installGovernance({ ctx: env.ctx, store: env.store })
|
||||
assert.equal(gov.checkDelivery({ fromId: a.bots.shangshu, toId: b.bots.gongbu }).allow, false)
|
||||
assert.equal(gov.checkDelivery({ fromId: a.bots.shangshu, toId: a.bots.gongbu }).allow, true)
|
||||
assert.equal(gov.checkDelivery({ fromId: a.bots.shangshu, toId: 'bot-outsider' }).allow, false)
|
||||
assert.equal(gov.checkDelivery({ fromId: b.bots.lead, toId: a.bots.gongbu, roomId: a.roomId }).allow, false)
|
||||
|
||||
assert.equal(gov.checkMemoryScope({ botId: a.bots.lead, scope: 'team' }).allow, false)
|
||||
assert.equal(gov.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: a.roomId }).allow, true)
|
||||
assert.equal(gov.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: b.roomId }).allow, false)
|
||||
assert.equal(gov.checkMemoryScope({ botId: 'bot-outsider', scope: 'team' }).allow, true)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('写租约:同项目第二个写任务被拒绝,释放后可获取', async () => {
|
||||
const env = await setup()
|
||||
try {
|
||||
await env.tool('sansheng_provision').execute({ project: '项目A', workDir: 'C:/work/a' }, userExec)
|
||||
await env.reload()
|
||||
const project = Object.values(env.store.peek().projects)[0]
|
||||
const first = await env.store.acquireLease(project.id, { holder: 'bot-gongbu', taskId: 't1' })
|
||||
assert.equal(first.ok, true)
|
||||
const second = await env.store.acquireLease(project.id, { holder: 'bot-other', taskId: 't2' })
|
||||
assert.equal(second.ok, false)
|
||||
assert.match(second.reason, /正在被/)
|
||||
await env.store.releaseLease(project.id, 'bot-gongbu')
|
||||
const third = await env.store.acquireLease(project.id, { holder: 'bot-other', taskId: 't3' })
|
||||
assert.equal(third.ok, true)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
|
@ -37,7 +37,8 @@ test('apply 注册全部工具、门禁与派发观测,并能读损坏的 DS B
|
|||
|
||||
const names = ctx.toolsList.map(def => def.name).sort()
|
||||
assert.deepEqual(names, [
|
||||
'sansheng_bind', 'sansheng_provision', 'sansheng_reconcile', 'sansheng_review', 'sansheng_status',
|
||||
'sansheng_bind', 'sansheng_config', 'sansheng_control', 'sansheng_lease',
|
||||
'sansheng_provision', 'sansheng_reconcile', 'sansheng_review', 'sansheng_status', 'sansheng_submit',
|
||||
])
|
||||
assert.equal(ctx.guards.length, 1, '装了 group_goal 门禁')
|
||||
assert.equal(typeof ctx.handlers['tools/execute'], 'function', '装了派发观测')
|
||||
|
|
@ -66,8 +67,11 @@ test('宿主提供 webServer 时注册右栏数据接口', async () => {
|
|||
statePath: join(dir, 'sansheng.json'),
|
||||
dsbotStatePath: join(dir, 'missing-bot-state.json'),
|
||||
})
|
||||
assert.equal(routes.length, 1, '注册了 /sansheng/state')
|
||||
assert.equal(routes[0].path, '/sansheng/state')
|
||||
const stateRoute = routes.find(route => route.path === '/sansheng/state')
|
||||
assert.ok(stateRoute, '注册了 /sansheng/state')
|
||||
assert.equal(stateRoute.path, '/sansheng/state')
|
||||
assert.ok(routes.some(route => route.path === '/sansheng/provision'))
|
||||
assert.ok(routes.some(route => route.path === '/sansheng/config'))
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,7 +80,7 @@ function fakeEnv({ goal = goalAt(), deliver } = {}) {
|
|||
return { room, dsbot, ctx, calls }
|
||||
}
|
||||
|
||||
test('派发记录:intent → 回执,失败记为未执行', async () => {
|
||||
test('派发记录:prepared → in_flight → 回执,业务拒绝记为 rejected', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
|
|
@ -91,7 +91,8 @@ test('派发记录:intent → 回执,失败记为未执行', async () => {
|
|||
|
||||
const result = await ctx.handlers['tools/execute'](exec, async () => {
|
||||
const last = store.peek().dispatches.at(-1)
|
||||
assert.equal(last.status, 'intent', '调用前先落意图')
|
||||
assert.equal(last.status, 'in_flight', '调用前先落意图并标记发送中')
|
||||
dsbot.roomOf().goal = goalAt({ revision: 5 })
|
||||
return { content: [{ type: 'text', text: '已通过' }] }
|
||||
})
|
||||
assert.equal(result.content[0].text, '已通过')
|
||||
|
|
@ -105,13 +106,13 @@ test('派发记录:intent → 回执,失败记为未执行', async () => {
|
|||
{ ...exec, arguments: { action: 'complete', summary: 'x', evidence: 'y' } },
|
||||
async () => ({ isError: true, content: [{ type: 'text', text: 'Error: 还有阶段未通过' }] }),
|
||||
)
|
||||
assert.equal(store.peek().dispatches.at(-1).status, 'failed')
|
||||
assert.equal(store.peek().dispatches.at(-1).status, 'rejected')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('重启对账:停在 intent 的派发标为待核实,核实后改状态且不重复', async () => {
|
||||
test('重启对账:停在 prepared 的派发标为待核实,核实后改状态且不重复', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
|
|
@ -132,7 +133,7 @@ test('重启对账:停在 intent 的派发标为待核实,核实后改状态
|
|||
await other.beginDispatch({ id: 'dsp-0002', projectId: PROJECT.id, action: 'rework' })
|
||||
await other.reconcileDispatches('boot-3')
|
||||
await other.resolveDispatch('dsp-0002', 'not-done', 'bot-shang')
|
||||
assert.equal(other.peek().dispatches.at(-1).status, 'failed')
|
||||
assert.equal(other.peek().dispatches.at(-1).status, 'rejected')
|
||||
} finally {
|
||||
await cleanupOther()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,231 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { goalDigest, reviewSubjectDigest, stageDigest } from '../src/digest.js'
|
||||
import { evaluateGoalAction } from '../src/gate.js'
|
||||
|
||||
const project = {
|
||||
id: 'prj-a',
|
||||
name: 'A 项目',
|
||||
bots: { lead: 'b-lead', shangshu: 'b-shang', gongbu: 'b-gong' },
|
||||
maxReworks: 3,
|
||||
workDir: 'C:/work/a',
|
||||
submissionSeq: 4,
|
||||
}
|
||||
|
||||
const members = [
|
||||
{ id: 'b-lead', name: '丞相', role: 'lead' },
|
||||
{ id: 'b-shang', name: '尚书', role: 'shangshu' },
|
||||
{ id: 'b-gong', name: '工部', role: 'gongbu' },
|
||||
]
|
||||
|
||||
function shangshu() {
|
||||
return { kind: 'bot', botId: 'b-shang', botName: '尚书', role: 'shangshu', isMain: false, project }
|
||||
}
|
||||
|
||||
function lead() {
|
||||
return { kind: 'bot', botId: 'b-lead', botName: '丞相', role: 'lead', isMain: false, project }
|
||||
}
|
||||
|
||||
function makeGoal({ revision = 5, allPassed = false } = {}) {
|
||||
return {
|
||||
id: 'goal-1',
|
||||
revision,
|
||||
status: 'active',
|
||||
objective: '交付 A',
|
||||
acceptance: '测试通过',
|
||||
constraints: [],
|
||||
current: allPassed ? 2 : 0,
|
||||
stages: [
|
||||
{
|
||||
id: 's1', title: '骨架', acceptance: '能打开', status: allPassed ? 'passed' : 'active', reworks: 0,
|
||||
tasks: [{ id: 't1', botId: 'b-gong', task: '写页面', status: 'done', note: '' }],
|
||||
},
|
||||
{
|
||||
id: 's2', title: '内容', acceptance: '文案齐全', status: allPassed ? 'passed' : 'pending', reworks: 0,
|
||||
tasks: [{ id: 't2', botId: 'b-gong', task: '填文案', status: allPassed ? 'done' : 'pending', note: '' }],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function stageReview(goal, verdict, { seq = 1, stageIndex = 1, digest, artifactDigest = 'art-1', submissionSeq = 4, reviewerRole = 'shangshu' } = {}) {
|
||||
return {
|
||||
id: `rev-${verdict}-${seq}`,
|
||||
seq,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'stage',
|
||||
stageIndex,
|
||||
reviewSubjectDigest: digest ?? reviewSubjectDigest('stage', goal, stageIndex),
|
||||
digest: digest ?? reviewSubjectDigest('stage', goal, stageIndex),
|
||||
artifactDigest,
|
||||
submissionSeq,
|
||||
verdict,
|
||||
reviewerRole,
|
||||
reason: verdict === 'reject' ? '缺证据' : null,
|
||||
at: seq,
|
||||
}
|
||||
}
|
||||
|
||||
function goalReview(goal, verdict, { seq = 10, verdictOverride } = {}) {
|
||||
return {
|
||||
id: `rev-goal-${verdict}-${seq}`,
|
||||
seq,
|
||||
projectId: project.id,
|
||||
goalId: goal.id,
|
||||
goalRevision: goal.revision,
|
||||
kind: 'goal',
|
||||
stageIndex: null,
|
||||
reviewSubjectDigest: reviewSubjectDigest('goal', goal),
|
||||
digest: reviewSubjectDigest('goal', goal),
|
||||
artifactDigest: 'art-1',
|
||||
submissionSeq: 4,
|
||||
verdict: verdictOverride ?? verdict,
|
||||
reviewerRole: 'lead',
|
||||
at: seq,
|
||||
}
|
||||
}
|
||||
|
||||
const artifact = { digest: 'art-1', kind: 'git', exists: true }
|
||||
|
||||
test('F02:同版本先 pass 后 reject,最新 reject 决定结果,不能命中旧 pass', () => {
|
||||
const goal = makeGoal()
|
||||
const reviews = [stageReview(goal, 'pass', { seq: 1 }), stageReview(goal, 'reject', { seq: 2 })]
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project, goal, reviews, members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'latest-reject')
|
||||
})
|
||||
|
||||
test('reject 之后重新 pass:最新 pass 生效', () => {
|
||||
const goal = makeGoal()
|
||||
const reviews = [stageReview(goal, 'reject', { seq: 1 }), stageReview(goal, 'pass', { seq: 2 })]
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project, goal, reviews, members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, true)
|
||||
})
|
||||
|
||||
test('G03:目标先 pass 后 reject,完成被最新 reject 阻止', () => {
|
||||
const goal = makeGoal({ allPassed: true })
|
||||
const reviews = [goalReview(goal, 'pass', { seq: 1 }), goalReview(goal, 'reject', { seq: 2 })]
|
||||
const result = evaluateGoalAction({
|
||||
action: 'complete', actor: shangshu(), project, goal, reviews, members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'goal-latest-reject')
|
||||
})
|
||||
|
||||
test('G01:阶段全过但没有丞相验收,complete 拒绝', () => {
|
||||
const goal = makeGoal({ allPassed: true })
|
||||
const result = evaluateGoalAction({
|
||||
action: 'complete', actor: shangshu(), project, goal, reviews: [], members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'no-goal-review')
|
||||
})
|
||||
|
||||
test('G02:Main Bot 仍不能修改受治理目标', () => {
|
||||
const goal = makeGoal()
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass',
|
||||
actor: { ...shangshu(), isMain: true },
|
||||
project, goal, reviews: [stageReview(goal, 'pass')], members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'main-bot')
|
||||
})
|
||||
|
||||
test('A01/A02:成果摘要变化后旧批准失效', () => {
|
||||
const goal = makeGoal()
|
||||
const reviews = [stageReview(goal, 'pass', { artifactDigest: 'art-old' })]
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project, goal, reviews, members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'artifact-changed')
|
||||
})
|
||||
|
||||
test('A03:验收标准/任务范围变化后旧批准失效', () => {
|
||||
const goal = makeGoal()
|
||||
const reviews = [stageReview(goal, 'pass')]
|
||||
goal.stages[0].acceptance = '新的验收标准'
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project, goal, reviews, members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'no-stage-review')
|
||||
})
|
||||
|
||||
test('成果提交代次推进后旧审批不能复用', () => {
|
||||
const goal = makeGoal()
|
||||
const reviews = [stageReview(goal, 'pass', { submissionSeq: 3 })]
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project, goal, reviews, members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'submission-advanced')
|
||||
})
|
||||
|
||||
test('G07:治理状态损坏时受治理操作拒绝', () => {
|
||||
const goal = makeGoal()
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project: { ...project, degraded: true }, goal,
|
||||
reviews: [stageReview(goal, 'pass')], members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'state-unavailable')
|
||||
})
|
||||
|
||||
test('未知身份不按用户放行', () => {
|
||||
const goal = makeGoal()
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: { kind: 'unknown', reason: '身份过期' }, project, goal, reviews: [], members, args: {},
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'unknown-actor')
|
||||
})
|
||||
|
||||
test('一个 Bot 命中多个项目时拒绝', () => {
|
||||
const goal = makeGoal()
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: { ...shangshu(), projectConflict: true }, project, goal, reviews: [], members, args: {},
|
||||
})
|
||||
assert.equal(result.allow, false)
|
||||
assert.equal(result.code, 'project-conflict')
|
||||
})
|
||||
|
||||
test('用户显式审查可以充当阶段审查(人工特权留痕)', () => {
|
||||
const goal = makeGoal()
|
||||
const reviews = [stageReview(goal, 'pass', { reviewerRole: 'user', artifactDigest: 'art-1' })]
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project, goal, reviews, members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, true)
|
||||
})
|
||||
|
||||
test('旧格式记录仍可兼容:摘要用 stageDigest/goalDigest', () => {
|
||||
const goal = makeGoal()
|
||||
const legacy = {
|
||||
...stageReview(goal, 'pass'),
|
||||
reviewSubjectDigest: undefined,
|
||||
digest: stageDigest(goal, 1),
|
||||
}
|
||||
const result = evaluateGoalAction({
|
||||
action: 'pass', actor: shangshu(), project, goal, reviews: [legacy], members, args: {}, artifact,
|
||||
})
|
||||
assert.equal(result.allow, true)
|
||||
})
|
||||
|
||||
test('无 workDir 的项目跳过成果校验(向后兼容)', () => {
|
||||
const goal = makeGoal({ allPassed: true })
|
||||
const oldProject = { ...project, workDir: null }
|
||||
const review = goalReview(goal, 'pass')
|
||||
review.artifactDigest = null
|
||||
const result = evaluateGoalAction({
|
||||
action: 'complete', actor: shangshu(), project: oldProject, goal, reviews: [review], members, args: {},
|
||||
})
|
||||
assert.equal(result.allow, true)
|
||||
})
|
||||
|
|
@ -11,10 +11,12 @@ function fakeCtx(web) {
|
|||
|
||||
function fakeStore() {
|
||||
return {
|
||||
peek: () => ({ version: 2, projects: {}, reviews: [], dispatches: [], reworks: [], events: [] }),
|
||||
peek: () => ({ version: 3, seq: 0, projects: {}, reviews: [], dispatches: [], reworks: [], artifacts: {}, leases: {}, events: [] }),
|
||||
unknownDispatches: () => [],
|
||||
dispatchesFor: () => [],
|
||||
reviewsFor: () => [],
|
||||
artifactsFor: () => [],
|
||||
health: () => ({ status: 'ok', path: 'x', error: null }),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -29,43 +31,54 @@ function fakeRes() {
|
|||
}
|
||||
}
|
||||
|
||||
test('注册 GET /sansheng/state 并返回 JSON', async () => {
|
||||
function routesOf(web) {
|
||||
const routes = []
|
||||
const web = { register: options => { routes.push(options); return () => {} } }
|
||||
web.register = options => { routes.push(options); return () => {} }
|
||||
return routes
|
||||
}
|
||||
|
||||
const stateRoute = routes => routes.find(route => route.path === '/sansheng/state')
|
||||
|
||||
test('注册 GET /sansheng/state 并返回 JSON', async () => {
|
||||
const web = { register() { return () => {} } }
|
||||
const routes = routesOf(web)
|
||||
installRoute({ ctx: fakeCtx(web), store: fakeStore(), dsbot: { botOf: () => undefined, roomOf: () => undefined } })
|
||||
assert.equal(routes.length, 1)
|
||||
assert.equal(routes[0].kind, 'exact')
|
||||
assert.equal(routes[0].path, '/sansheng/state')
|
||||
const route = stateRoute(routes)
|
||||
assert.ok(route, '注册了 /sansheng/state')
|
||||
assert.equal(route.kind, 'exact')
|
||||
|
||||
const res = fakeRes()
|
||||
await routes[0].handler({ method: 'GET' }, res)
|
||||
await route.handler({ method: 'GET' }, res)
|
||||
assert.equal(res.statusCode, 200)
|
||||
assert.match(res.headers['content-type'], /application\/json/)
|
||||
assert.equal(res.headers['cache-control'], 'no-store')
|
||||
assert.deepEqual(JSON.parse(res.body).projects, [])
|
||||
assert.equal(JSON.parse(res.body).health.status, 'ok')
|
||||
})
|
||||
|
||||
test('非 GET 请求返回 405', async () => {
|
||||
const routes = []
|
||||
const web = { register: options => { routes.push(options); return () => {} } }
|
||||
const web = { register() { return () => {} } }
|
||||
const routes = routesOf(web)
|
||||
installRoute({ ctx: fakeCtx(web), store: fakeStore(), dsbot: { botOf: () => undefined, roomOf: () => undefined } })
|
||||
const res = fakeRes()
|
||||
await routes[0].handler({ method: 'POST' }, res)
|
||||
await stateRoute(routes).handler({ method: 'POST' }, res)
|
||||
assert.equal(res.statusCode, 405)
|
||||
})
|
||||
|
||||
test('状态读取抛错时返回 500,而不是击穿宿主', async () => {
|
||||
const routes = []
|
||||
const web = { register: options => { routes.push(options); return () => {} } }
|
||||
const web = { register() { return () => {} } }
|
||||
const routes = routesOf(web)
|
||||
const broken = {
|
||||
peek: () => { throw new Error('磁盘坏了') },
|
||||
unknownDispatches: () => [],
|
||||
dispatchesFor: () => [],
|
||||
reviewsFor: () => [],
|
||||
artifactsFor: () => [],
|
||||
health: () => ({ status: 'broken', error: '磁盘坏了' }),
|
||||
}
|
||||
installRoute({ ctx: fakeCtx(web), store: broken, dsbot: { botOf: () => undefined, roomOf: () => undefined } })
|
||||
const res = fakeRes()
|
||||
await routes[0].handler({ method: 'GET' }, res)
|
||||
await stateRoute(routes).handler({ method: 'GET' }, res)
|
||||
assert.equal(res.statusCode, 500)
|
||||
assert.match(JSON.parse(res.body).error, /磁盘坏了/)
|
||||
})
|
||||
|
|
@ -74,3 +87,40 @@ test('宿主没有 webServer 时安静跳过,不抛错', () => {
|
|||
const ctx = { get: (name, fallback) => fallback, effect: fn => fn() }
|
||||
assert.doesNotThrow(() => installRoute({ ctx, store: fakeStore(), dsbot: {} }))
|
||||
})
|
||||
|
||||
test('POST /sansheng/project/resolve 按 workspaceId 找项目,找不到返回 missing', async () => {
|
||||
const web = { register() { return () => {} } }
|
||||
const routes = routesOf(web)
|
||||
const project = {
|
||||
id: 'prj-1', name: 'A', workspaceId: 'ws-1', hostWorkspaceId: 'ws-1', workDir: 'C:/a', roomId: 'room-1',
|
||||
}
|
||||
const store = {
|
||||
...fakeStore(),
|
||||
peek: () => ({ version: 3, projects: { 'prj-1': project }, reviews: [], dispatches: [], reworks: [], artifacts: {}, leases: {}, events: [] }),
|
||||
resolveProject: ref => (ref === 'prj-1' ? project : undefined),
|
||||
}
|
||||
installRoute({ ctx: fakeCtx(web), store, dsbot: { botOf: () => undefined, roomOf: () => undefined } })
|
||||
const route = routes.find(item => item.path === '/sansheng/project/resolve')
|
||||
assert.ok(route)
|
||||
|
||||
const makeReq = body => {
|
||||
const listeners = {}
|
||||
const req = {
|
||||
method: 'POST',
|
||||
on(event, fn) { listeners[event] = fn },
|
||||
}
|
||||
setTimeout(() => {
|
||||
listeners.data?.(Buffer.from(JSON.stringify(body)))
|
||||
listeners.end?.()
|
||||
}, 0)
|
||||
return req
|
||||
}
|
||||
const found = fakeRes()
|
||||
await route.handler(makeReq({ workspaceId: 'ws-1' }), found)
|
||||
assert.equal(found.statusCode, 200)
|
||||
assert.equal(JSON.parse(found.body).project.id, 'prj-1')
|
||||
|
||||
const missing = fakeRes()
|
||||
await route.handler(makeReq({ workspaceId: 'ws-2' }), missing)
|
||||
assert.equal(JSON.parse(missing.body).missing, true)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -60,6 +60,48 @@ test('项目绑定与审查记录可持久化、可反查', async () => {
|
|||
}
|
||||
})
|
||||
|
||||
test('v2 状态迁移到 v3:旧项目/审查保留,新字段补齐', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
const file = join(dir, 'state.json')
|
||||
const { writeFile } = await import('node:fs/promises')
|
||||
await writeFile(file, JSON.stringify({
|
||||
version: 2,
|
||||
projects: { 'prj-old': { ...project, id: 'prj-old', roomId: 'room-old', bots: { lead: 'o-1', shangshu: 'o-2', gongbu: 'o-3' } } },
|
||||
reviews: [{ id: 'rev-old', projectId: 'prj-old', kind: 'stage', verdict: 'pass', digest: 'x', at: 1 }],
|
||||
dispatches: [],
|
||||
reworks: [],
|
||||
events: [],
|
||||
}), 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
assert.equal(store.peek().version, 3)
|
||||
assert.equal(store.projectById('prj-old').submissionSeq, 0)
|
||||
assert.deepEqual(store.projectById('prj-old').delivery, { include: [], exclude: [] })
|
||||
assert.equal(store.peek().reviews.length, 1)
|
||||
assert.equal(typeof store.peek().artifacts, 'object')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('commitArtifact 推进提交代次并保存快照', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
const store = new SanshengStore(join(dir, 'state.json'))
|
||||
await store.load()
|
||||
await store.saveProject({ ...project })
|
||||
const first = await store.commitArtifact('prj-1', { id: 'art-1', projectId: 'prj-1', digest: 'd1', createdAt: 1 })
|
||||
assert.equal(first.submissionSeq, 1)
|
||||
const second = await store.commitArtifact('prj-1', { id: 'art-2', projectId: 'prj-1', digest: 'd2', createdAt: 2 })
|
||||
assert.equal(second.submissionSeq, 2)
|
||||
assert.equal(store.projectById('prj-1').submissionSeq, 2)
|
||||
assert.equal(store.artifactById('art-2').submissionSeq, 2)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('状态文件损坏时 load 明确报错而不是静默清空', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
|
|
|
|||
Loading…
Reference in New Issue