fix: 按实施后审查修复 Q01-Q13 治理/事务/成果/租约边界(v0.2.3)
- Q01/Q02 严格 schema + registry 保留;broken/missing 时治理拒绝 - Q03 用户工具改 user 正向允许,unknown 全拒 - Q04 记忆群域/target Bot/Main 豁免前统一治理 - Q05 派发先记账失败停止执行;回执失败标 unknown - Q06 事务 draft 落盘后发布;guard 后最终复核 - Q07 截断/缺失成果不可验收,审查前拦截 - Q08 真实写入口按工作根互斥;submit finally 释放 - Q09 核实 projectId 校验 + 事件同事务 - Q10 重复 draft/start 不再 confirmed - Q11/Q12 模型原子性、跨项目缓存隔离保留并增强 - Q13 needsKey 展示;144/144 tests
This commit is contained in:
parent
7746edbab3
commit
1ee90d1a42
|
|
@ -22,13 +22,15 @@
|
|||
| `sansheng_status` | 项目、群、角色、模型、目标阶段、返工预算、写租约、成果代次、待核实派发 |
|
||||
| `sansheng_review` | 尚书记阶段通过/驳回,丞相记目标验收;自动生成并绑定成果快照,最新判决与摘要/代次不一致即失效 |
|
||||
| `sansheng_submit` | 提交成果快照(Git / 非 Git manifest),推进提交代次 |
|
||||
| `sansheng_config` | 只改本项目的模型/返工预算/自动返工/交付范围 |
|
||||
| `sansheng_config` | 只改本项目的模型/返工预算/自动返工/交付范围;角色卡也可直接切换模型 |
|
||||
| `sansheng_control` | 用户暂停/恢复/停止/取消目标 |
|
||||
| `sansheng_lease` | 项目写租约(第一版每项目最多一个活动写任务) |
|
||||
| `sansheng_lease` | 项目写租约 + 真实写入口按工作根独占(同根串行) |
|
||||
| `sansheng_reconcile` | 重启后核对"结果未知"的派发(不重发、不假装成功) |
|
||||
|
||||
`group_goal` 仍是阶段进度的唯一权威;尚书是唯一操作者,丞相只验收,工部只执行。项目隔离由服务端治理服务 `sansheng-governance` 落到 ds-bot 的投递与记忆边界,不只靠提示词。
|
||||
|
||||
2026-11-14 审查修复:Q01–Q12 的状态/schema、治理故障拒绝、unknown 权限、记忆群域、派发先记账、事务草稿、成果完整性、真实写根租约、核实项目一致性、draft/start 分类、模型配置原子性、跨项目缓存已补回归;仍未做真实模型 E2E,见 `docs/verification/02-test-matrix.md`。
|
||||
|
||||
根目录 `package.json` 只是工作区清单(`workspaces: sansheng, ds-bot`),本身不是 DSH 插件,也不进 `dsh.profile.bundles`。
|
||||
|
||||
## 装进 DSH
|
||||
|
|
@ -49,7 +51,7 @@
|
|||
## 验证
|
||||
|
||||
```sh
|
||||
node --test --test-isolation=none sansheng/test/*.test.js # 127 tests
|
||||
node --test --test-isolation=none sansheng/test/*.test.js # 144 tests
|
||||
node --check sansheng/client.js && node --check sansheng/index.js
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@
|
|||
| 基准提交 | `3f20f89`(工作树在开工时仅多出交接方案文档) |
|
||||
| 远端 | `origin https://git.qyhhh.top/newbie/dsh-sansheng-liubu.git` |
|
||||
| 根工作区 | `workspaces: ["sansheng", "ds-bot"]`,根 `package.json` 不是 DSH 插件 |
|
||||
| 治理包 | `sansheng/` = `dsh-sansheng-sansheng@0.2.2`(本次发布候选) |
|
||||
| 团队底座 | `ds-bot/` = `ds-bot@0.3.2-sansheng.2`(上游 `Fei2411/DS-Bot@84c3cb8` + 本地 M-01–M-06) |
|
||||
| 治理包 | `sansheng/` = `dsh-sansheng-sansheng@0.2.3`(本次发布候选) |
|
||||
| 团队底座 | `ds-bot/` = `ds-bot@0.3.2-sansheng.3`(上游 `Fei2411/DS-Bot@84c3cb8` + 本地 M-01–M-06) |
|
||||
| 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) |
|
||||
|
|
@ -108,4 +108,3 @@ ds-bot 侧只在服务存在时执行检查;不存在时保持上游行为。
|
|||
- [x] 项目树入口无公开项目动作 API → 采用宿主原生 `contextMenus` workspace/session 菜单 + 右栏页签;不使用私有 DOM。
|
||||
- [x] 不依赖直接修改宿主才能成立的功能;ds-bot 必要补丁均记录在 PATCHES。
|
||||
- [x] 旧数据保留策略明确,无自动迁移。
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# 验收矩阵与证据状态(候选版本)
|
||||
# 验收矩阵与证据状态(候选版本 v0.2.3)
|
||||
|
||||
日期:2026-11-13
|
||||
结论:**候选版本**。仓库内自动化回归通过;已在隔离测试 profile(独立 DSH_HOME,宿主 0.2.2-rc.3)完成真实宿主冒烟:右栏入口、初始化项目、三卡与角色会话可打开、输入框位于底部,证据见 `03-host-smoke.md`。真实模型 E2E(E01–E04)、workspace-groups 项目树右键、深色/窄屏仍缺失;用户日常 desktop profile 未修改。
|
||||
日期:2026-11-14
|
||||
结论:**候选版本**。仓库内自动化回归 **144/144 通过**;已在隔离测试 profile(独立 DSH_HOME,宿主 0.2.2-rc.3)完成真实宿主冒烟:右栏入口、初始化项目、三卡与角色会话可打开、输入框位于底部,证据见 `03-host-smoke.md`。真实模型 E2E(E01–E04)、workspace-groups 项目树右键、深色/窄屏仍缺失;用户日常 desktop profile 未修改。
|
||||
|
||||
## 1. 自动化测试入口
|
||||
|
||||
|
|
@ -19,6 +19,7 @@ node --check sansheng/index.js
|
|||
- `api-v3.test.js`:状态投影与历史折叠
|
||||
- `gate-install.test.js`:F01、unknown 身份、治理损坏、跨项目
|
||||
- `client.test.js`:右栏/入口/项目上下文(见 UI 工作包报告)
|
||||
- 审查修复回归:Q01/Q01b(store)、Q02(governance)、Q03(unknown 工具)、Q05/Q05b/Q05c(observer)、Q06/G06(draft+最终复核)、Q07(artifact/gate)、Q08/Q08b(提交租约+真实写根)、Q09(store+HTTP route)、Q10(records)、Q11/Q11b(config)、Q12(client)、Q13(needsKey 映射)。
|
||||
|
||||
## 2. 入口与布局
|
||||
|
||||
|
|
@ -43,9 +44,9 @@ node --check sansheng/index.js
|
|||
| 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 + Q11) | `updateProjectConfig` 先解析全部模型再应用;无效模型零修改,中途失败回滚 runtime 模型 |
|
||||
| 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;同根并发仍以单写租约为准,未做真实文件系统越界测试 |
|
||||
| I05 A 记忆不注入 B | 源码级通过 / 真实宿主未验证 | Q04:team/group/target Bot 在 `readScopes`、groupSnapshot、autoRecall、memoryUpdate、writeDenied 前统一走 governance;Main 豁免不能绕过;仍缺 ds-bot 整模块测试/真实宿主验证 |
|
||||
| I06 跨项目自动投递拒绝 | 通过(isolation I05/I06 + Q02) | governance.checkDelivery 覆盖 broken/missing registry;ds-bot delivery 补丁 |
|
||||
| I07 并行写入与工作根 | 部分通过 | Q08:真实 `write/edit/apply_patch/shell/pwsh` 等入口按规范化工作根独占,成功/失败 finally 释放;同根单写;未覆盖所有第三方写工具与崩溃后租约自动清理 |
|
||||
|
||||
## 4. 门禁与成果
|
||||
|
||||
|
|
@ -56,8 +57,8 @@ node --check sansheng/index.js
|
|||
| 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` |
|
||||
| G06 检查后变更并发改判 | 通过(新增 observer 最终复核测试;真实并发宿主未测) | Q06:draft 落盘后才发布;guard 打标后 observer 在 `next()` 前用最新 reviews/成果重判;仍非完整 TOCTOU 证明 |
|
||||
| G07 状态损坏不放行 | 通过(gate-install G07 + Q01/Q02) | Q01:null/[]/错误版本/坏条目/空主状态均 broken 且保留 registry;Q02:治理服务拒绝已知受治理主体 |
|
||||
| A01 改已跟踪文件 | 通过(artifact/review-v3) | git diff digest |
|
||||
| A02 新增未跟踪交付文件 | 通过(artifact/review-v3) | untracked manifest |
|
||||
| A03 改验收标准/任务范围 | 通过(review-v3) | reviewSubjectDigest |
|
||||
|
|
@ -71,7 +72,7 @@ node --check sansheng/index.js
|
|||
| 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) | 事务克隆回滚 |
|
||||
| R04 intent/结果保存失败 | 通过(dispatch-v2 R04 + Q05) | begin/mark 失败 nativeCalls=0;原生已执行但回执失败标 unknown,不自动重发 |
|
||||
| R05 返工与原生 @ 只执行一次 | 通过(dispatch-v2 R05) | 稳定 requestId + addRework 去重 |
|
||||
| R06 返工上限跨重启 | 通过(records/gate) | budgetOf 取原生累计与本地记录最大值 |
|
||||
| R07 暂停/取消/刷新 | 部分通过 | `sansheng_control`/route 调 `rt.goalControl`;停止请求与已停止分开显示;未做宿主 E2E |
|
||||
|
|
@ -85,13 +86,31 @@ node --check sansheng/index.js
|
|||
| E03 双项目并行 | 未执行 | 自动化隔离测试覆盖数据层,不代替真实模型 |
|
||||
| E04 中断恢复 | 未执行 | 单测覆盖故障窗口,真实重启未验证 |
|
||||
|
||||
## 7. 发布门核对
|
||||
## 7. 审查报告 Q01–Q13 修复证据
|
||||
|
||||
| 项 | 状态 | 回归/证据 |
|
||||
| --- | --- | --- |
|
||||
| Q01 | 已修 | `store.test.js` Q01/Q01b:null/[]/版本 99/projects 类型/坏条目/空主状态均 broken,registry 保留;v2 迁移仍通过 |
|
||||
| Q02 | 已修 | `isolation.test.js` Q02:broken 后 registry Bot/群拒绝投递与记忆;恢复后放行 |
|
||||
| Q03 | 已修 | `isolation.test.js` Q03:unknown 对 provision/bind/config/control/reconcile/lease 全部拒绝 |
|
||||
| Q04 | 源码级已修 | `ds-bot/src/host/memory.js` 统一 groupAllowedFor + targetBotId;governance Q04 测试覆盖 group/target/Main;无 ds-bot 整模块宿主测试 |
|
||||
| Q05 | 已修 | `dispatch-v2.test.js` Q05/Q05b/Q05c:begin/mark 失败 nativeCalls=0;回执失败 unknown |
|
||||
| Q06 | 已修 | `store.test.js` Q06 延迟落盘不可见;`records.test.js` Q06/G06 guard 打标后最终复核阻止执行 |
|
||||
| Q07 | 已修 | `artifact.test.js` missing 不再通过;`gate.test.js` Q07 truncated/missing 拒绝;review 写入前拦截 pass |
|
||||
| Q08 | 部分修 | `store.test.js` 同根互斥;`dispatch-v2.test.js` Q08b 真实 write 入口互斥;submit finally 释放;未覆盖所有第三方写工具/崩溃清理 |
|
||||
| Q09 | 已修 | `store.test.js` Q09 + `route.test.js` Q09:跨项目核实 409 且不写事件;事件与状态同事务 |
|
||||
| Q10 | 已修 | `records.test.js` Q10:重复 draft/start 拒绝,新建/启动确认 |
|
||||
| Q11 | 已修 | `isolation.test.js` Q11/Q11b:先全量校验、零修改、回滚 |
|
||||
| Q12 | 已修 | `client.test.js` Q12:跨项目失败清空;切换立即清 loading |
|
||||
| Q13 | 已修(附加) | route 保留 needsKey,client 禁用未配置凭据模型 |
|
||||
|
||||
## 8. 发布门核对
|
||||
|
||||
| 项 | 状态 |
|
||||
| --- | --- |
|
||||
| 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 复核 | 缺失,必须由用户测试环境补 |
|
||||
| 两包依赖/宿主兼容 | 明确:sansheng 0.2.3 + ds-bot 0.3.2-sansheng.3(本地补丁 M-01–M-06) |
|
||||
| 数据保留/升级/回退 | v2→v3 只补字段;严格 schema 只拒绝损坏文件并保留 registry;不迁移旧十席数据 |
|
||||
| 真实截图与 UI 复核 | 有测试 profile 浅色截图;真实多项目/深色/窄屏仍缺 |
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ profile `web-test` 的 bundles:`@deepseek-ai/dsh-base`、`@deepseek-ai/dsh-web
|
|||
| 左侧栏保持宿主项目树 | 安装 M-06 后,DS Bot 不再 shadow `sidebar.workspaces`;左栏显示「工作区 / DS Bot / New Session」项目树,不再换成 Bot 列表 | `evidence/host-project-tree-bot-switch.png` |
|
||||
| Bot 切换在右栏 | 右栏角色卡下方新增折叠「Bot 切换 · 4」,列出丞相/工部/尚书/Chief 与项目群,点击打开对应真实会话 | `evidence/host-project-tree-bot-switch.png` |
|
||||
| 模型切换 | 组件/服务端测试通过;测试 profile 没有 API Key,`/sansheng/state` 的 `models` 为空,角色卡显示「默认模型」,未能真实切换 | `client.test.js`、Q11 测试 |
|
||||
| v0.2.3 审查修复后重启 | `GET /sansheng/health` 200:store `ok`、`governance:true`、Bot 4 / 群 1;`/sansheng/state` 200,严格 schema 加载既有 v3 状态;左栏项目树/右栏三卡/Bot 切换保持可用 | `evidence/host-v023.png` |
|
||||
|
||||
HTTP 响应原文(初始空状态):
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# 发布说明(候选版本 v0.2.2 / ds-bot 0.3.2-sansheng.2)
|
||||
# 发布说明(候选版本 v0.2.3 / ds-bot 0.3.2-sansheng.3)
|
||||
|
||||
日期:2026-11-14
|
||||
状态:**候选版本**。可用于隔离测试环境;用户日常 desktop profile 未由实施者修改。
|
||||
|
|
@ -7,16 +7,24 @@
|
|||
|
||||
| 包 | 版本 | 文件 |
|
||||
| --- | --- | --- |
|
||||
| `dsh-sansheng-sansheng` | 0.2.2 | `dist/dsh-sansheng-sansheng-0.2.2.tgz` |
|
||||
| `ds-bot`(上游 0.3.2 + M-01–M-06) | 0.3.2-sansheng.2 | `dist/ds-bot-0.3.2-sansheng.2.tgz` |
|
||||
| `dsh-sansheng-sansheng` | 0.2.3 | `dist/dsh-sansheng-sansheng-0.2.3.tgz` |
|
||||
| `ds-bot`(上游 0.3.2 + M-01–M-06) | 0.3.2-sansheng.3 | `dist/ds-bot-0.3.2-sansheng.3.tgz` |
|
||||
|
||||
云端预发布:`v0.2.2-sansheng`,https://git.qyhhh.top/DeepsSeekHarness/dsh-sansheng-liubu/releases/tag/v0.2.2-sansheng (两个 tarball 已作为 release assets 上传)。
|
||||
云端发布:**未执行**。按审查报告“不授权推送或发布”的约束,v0.2.3 只在本地构建了两个 tarball;待用户明确授权后再推送/开 PR/合并/发布。此前 `v0.2.2-sansheng` 仍是在线候选版本。
|
||||
|
||||
### v0.2.2 变更
|
||||
### v0.2.3 变更
|
||||
|
||||
- 角色卡模型下拉:`/sansheng/state` 返回可用模型目录,角色卡直接切换本项目该角色模型(无 API Key 时显示默认模型,不伪造可选项)。
|
||||
- Q11:模型配置先全部解析校验,再应用;任一无效零修改,中途失败/保存失败回滚 runtime 模型。
|
||||
- Q12:项目切换请求按上下文签名缓存,切到 B 后失败不会显示 A 的旧卡片与可操作内容。
|
||||
- Q01/Q02:Store 严格校验 v2/v3 schema;错误 JSON/schema/未来版本/空主状态进 broken,保留 registry;governance 对 registry 中的受治理 Bot/群在 broken/missing 时拒绝投递、记忆读写/注入。
|
||||
- Q03:用户专属工具改为 `actor.kind === 'user'` 正向允许;unknown 不能 provision/bind/config/control/reconcile/lease。
|
||||
- Q04:记忆补丁覆盖显式 recall、默认读取、群快照注入、autoRecall、memoryUpdate、目标 Bot 写入;Main 身份也不能绕过项目归属。
|
||||
- Q05:派发意图/ in_flight 落盘失败时停止原生执行;原生已执行但回执失败标 unknown,不宣称成功。
|
||||
- Q06/G06:事务在 draft 上落盘,成功后才发布;guard 通过后 observer 在 `next()` 前用最新 reviews/成果复核。
|
||||
- Q07:truncated/missing/读取不完整的成果不能用于 stage_pass/goal_pass;缺失目录不再被 verify 当通过。
|
||||
- Q08:真实写工具(write/edit/apply_patch/shell/pwsh 等)按规范化工作根独占;提交快照租约成功/失败都释放。
|
||||
- Q09:HTTP/tool 核实校验 dispatch.projectId;状态更新与审计事件同一事务。
|
||||
- Q10:重复 draft/start 不再把“目标本来就在该状态”记成 confirmed。
|
||||
- Q11/Q12:保留 v0.2.2 的模型配置原子性与跨项目缓存隔离;Q12 增加切换时立即清空旧项目可操作数据。
|
||||
- Q13:模型目录保留 `needsKey`,未配置凭据的选项禁用并标注。
|
||||
|
||||
构建命令(在包目录运行):
|
||||
|
||||
|
|
@ -37,7 +45,7 @@ node <path-to-pnpm.cjs> pack --pack-destination ..\dist
|
|||
2. 停旧包:从 `dsh.profile.bundles` 移除 `dsh-sansheng-liubu-mode`(不要让旧十席与新方案同时注册入口)。
|
||||
3. 安装两个 tarball:
|
||||
```powershell
|
||||
dsh plugin --profile desktop add <绝对路径>\dsh-sansheng-sansheng-0.2.1.tgz <绝对路径>\ds-bot-0.3.2-sansheng.2.tgz
|
||||
dsh plugin --profile desktop add <绝对路径>\dsh-sansheng-sansheng-0.2.3.tgz <绝对路径>\ds-bot-0.3.2-sansheng.3.tgz
|
||||
```
|
||||
4. 确认 `dsh.profile.bundles` 含 `dsh-sansheng-sansheng` 与 `ds-bot`。
|
||||
5. 彻底重启 DSH(插件宿主半改动只有重启生效)。
|
||||
|
|
@ -62,6 +70,9 @@ node <path-to-pnpm.cjs> pack --pack-destination ..\dist
|
|||
## 6. 已知限制(必须随版本说明)
|
||||
|
||||
- 真实模型 E2E(E01–E04)未执行;隔离测试 profile 无 API key。
|
||||
- Q04 记忆边界为源码级修复 + governance 回归;没有 ds-bot 整模块/真实宿主注入测试。
|
||||
- Q08 只覆盖当前已知写工具(write/edit/apply_patch/shell/pwsh 等);第三方工具若绕过这些入口仍可能不受根租约约束,进程崩溃后的租约只能等过期。
|
||||
- 真实模型 E2E(E01–E04)、深色/窄屏、长消息/连续工具流仍缺;不把 144 项单测写成真实 DSH E2E 全通过。
|
||||
- `workspace-groups-remote` 项目树右键菜单未在真实测试 profile 复现(DS Bot 页面占据左栏);组件级 contextMenus 测试通过。用户日常环境若项目树可见,右键「三省六部」应可用;若不可用,用左栏底部「三省」入口。
|
||||
- 深色模式、窄屏、长消息/连续工具流未截图验证。
|
||||
- 项目树适配采用宿主原生 `contextMenus` + `sidebar.footer.action` + 右栏页签;不使用私有 DOM。
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# 交付记录
|
||||
# 交付记录
|
||||
|
||||
- 实施提交:`b955513`(feat/dsbot 分支)
|
||||
- 实施分支已推送到 Gitea:`DeepsSeekHarness/dsh-sansheng-liubu`
|
||||
|
|
@ -11,7 +11,10 @@
|
|||
- 发布:预发布 `v0.2.2-sansheng`,已上传两个可安装 tarball
|
||||
https://git.qyhhh.top/DeepsSeekHarness/dsh-sansheng-liubu/releases/tag/v0.2.2-sansheng
|
||||
- 发布产物:`dist/dsh-sansheng-sansheng-0.2.2.tgz`、`dist/ds-bot-0.3.2-sansheng.2.tgz`
|
||||
- 审查修复 v0.2.3:本地提交(当前 HEAD)(`dsh-sansheng-sansheng@0.2.3` / `ds-bot@0.3.2-sansheng.3`),144/144 回归;按审查“不授权推送/发布”暂未推 Gitea,tarball 只在 `dist/`。
|
||||
- 当前状态:候选版本,真实模型 E2E(E01–E04)未执行;日常 desktop profile 未修改。
|
||||
|
||||
> 说明:仓库的 `master` 分支仍是旧版结构(工作台/panel 目录),与 `feat/dsbot` 不在同一历史线。
|
||||
> 本次实施以 `feat/dsbot` 为开发/集成分支,未向 `master` 强推或覆盖旧结构。
|
||||
|
||||
|
||||
|
|
|
|||
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "ds-bot",
|
||||
"version": "0.3.2-sansheng.2",
|
||||
"version": "0.3.2-sansheng.3",
|
||||
"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",
|
||||
|
|
|
|||
|
|
@ -88,6 +88,12 @@ export function install(rt) {
|
|||
if (!botId || botId === 'user') return true
|
||||
return sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'team' })?.allow !== false
|
||||
}
|
||||
// Q04:群记忆读取、自动召回、群快照注入和更新提示都必须按项目边界过滤,
|
||||
// 不能只处理 team 域;明确点名的跨项目群记忆返回错误,默认作用域则过滤掉。
|
||||
const groupAllowedFor = (botId, roomId) => {
|
||||
if (!botId || botId === 'user' || !roomId) return true
|
||||
return sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'group', roomId })?.allow !== false
|
||||
}
|
||||
|
||||
if (config.memory === false) {
|
||||
Object.assign(rt, {
|
||||
|
|
@ -416,7 +422,7 @@ export function install(rt) {
|
|||
// 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 })
|
||||
const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: scope.kind, roomId: scope.kind === 'group' ? scope.roomId : undefined, targetBotId: scope.kind === 'bot' ? scope.botId : 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.'
|
||||
|
|
@ -760,6 +766,7 @@ export function install(rt) {
|
|||
return { text: lines.join('\n'), failed: main.failed !== undefined || ownTopics.failed === true || (teamAllowed && (team.failed !== undefined || teamTopics.failed === true)) }
|
||||
}
|
||||
function groupSection(roomId, bot) {
|
||||
if (!groupAllowedFor(bot.id, roomId)) return { text: '', failed: false }
|
||||
const group = groupScope(roomId)
|
||||
const groupRead = sectionRead(join(dirOf(group), MAIN))
|
||||
const groupTopics = sectionTopics(group)
|
||||
|
|
@ -910,7 +917,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)]), ...(teamAllowedFor(bot.id) ? [TEAM] : [])]
|
||||
const scopes = [own, ...(roomId === undefined || !groupAllowedFor(bot.id, roomId) ? [] : [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) })))
|
||||
|
|
@ -959,7 +966,7 @@ export function install(rt) {
|
|||
return undefined
|
||||
}
|
||||
const own = ownScope(bot.id)
|
||||
const keys = new Set([scopeKey(own), ...(teamAllowedFor(bot.id) ? [scopeKey(TEAM)] : []), ...(roomId === undefined ? [] : [scopeKey(groupScope(roomId))])])
|
||||
const keys = new Set([scopeKey(own), ...(teamAllowedFor(bot.id) ? [scopeKey(TEAM)] : []), ...(roomId === undefined || !groupAllowedFor(bot.id, roomId) ? [] : [scopeKey(groupScope(roomId))])])
|
||||
try {
|
||||
for (const path of new Set([journalPath, journalFor(scopeKey(own), 'read').path])) readTail(path)
|
||||
} catch (error) {
|
||||
|
|
@ -1159,12 +1166,21 @@ export function install(rt) {
|
|||
const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'bot', targetBotId: scope.botId })
|
||||
if (verdict && verdict.allow === false) return { error: verdict.reason ?? '项目记忆边界拒绝读取其他项目成员记忆。' }
|
||||
}
|
||||
if (scope && scope.kind === 'group' && botId && botId !== 'user') {
|
||||
const verdict = sanshengGovernance()?.checkMemoryScope?.({ botId, scope: 'group', roomId: scope.roomId })
|
||||
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 (botId && botId !== 'user') {
|
||||
if (scope === undefined && roomId !== undefined && !groupAllowedFor(botId, roomId)) {
|
||||
scopes = scopes.filter(item => item.kind !== 'group')
|
||||
}
|
||||
if (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) {
|
||||
|
|
|
|||
|
|
@ -340,6 +340,11 @@ window.__ModuleLoader__.load({
|
|||
// 否则从项目树切到 B 后仍会请求 A 的工作区,右栏永远停在旧项目。
|
||||
const context = workspaceContextOf(ctx)
|
||||
const signature = contextSignature(context)
|
||||
// 切到另一个项目时立即作废旧项目的可操作数据,避免在新请求
|
||||
// 返回前仍显示/点击旧项目卡片。
|
||||
if (lastSignature !== null && signature !== lastSignature) {
|
||||
onChange({ loading: true, error: null, data: null, updatedAt: 0, context })
|
||||
}
|
||||
let retryImmediately = false
|
||||
try {
|
||||
if (!fetchImpl) throw new Error('宿主没有 fetch')
|
||||
|
|
@ -358,8 +363,12 @@ window.__ModuleLoader__.load({
|
|||
onChange({ loading: false, error: null, data, updatedAt: lastUpdatedAt, context })
|
||||
} catch (error) {
|
||||
if (stopped || isStale(requestId, latestRequestId)) return
|
||||
// 只有同一项目断连才展示上次数据;切到 B 后失败不能把 A 的卡片
|
||||
// 配上 B 的上下文(Q12)。
|
||||
// 请求失败时也要重新读取当前 workspace:A 的迟到失败不能配上
|
||||
// B 的实际工作区,也不能把 A 的缓存当 B 展示。
|
||||
if (contextSignature(workspaceContextOf(ctx)) !== signature) {
|
||||
retryImmediately = true
|
||||
return
|
||||
}
|
||||
const sameProject = signature === lastSignature
|
||||
onChange({
|
||||
loading: false,
|
||||
|
|
@ -729,7 +738,12 @@ window.__ModuleLoader__.load({
|
|||
card.model && !modelOptions.some(item => item.ref === card.model)
|
||||
? h('option', { key: 'current', value: card.model, children: card.model })
|
||||
: null,
|
||||
...modelOptions.map(item => h('option', { key: item.ref, value: item.ref, children: item.name || item.ref })),
|
||||
...modelOptions.map(item => h('option', {
|
||||
key: item.ref,
|
||||
value: item.ref,
|
||||
disabled: item.needsKey === true,
|
||||
children: (item.name || item.ref) + (item.needsKey === true ? '(未配置凭据)' : ''),
|
||||
})),
|
||||
].filter(Boolean))
|
||||
: h('span', { key: 'model', className: 'ss-model-text', children: model })
|
||||
return h('div', props, [
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-sansheng-sansheng",
|
||||
"version": "0.2.2",
|
||||
"version": "0.2.3",
|
||||
"private": true,
|
||||
"description": "三省六部:在 DS Bot 团队上提供丞相/尚书/工部三角色、目标门禁与审查记录。",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -689,13 +689,18 @@ function verifyCurrent(snapshot, project, current) {
|
|||
current,
|
||||
}
|
||||
}
|
||||
if (snapshot.truncated === true) {
|
||||
return { ok: false, reason: '审查依据的成果快照被截断(文件数超过上限),不是完整成果,不能用于验收。', 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 }
|
||||
return { ok: false, reason: '审查时工作目录不存在,不能把“无成果”当成已验收成果。', current }
|
||||
}
|
||||
if (current.truncated === true) {
|
||||
return { ok: false, reason: '当前成果快照被截断(文件数超过上限),不能作为完整交付验收。', current }
|
||||
}
|
||||
if (snapshot.digest !== current.digest) {
|
||||
return { ok: false, reason: '成果已变化:交付文件或提交与审查时不一致。', current }
|
||||
|
|
|
|||
|
|
@ -151,6 +151,12 @@ export function evaluateGoalAction({
|
|||
if (artifact === undefined || artifact === null) {
|
||||
return deny('artifact-unavailable', '无法读取当前成果快照,不能推进受治理目标。')
|
||||
}
|
||||
if (artifact.kind === 'missing' || artifact.exists === false) {
|
||||
return deny('artifact-missing', '当前工作目录不存在或不是目录,不能生成完整成果快照;请恢复工作目录后重新提交/审查。')
|
||||
}
|
||||
if (artifact.truncated === true) {
|
||||
return deny('artifact-truncated', '当前成果快照被截断(文件数超过上限),不是完整成果,不能验收;请缩小交付范围或提高上限后重新提交。')
|
||||
}
|
||||
if (currentDigest !== review.artifactDigest) {
|
||||
return deny('artifact-changed', '交付成果在审查之后发生了变化(文件、未跟踪交付物或提交不同);旧审查已失效,请重新审查并生成新快照。')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,6 +90,8 @@ export function installGates({ ctx, store, dsbot, isBotSession }) {
|
|||
projectFreshness: health.status,
|
||||
})
|
||||
if (!verdict.allow) return `三省六部:${verdict.reason}`
|
||||
// 给 observer 一个标记:真正执行前还要在异步边界后复核一次最新审批/成果。
|
||||
try { exec.__sanshengGate = true } catch { /* 冻结的 exec 对象则跳过最终复核 */ }
|
||||
return undefined
|
||||
} catch (error) {
|
||||
// 校验内部出错时拒绝而不是放行:目标状态比一次调用重要。
|
||||
|
|
|
|||
|
|
@ -1,63 +1,101 @@
|
|||
/**
|
||||
* 对外治理服务:ds-bot 的投递与记忆模块在运行时调用。
|
||||
* 目标是把"项目边界"放在服务端,而不是只靠 prompt 或前端按钮。
|
||||
*
|
||||
* Q02:项目归属解析必须同时看 health 与 registry。主状态损坏/缺失时,
|
||||
* registry 里记录过的 Bot/群是"已知受治理但当前不可用",必须拒绝,而不是
|
||||
* 因空 projects 被误判成非项目 Bot。
|
||||
*/
|
||||
export function installGovernance({ ctx, store }) {
|
||||
function statusOfBot(botId) {
|
||||
const project = store.projectByBot(botId)
|
||||
if (project) return { kind: 'bound', project }
|
||||
const hinted = typeof store.registryProjectForBot === 'function' ? store.registryProjectForBot(botId) : undefined
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
if (hinted && health.status !== 'ok') return { kind: 'unavailable', projectId: hinted, reason: '治理状态不可用' }
|
||||
if (hinted && !project) return { kind: 'unavailable', projectId: hinted, reason: 'registry 中有绑定但主状态缺失' }
|
||||
return { kind: 'unbound' }
|
||||
}
|
||||
|
||||
function statusOfRoom(roomId) {
|
||||
if (!roomId) return { kind: 'unbound' }
|
||||
const project = store.projectByRoom(roomId)
|
||||
if (project) return { kind: 'bound', project }
|
||||
const hinted = typeof store.registryProjectForRoom === 'function' ? store.registryProjectForRoom(roomId) : undefined
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
if (hinted && health.status !== 'ok') return { kind: 'unavailable', projectId: hinted, reason: '治理状态不可用' }
|
||||
if (hinted && !project) return { kind: 'unavailable', projectId: hinted, reason: 'registry 中有绑定但主状态缺失' }
|
||||
return { kind: 'unbound' }
|
||||
}
|
||||
|
||||
const unavailableReason = (what, state) =>
|
||||
`治理状态不可用(${what} ${state.projectId ?? ''}):${state.reason ?? '主状态损坏或缺失'};为防跨项目泄漏,已拒绝本次操作。`
|
||||
|
||||
const api = {
|
||||
version: 3,
|
||||
projectOfBot(botId) {
|
||||
const project = store.projectByBot(botId)
|
||||
return project ? { id: project.id, name: project.name } : undefined
|
||||
const resolved = statusOfBot(botId)
|
||||
return resolved.kind === 'bound' ? { id: resolved.project.id, name: resolved.project.name } : undefined
|
||||
},
|
||||
projectOfRoom(roomId) {
|
||||
const project = store.projectByRoom(roomId)
|
||||
return project ? { id: project.id, name: project.name } : undefined
|
||||
const resolved = statusOfRoom(roomId)
|
||||
return resolved.kind === 'bound' ? { id: resolved.project.id, name: resolved.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)
|
||||
const from = statusOfBot(fromId)
|
||||
const to = statusOfBot(toId)
|
||||
const room = statusOfRoom(roomId)
|
||||
|
||||
if (roomProject) {
|
||||
if (fromProject && fromProject.id !== roomProject.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:发送方属于「${fromProject.name}」,群属于「${roomProject.name}」。` }
|
||||
// Q02:任何已知受治理主体在不可用状态下一律拒绝。
|
||||
for (const [label, state] of [['发送方', from], ['接收方', to], ['群', room]]) {
|
||||
if (state.kind === 'unavailable') return { allow: false, reason: unavailableReason(label, state) }
|
||||
}
|
||||
|
||||
if (room.kind === 'bound') {
|
||||
const project = room.project
|
||||
if (from.kind === 'bound' && from.project.id !== project.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:发送方属于「${from.project.name}」,群属于「${project.name}」。` }
|
||||
}
|
||||
if (toProject && toProject.id !== roomProject.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:接收方属于「${toProject.name}」,群属于「${roomProject.name}」。` }
|
||||
if (to.kind === 'bound' && to.project.id !== project.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:接收方属于「${to.project.name}」,群属于「${project.name}」。` }
|
||||
}
|
||||
if (fromProject && !toProject) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:接收方不属于任何项目,不能接收「${fromProject.name}」的项目内容。` }
|
||||
if (from.kind === 'bound' && to.kind === 'unbound') {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:接收方不属于任何项目,不能接收「${from.project.name}」的项目内容。` }
|
||||
}
|
||||
return { allow: true }
|
||||
}
|
||||
|
||||
if (!fromProject) return { allow: true }
|
||||
if (!toProject) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:「${fromProject.name}」的 Bot 不能给项目外 Bot 发私聊消息。` }
|
||||
if (from.kind === 'unbound') return { allow: true }
|
||||
if (to.kind === 'unbound') {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:「${from.project.name}」的 Bot 不能给项目外 Bot 发私聊消息。` }
|
||||
}
|
||||
if (toProject.id !== fromProject.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:「${fromProject.name}」的 Bot 不能给「${toProject.name}」的 Bot 发消息。` }
|
||||
if (to.project.id !== from.project.id) {
|
||||
return { allow: false, reason: `跨项目投递被拒绝:「${from.project.name}」的 Bot 不能给「${to.project.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 }
|
||||
const actor = statusOfBot(botId)
|
||||
if (actor.kind === 'unavailable') return { allow: false, reason: unavailableReason('Bot', actor) }
|
||||
if (actor.kind === 'unbound') return { allow: true }
|
||||
const project = actor.project
|
||||
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) {
|
||||
const room = statusOfRoom(roomId)
|
||||
if (room.kind === 'unavailable') return { allow: false, reason: unavailableReason('群', room) }
|
||||
if (room.kind === 'unbound' || room.project.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) {
|
||||
const target = statusOfBot(targetBotId)
|
||||
if (target.kind === 'unavailable') return { allow: false, reason: unavailableReason('目标 Bot', target) }
|
||||
if (target.kind === 'unbound' || target.project.id !== project.id) {
|
||||
return { allow: false, reason: `记忆边界拒绝:「${project.name}」的 Bot 不能读写其他项目成员的记忆。` }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,25 @@
|
|||
import { budgetOf } from './gate.js'
|
||||
import { resolve } from 'node:path'
|
||||
import { captureArtifactSnapshotSync } from './artifact.js'
|
||||
import { budgetOf, evaluateGoalAction } from './gate.js'
|
||||
import { resolveActor } from './identity.js'
|
||||
import {
|
||||
classifyGoalOutcome, describeDispatch, detectRework, isGoalMutation, newId, payloadDigestOf,
|
||||
} from './records.js'
|
||||
import { roleOfBot } from './roles.js'
|
||||
|
||||
// Q08:这些是 DSH 里真正会改用户项目的工具入口;按实际工作根加独占租约。
|
||||
const WRITE_TOOLS = new Set([
|
||||
'write', 'edit', 'apply_patch', 'delete', 'move', 'copy',
|
||||
'write_file', 'edit_file', 'delete_file', 'move_file', 'copy_file',
|
||||
'shell', 'bash', 'pwsh', 'execute', 'terminal', 'run_terminal',
|
||||
'shell_command', 'run_command', 'terminal_command',
|
||||
])
|
||||
let rootWriteSeq = 0
|
||||
|
||||
function isWriteTool(name) {
|
||||
return WRITE_TOOLS.has(String(name ?? ''))
|
||||
}
|
||||
|
||||
function textOfResult(result) {
|
||||
if (typeof result === 'string') return result
|
||||
const content = Array.isArray(result?.content) ? result.content : []
|
||||
|
|
@ -18,7 +33,9 @@ function textOfResult(result) {
|
|||
*/
|
||||
export function installObserver({ ctx, store, dsbot, bootId, isBotSession }) {
|
||||
return ctx.on('tools/execute', async (exec, next) => {
|
||||
if (!exec || exec.name !== 'group_goal') return next()
|
||||
if (!exec) return next()
|
||||
if (isWriteTool(exec.name)) return observeWrite({ store, dsbot, exec, next, isBotSession })
|
||||
if (exec.name !== 'group_goal') return next()
|
||||
const action = String(exec.arguments?.action ?? '')
|
||||
if (!isGoalMutation(action)) return next()
|
||||
|
||||
|
|
@ -69,13 +86,44 @@ export function installObserver({ ctx, store, dsbot, bootId, isBotSession }) {
|
|||
}
|
||||
return record.note ?? `三省六部:请求 ${record.requestId ?? record.id} 已处理过,本次没有重复执行。`
|
||||
}
|
||||
if (!replay) await store.markDispatchInFlight(record.id)
|
||||
try {
|
||||
await store.markDispatchInFlight(record.id)
|
||||
} catch (error) {
|
||||
await store.finishDispatch(record.id, {
|
||||
status: 'unknown',
|
||||
note: `派发意图已写入,但标记 in_flight 失败:${String(error?.message ?? error)}`,
|
||||
}).catch(() => {})
|
||||
return `三省六部:无法标记派发 ${record.id} 为发送中(${error?.message ?? error}),本次目标修改未执行;请先核实后再重试。`
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.code === 'payload-conflict') throw error
|
||||
// Q05:项目已识别时,派发意图写入失败必须阻止原生命令执行。
|
||||
// 不能“记账失败就继续”,否则执行了却没有可对账的记录。
|
||||
if (project) {
|
||||
return `三省六部:无法写入派发记录(${error?.message ?? error}),本次目标修改未执行;请恢复存储后重试。`
|
||||
}
|
||||
record = undefined
|
||||
}
|
||||
|
||||
// Q06/G06:guard 通过后到真正执行还有异步窗口;若 guard 打过标记,
|
||||
// 在 next() 前用最新 reviews/artifact 再判一次,防止审批在窗口里被撤销/成果变化。
|
||||
if (record && project && exec.__sanshengGate === true) {
|
||||
try {
|
||||
const reason = finalGateReason({ store, dsbot, exec, project, roomId, isBotSession })
|
||||
if (reason) {
|
||||
await store.finishDispatch(record.id, { status: 'rejected', note: reason }).catch(() => {})
|
||||
return `三省六部:${reason}`
|
||||
}
|
||||
} catch (error) {
|
||||
await store.finishDispatch(record.id, {
|
||||
status: 'unknown',
|
||||
note: `最终复核失败:${String(error?.message ?? error)}`,
|
||||
}).catch(() => {})
|
||||
return `三省六部:最终复核失败(${error?.message ?? error}),本次目标修改未执行。`
|
||||
}
|
||||
}
|
||||
|
||||
let result
|
||||
try {
|
||||
result = await next()
|
||||
|
|
@ -94,12 +142,78 @@ export function installObserver({ ctx, store, dsbot, bootId, isBotSession }) {
|
|||
if (record) {
|
||||
try {
|
||||
await settle({ ctx, store, dsbot, project, record, action, result, before, roomId })
|
||||
} catch { /* 记账失败不影响调用 */ }
|
||||
} catch (error) {
|
||||
// 原生调用已经返回,但回执写入失败:不能把 in_flight 留成“看似成功”。
|
||||
// 尽力改成 unknown,交给 sansheng_reconcile;若存储仍不可用,下次启动对账会处理。
|
||||
try {
|
||||
await store.finishDispatch(record.id, {
|
||||
status: 'unknown',
|
||||
note: `原生调用已返回,但派发回执记录失败:${String(error?.message ?? error)}`,
|
||||
})
|
||||
} catch { /* 下次启动 reconcile 会把 prepared/in_flight 标为 unknown */ }
|
||||
}
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
async function observeWrite({ store, dsbot, exec, next, isBotSession }) {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession })
|
||||
if (actor.kind !== 'bot' || !actor.project || actor.projectConflict) return next()
|
||||
const project = actor.project
|
||||
if (!project.workDir) return next()
|
||||
const root = resolve(project.workDir)
|
||||
const holder = `${actor.botId}:${exec.id ?? exec.agent?.id ?? 'write'}:${++rootWriteSeq}`
|
||||
let lease
|
||||
try {
|
||||
lease = await store.acquireRootLease(root, { holder, taskId: String(exec.id ?? exec.arguments?.task ?? 'write') })
|
||||
} catch (error) {
|
||||
return `三省六部:无法建立工作根写租约(${error?.message ?? error}),本次文件写未执行。`
|
||||
}
|
||||
if (!lease.ok) return `三省六部:${lease.reason} 本次文件写未执行。`
|
||||
try {
|
||||
return await next()
|
||||
} finally {
|
||||
// 真实执行结束、抛错或取消都释放;进程被杀时最多留到租约过期。
|
||||
await store.releaseRootLease(root, holder).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
function finalGateReason({ store, dsbot, exec, project, roomId, isBotSession }) {
|
||||
const room = dsbot.roomOf(roomId)
|
||||
const goal = room?.goal
|
||||
const action = String(exec.arguments?.action ?? '')
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession })
|
||||
const members = (room?.members ?? []).map(id => ({
|
||||
id,
|
||||
name: dsbot.botOf(id)?.name ?? id,
|
||||
role: roleOfBot(project, id),
|
||||
}))
|
||||
let artifact
|
||||
if (project.workDir && (action === 'pass' || action === 'complete')) {
|
||||
artifact = captureArtifactSnapshotSync({
|
||||
project,
|
||||
goal,
|
||||
stageIndex: action === 'complete' ? null : (goal?.current ?? -1) + 1,
|
||||
scope: action === 'complete' ? 'goal' : 'stage',
|
||||
})
|
||||
}
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
const verdict = evaluateGoalAction({
|
||||
action,
|
||||
actor: { ...actor, role: roleOfBot(project, actor.botId) },
|
||||
project,
|
||||
goal,
|
||||
reviews: store.peek().reviews,
|
||||
reworks: store.peek().reworks,
|
||||
members,
|
||||
args: exec.arguments ?? {},
|
||||
artifact,
|
||||
projectFreshness: health.status,
|
||||
})
|
||||
return verdict.allow ? undefined : verdict.reason
|
||||
}
|
||||
|
||||
async function settle({ ctx, store, dsbot, project, record, action, result, before, roomId }) {
|
||||
const after = roomId ? dsbot.roomOf(roomId)?.goal : undefined
|
||||
const outcome = classifyGoalOutcome({ action, before, after, result })
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ function checkProjectName(store, name, selfId) {
|
|||
* 账号/工作区只登记,不改宿主项目树;失败只清理本次新建对象。
|
||||
*/
|
||||
export async function provisionProject({ ctx, store, dsbot, args, actor }) {
|
||||
if (actor?.kind === 'bot') return { ok: false, text: '只有用户能创建项目;Bot 在现有项目群里工作。' }
|
||||
if (actor?.kind !== 'user') 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)。' }
|
||||
|
|
@ -316,6 +316,13 @@ export async function updateProjectConfig({ ctx, store, args }) {
|
|||
rollback.push(`${ROLE_LABEL[undo.role]}(${undoError?.message ?? undoError})`)
|
||||
}
|
||||
}
|
||||
if (rollback.length > 0) {
|
||||
await store.addEvent?.({
|
||||
kind: 'config-rollback-failed',
|
||||
projectId: project.id,
|
||||
summary: `${ROLE_LABEL[item.role]}更新失败;回滚失败:${rollback.join('、')}`,
|
||||
}).catch?.(() => {})
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
text: `更新${ROLE_LABEL[item.role]}模型失败:${error?.message ?? error}。`
|
||||
|
|
@ -357,6 +364,13 @@ export async function updateProjectConfig({ ctx, store, args }) {
|
|||
rollback.push(`${ROLE_LABEL[undo.role]}(${undoError?.message ?? undoError})`)
|
||||
}
|
||||
}
|
||||
if (rollback.length > 0) {
|
||||
await store.addEvent?.({
|
||||
kind: 'config-rollback-failed',
|
||||
projectId: project.id,
|
||||
summary: `保存配置失败;模型回滚失败:${rollback.join('、')}`,
|
||||
}).catch?.(() => {})
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
text: `保存配置失败:${error?.message ?? error}。`
|
||||
|
|
|
|||
|
|
@ -57,8 +57,10 @@ export function classifyGoalOutcome({ action, before, after, result }) {
|
|||
const changed = after !== undefined && (
|
||||
afterId !== beforeId
|
||||
|| afterRevision > beforeRevision
|
||||
|| (action === 'draft' && after?.status === 'drafting')
|
||||
|| (action === 'start' && after?.status === 'active')
|
||||
// Q10:draft 必须是“新建了目标”,start 必须是“从非 active 进入 active”。
|
||||
// 目标本来就在 drafting/active 时,重复 draft/start 即使原生返回成功也不能算确认。
|
||||
|| (action === 'draft' && afterId !== null && afterId !== beforeId)
|
||||
|| (action === 'start' && before?.status !== 'active' && after?.status === 'active')
|
||||
)
|
||||
if (changed) return { status: 'confirmed', note: null }
|
||||
const text = textOfResult(result)
|
||||
|
|
|
|||
|
|
@ -118,6 +118,7 @@ export function installRoute({ ctx, store, dsbot }) {
|
|||
providerName: entry.providerName,
|
||||
model: entry.id,
|
||||
name: entry.name,
|
||||
needsKey: entry.needsKey === true,
|
||||
}))
|
||||
}
|
||||
} catch { /* 模型目录不可用时仍返回项目状态 */ }
|
||||
|
|
@ -244,10 +245,10 @@ export function installRoute({ ctx, store, dsbot }) {
|
|||
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')
|
||||
const result = await store.resolveDispatch(String(body.id ?? ''), verdict, 'user', project.id, { withEvent: true })
|
||||
if (!result) return send(res, 404, { ok: false, error: '找不到派发记录。' })
|
||||
if (result.wrongProject) return send(res, 409, { 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) })
|
||||
|
|
|
|||
|
|
@ -35,13 +35,67 @@ function isObject(value) {
|
|||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function isNonEmptyString(value) {
|
||||
return typeof value === 'string' && value.trim() !== ''
|
||||
}
|
||||
|
||||
function projectProblem(project, id) {
|
||||
if (!isObject(project)) return `项目 ${id} 不是对象`
|
||||
if (!isNonEmptyString(project.id)) return `项目 ${id} 缺少 id`
|
||||
if (project.id !== id) return `项目键 ${id} 与 id ${project.id} 不一致`
|
||||
if (!isNonEmptyString(project.name)) return `项目 ${id} 缺少 name`
|
||||
if (!isNonEmptyString(project.roomId)) return `项目 ${id} 缺少 roomId`
|
||||
if (!isObject(project.bots)) return `项目 ${id} 缺少 bots`
|
||||
for (const role of ROLE_IDS) {
|
||||
if (!isNonEmptyString(project.bots[role])) return `项目 ${id} 缺少 ${role} Bot`
|
||||
}
|
||||
if (new Set(ROLE_IDS.map(role => project.bots[role])).size !== ROLE_IDS.length) {
|
||||
return `项目 ${id} 的角色 Bot 重复`
|
||||
}
|
||||
if (project.workspaceId !== undefined && project.workspaceId !== null && typeof project.workspaceId !== 'string') return `项目 ${id} 的 workspaceId 非法`
|
||||
if (project.models !== undefined && !isObject(project.models)) return `项目 ${id} 的 models 非法`
|
||||
if (project.delivery !== undefined && !isObject(project.delivery)) return `项目 ${id} 的 delivery 非法`
|
||||
return undefined
|
||||
}
|
||||
|
||||
function arrayProblem(value, name) {
|
||||
if (!Array.isArray(value)) return `${name} 不是数组`
|
||||
for (const [index, item] of value.entries()) {
|
||||
if (!isObject(item)) return `${name}[${index}] 不是对象`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Q01:只接受明确支持的 v2/v3 schema。合法 JSON 但 schema 错误一律视为损坏,
|
||||
* 不能把 null/[]/错误版本/部分非法结构静默回退成“健康空状态”。
|
||||
*/
|
||||
export function validateState(raw) {
|
||||
if (!isObject(raw)) return { ok: false, error: '状态顶层不是对象' }
|
||||
if (raw.version !== 2 && raw.version !== 3) return { ok: false, error: `不支持的状态版本 ${String(raw.version)}` }
|
||||
if (!isObject(raw.projects)) return { ok: false, error: 'projects 不是对象' }
|
||||
for (const [id, project] of Object.entries(raw.projects)) {
|
||||
const problem = projectProblem(project, id)
|
||||
if (problem) return { ok: false, error: problem }
|
||||
}
|
||||
for (const name of ['reviews', 'dispatches', 'reworks', 'events']) {
|
||||
const problem = arrayProblem(raw[name] ?? [], name)
|
||||
if (problem) return { ok: false, error: problem }
|
||||
}
|
||||
if (raw.artifacts !== undefined && !isObject(raw.artifacts)) return { ok: false, error: 'artifacts 不是对象' }
|
||||
if (raw.leases !== undefined && !isObject(raw.leases)) return { ok: false, error: 'leases 不是对象' }
|
||||
if (raw.seq !== undefined && !Number.isFinite(raw.seq)) return { ok: false, error: 'seq 不是数字' }
|
||||
return { ok: true, state: raw }
|
||||
}
|
||||
|
||||
|
||||
function normalizeProject(project) {
|
||||
if (!isObject(project)) return undefined
|
||||
return {
|
||||
schemaVersion: VERSION,
|
||||
submissionSeq: 0,
|
||||
delivery: { include: [], exclude: [] },
|
||||
...project,
|
||||
schemaVersion: VERSION,
|
||||
models: isObject(project.models) ? project.models : {},
|
||||
bots: isObject(project.bots) ? project.bots : {},
|
||||
}
|
||||
|
|
@ -137,13 +191,17 @@ export class SanshengStore {
|
|||
async load() {
|
||||
this.#ready ??= (async () => {
|
||||
let projectError
|
||||
let loadedRaw
|
||||
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)
|
||||
const checked = validateState(raw)
|
||||
if (!checked.ok) throw new Error(`状态 schema 非法:${checked.error}`)
|
||||
loadedRaw = checked.state
|
||||
this.#state = normalize(loadedRaw)
|
||||
this.#health = { status: 'ok', path: this.#file, error: null }
|
||||
}
|
||||
} catch (error) {
|
||||
|
|
@ -164,7 +222,15 @@ export class SanshengStore {
|
|||
} catch {
|
||||
// registry 只是提示文件;读不了时按无提示处理,不影响主状态。
|
||||
}
|
||||
if (this.#health.status === 'ok') await this.#writeRegistry().catch(() => {})
|
||||
// 主状态合法但为空、registry 仍记录受治理项目:说明主状态被替换/截断,
|
||||
// 不能当作“项目全都删了”并覆盖最后的治理身份。
|
||||
if (this.#health.status === 'ok'
|
||||
&& Object.keys(this.#state.projects).length === 0
|
||||
&& (Object.keys(this.#registry.rooms ?? {}).length > 0 || Object.keys(this.#registry.bots ?? {}).length > 0)) {
|
||||
this.#health = { status: 'broken', path: this.#file, error: '主状态为空但 registry 仍记录受治理项目' }
|
||||
projectError ??= new Error(`状态 schema 非法:${this.#health.error}`)
|
||||
}
|
||||
if (this.#health.status === 'ok') await this.#writeRegistry(this.#state).catch(() => {})
|
||||
if (projectError) throw projectError
|
||||
return this.#state
|
||||
})()
|
||||
|
|
@ -184,44 +250,39 @@ export class SanshengStore {
|
|||
return this.#registry
|
||||
}
|
||||
|
||||
async #writeRegistry() {
|
||||
await writeJsonAtomic(this.#registryFile, registryOf(this.#state))
|
||||
this.#registry = registryOf(this.#state)
|
||||
async #writeRegistry(state = this.#state) {
|
||||
const registry = registryOf(state)
|
||||
await writeJsonAtomic(this.#registryFile, registry)
|
||||
this.#registry = registry
|
||||
}
|
||||
|
||||
async transact(mutate) {
|
||||
const run = this.#queue.then(async () => {
|
||||
await this.load()
|
||||
const before = clone(this.#state)
|
||||
// Q06:在草稿上修改,落盘成功后才发布给同步读取者;任何读都不会看到未提交状态。
|
||||
const draft = 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)
|
||||
const result = await mutate(draft)
|
||||
if (draft.reviews.length > REVIEW_LIMIT) draft.reviews = draft.reviews.slice(-REVIEW_LIMIT)
|
||||
if (draft.dispatches.length > DISPATCH_LIMIT) draft.dispatches = draft.dispatches.slice(-DISPATCH_LIMIT)
|
||||
if (draft.reworks.length > REWORK_LIMIT) draft.reworks = draft.reworks.slice(-REWORK_LIMIT)
|
||||
if (draft.events.length > EVENT_LIMIT) draft.events = draft.events.slice(-EVENT_LIMIT)
|
||||
const artifactIds = Object.keys(draft.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]
|
||||
const keep = new Set(artifactIds.sort((a, b) => (draft.artifacts[a].createdAt ?? 0) - (draft.artifacts[b].createdAt ?? 0)).slice(-ARTIFACT_LIMIT))
|
||||
for (const id of artifactIds) if (!keep.has(id)) delete draft.artifacts[id]
|
||||
}
|
||||
await writeJsonAtomic(this.#file, this.#state)
|
||||
await writeJsonAtomic(this.#file, draft)
|
||||
// 只有主状态落盘成功后才发布;registry 失败不回滚已提交主状态,下次 load 重建。
|
||||
this.#state = draft
|
||||
try {
|
||||
await this.#writeRegistry()
|
||||
await this.#writeRegistry(draft)
|
||||
} catch {
|
||||
// registry 失败不改变业务事务结果;下次 load 会重建。
|
||||
// registry 是提示文件,主状态已是权威。
|
||||
}
|
||||
this.#health = { status: 'ok', path: this.#file, error: null }
|
||||
return result
|
||||
} catch (error) {
|
||||
this.#state = before
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
|
@ -269,7 +330,7 @@ export class SanshengStore {
|
|||
return botId ? this.#registry.bots?.[botId] : undefined
|
||||
}
|
||||
|
||||
async #validateProject(project) {
|
||||
async #validateProject(project, state = this.#state) {
|
||||
if (!isObject(project) || typeof project.id !== 'string' || project.id === '') {
|
||||
throw new SanshengStoreError('invalid-project', '项目绑定缺少 id。')
|
||||
}
|
||||
|
|
@ -277,7 +338,7 @@ export class SanshengStore {
|
|||
if (new Set(bots).size !== bots.length) {
|
||||
throw new SanshengStoreError('roles-duplicated', '丞相/尚书/工部必须是三个不同的 Bot。')
|
||||
}
|
||||
for (const other of Object.values(this.#state.projects)) {
|
||||
for (const other of Object.values(state.projects)) {
|
||||
if (other.id === project.id) continue
|
||||
if (project.roomId && other.roomId === project.roomId) {
|
||||
throw new SanshengStoreError('room-taken', `群 ${project.roomId} 已绑定项目「${other.name}」。`)
|
||||
|
|
@ -293,7 +354,7 @@ export class SanshengStore {
|
|||
|
||||
async saveProject(project) {
|
||||
return this.transact(async state => {
|
||||
await this.#validateProject(project)
|
||||
await this.#validateProject(project, state)
|
||||
const previous = state.projects[project.id] ?? {}
|
||||
const next = {
|
||||
schemaVersion: VERSION,
|
||||
|
|
@ -315,7 +376,7 @@ export class SanshengStore {
|
|||
const project = state.projects[id]
|
||||
if (!project) throw new SanshengStoreError('not-found', `项目 ${id} 不存在。`)
|
||||
const next = { ...project, ...patch, updatedAt: Date.now() }
|
||||
await this.#validateProject(next)
|
||||
await this.#validateProject(next, state)
|
||||
state.projects[id] = next
|
||||
return next
|
||||
})
|
||||
|
|
@ -449,15 +510,27 @@ export class SanshengStore {
|
|||
}
|
||||
|
||||
/** 尚书/用户核实一条 unknown 派发:done=确实执行过,not-done=没执行。 */
|
||||
async resolveDispatch(id, verdict, by) {
|
||||
async resolveDispatch(id, verdict, by, projectId, { withEvent = false } = {}) {
|
||||
return this.transact(state => {
|
||||
const record = state.dispatches.find(item => item.id === id)
|
||||
if (!record) return undefined
|
||||
if (projectId && record.projectId !== projectId) return { record, changed: false, wrongProject: true }
|
||||
if (record.status !== 'unknown') return { record, changed: false }
|
||||
record.status = verdict === 'done' ? 'confirmed' : 'rejected'
|
||||
record.resolvedBy = by
|
||||
record.resolvedAt = Date.now()
|
||||
record.note = verdict === 'done' ? '核实:原生操作已执行。' : '核实:原生操作没有执行。'
|
||||
if (withEvent) {
|
||||
state.seq += 1
|
||||
state.events.push({
|
||||
kind: 'reconcile',
|
||||
projectId: record.projectId,
|
||||
summary: `${id} → ${verdict}`,
|
||||
action: record.action,
|
||||
seq: state.seq,
|
||||
at: Date.now(),
|
||||
})
|
||||
}
|
||||
return { record, changed: true }
|
||||
})
|
||||
}
|
||||
|
|
@ -530,4 +603,47 @@ export class SanshengStore {
|
|||
if (lease.expiresAt <= Date.now()) return undefined
|
||||
return lease
|
||||
}
|
||||
|
||||
/** Q08:真实文件写入口按“规范化工作根”互斥;不同项目指向同一根目录也必须串行。 */
|
||||
async acquireRootLease(root, { holder, taskId = null, ttlMs = 30 * 60 * 1000 } = {}) {
|
||||
const key = rootLeaseKey(root)
|
||||
if (key === '') throw new SanshengStoreError('invalid-root', '工作目录为空,不能建立写租约。')
|
||||
return this.transact(state => {
|
||||
const now = Date.now()
|
||||
const current = state.leases[key]
|
||||
if (current && current.expiresAt > now && current.holder !== holder) {
|
||||
return {
|
||||
ok: false,
|
||||
lease: current,
|
||||
reason: `工作目录正在被 ${current.holder} 写入(任务 ${current.taskId ?? '未命名'}),同一实际路径不能并发写。`,
|
||||
}
|
||||
}
|
||||
const lease = { root: key.slice(5), holder, taskId, acquiredAt: now, expiresAt: now + ttlMs, renewedAt: now }
|
||||
state.leases[key] = lease
|
||||
return { ok: true, lease }
|
||||
})
|
||||
}
|
||||
|
||||
async releaseRootLease(root, holder) {
|
||||
const key = rootLeaseKey(root)
|
||||
return this.transact(state => {
|
||||
const current = state.leases[key]
|
||||
if (!current || current.holder !== holder) return { ok: false, reason: '工作根租约不存在或不属于该持有者。' }
|
||||
delete state.leases[key]
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
|
||||
rootLeaseOf(root) {
|
||||
const current = this.#state.leases?.[rootLeaseKey(root)]
|
||||
if (!current) return undefined
|
||||
if (current.expiresAt <= Date.now()) return undefined
|
||||
return current
|
||||
}
|
||||
}
|
||||
|
||||
function rootLeaseKey(root) {
|
||||
const text = String(root ?? '').trim().replace(/\\/g, '/').replace(/\/+$/, '')
|
||||
if (text === '') return ''
|
||||
return `root:${text}`.toLowerCase()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -163,6 +163,9 @@ async function review({ store, dsbot, args, exec }) {
|
|||
if (project.workDir) {
|
||||
try {
|
||||
const snapshot = await captureArtifactSnapshot({ project, goal, stageIndex, scope: 'stage' })
|
||||
if (action === 'stage_pass' && (snapshot.truncated || snapshot.kind === 'missing' || (snapshot.kind !== 'unscoped' && snapshot.exists === false))) {
|
||||
return '当前成果不完整(目录缺失或被截断),不能记录 stage_pass;请恢复完整交付或缩小交付范围后重试。'
|
||||
}
|
||||
const committed = await store.commitArtifact(project.id, snapshot)
|
||||
artifact = committed.snapshot
|
||||
submissionSeq = committed.submissionSeq
|
||||
|
|
@ -220,6 +223,9 @@ async function review({ store, dsbot, args, exec }) {
|
|||
if (project.workDir) {
|
||||
try {
|
||||
const snapshot = await captureArtifactSnapshot({ project, goal, stageIndex: null, scope: 'goal' })
|
||||
if (action === 'goal_pass' && (snapshot.truncated || snapshot.kind === 'missing' || (snapshot.kind !== 'unscoped' && snapshot.exists === false))) {
|
||||
return '当前成果不完整(目录缺失或被截断),不能记录 goal_pass;请恢复完整交付或缩小交付范围后重试。'
|
||||
}
|
||||
const committed = await store.commitArtifact(project.id, snapshot)
|
||||
artifact = committed.snapshot
|
||||
submissionSeq = committed.submissionSeq
|
||||
|
|
@ -273,32 +279,37 @@ async function submit({ store, dsbot, args, exec }) {
|
|||
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 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')
|
||||
} finally {
|
||||
// 写租约只覆盖这次实际提交;成功/失败都释放,不能被一次提交永久占住。
|
||||
await store.releaseLease(project.id, holder).catch(() => {})
|
||||
}
|
||||
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 不能改项目配置。'
|
||||
if (actor.kind !== 'user') 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 } })
|
||||
|
|
@ -307,7 +318,7 @@ async function config({ ctx, store, dsbot, args, exec }) {
|
|||
|
||||
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 并按角色权限执行。'
|
||||
if (actor.kind !== 'user') return '暂停/恢复/停止只能由用户操作;Bot 用 group_goal pause/resume/stop 并按角色权限执行。'
|
||||
const resolved = resolveProjectForCall({ store, actor, args })
|
||||
if (resolved.error) return resolved.error
|
||||
const project = resolved.project
|
||||
|
|
@ -380,10 +391,10 @@ async function reconcile({ store, dsbot, args, exec }) {
|
|||
}
|
||||
const verdict = String(args.verdict ?? '').trim()
|
||||
if (verdict !== 'done' && verdict !== 'not-done') return 'verdict 必须是 done(确实执行过)或 not-done(没有执行)。'
|
||||
const result = await store.resolveDispatch(id, verdict, actor.botId ?? 'user')
|
||||
const result = await store.resolveDispatch(id, verdict, actor.botId ?? 'user', project?.id, { withEvent: true })
|
||||
if (!result) return `找不到派发记录 ${id}。`
|
||||
if (result.wrongProject) return `派发 ${id} 不属于当前项目 ${project?.id ?? ''},不能跨项目核实。`
|
||||
if (!result.changed) return `派发 ${id} 当前是 ${result.record.status},不需要核实。`
|
||||
await store.addEvent({ kind: 'reconcile', projectId: record.projectId, summary: `${id} → ${verdict}`, action: record.action })
|
||||
return verdict === 'done'
|
||||
? `已核实 ${id}:原生操作确实执行过,记录改为已确认。`
|
||||
: `已核实 ${id}:原生操作没有执行,记录改为被拒绝;需要时再重新发起。`
|
||||
|
|
@ -445,7 +456,7 @@ export function installTools({ ctx, store, dsbot, isBotSession }) {
|
|||
},
|
||||
async (args, exec) => {
|
||||
const actor = resolveActor({ dsbot, store, sessionId: exec.agent?.id, isBotSession })
|
||||
if (actor.kind === 'bot') return '只有用户能把群绑定为项目;Bot 不能改项目绑定。'
|
||||
if (actor.kind !== 'user') return '只有用户能把群绑定为项目;Bot 或身份不明的调用者不能改项目绑定。'
|
||||
const result = await bindProject({ store, dsbot, rt: ctx.get('dsbot-runtime', false), args })
|
||||
return result.text
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -252,8 +252,9 @@ test('workDir 为空/不存在:unscoped 与 missing 同类通过、跨类失
|
|||
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)
|
||||
// Q07:missing 不是“完整成果”,不能拿同摘要的空快照通过验收。
|
||||
assert.equal((await verifyArtifactSnapshot({ snapshot: missing, project: missingProject })).ok, false)
|
||||
assert.equal(verifyArtifactSnapshotSync({ snapshot: missing, project: missingProject }).ok, false)
|
||||
|
||||
const missingAgainstUnscoped = await verifyArtifactSnapshot({ snapshot: missing, project: unscopedProject })
|
||||
assert.equal(missingAgainstUnscoped.ok, false)
|
||||
|
|
|
|||
|
|
@ -170,3 +170,95 @@ test('R04:事务失败回滚内存状态,不留下虚假成功', async () =>
|
|||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q05:派发意图写入失败时阻止原生执行,不留下“执行了但没记录”', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
store.beginDispatch = async () => { throw new Error('磁盘写失败') }
|
||||
let called = false
|
||||
const result = await ctx.handlers['tools/execute'](exec, async () => { called = true; return { content: [] } })
|
||||
assert.equal(called, false, '记账失败必须停止原生命令')
|
||||
assert.match(String(result), /无法写入派发记录/)
|
||||
assert.equal(store.peek().dispatches.length, 0)
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q05b:markInFlight 失败时也阻止原生执行,并把记录标为 unknown', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
store.markDispatchInFlight = async () => { throw new Error('状态写失败') }
|
||||
let called = false
|
||||
const result = await ctx.handlers['tools/execute'](exec, async () => { called = true; return { content: [] } })
|
||||
assert.equal(called, false)
|
||||
assert.match(String(result), /本次目标修改未执行/)
|
||||
assert.equal(store.peek().dispatches.at(-1).status, 'unknown')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q08b:真实文件写入口按工作根互斥,执行结束释放', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject({ ...PROJECT, workDir: 'C:/work/shared-root' })
|
||||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
let release
|
||||
const gate = new Promise(resolve => { release = resolve })
|
||||
let firstCalled = false
|
||||
let secondCalled = false
|
||||
const first = ctx.handlers['tools/execute'](
|
||||
{ name: 'write', id: 'call-1', arguments: { path: 'a.txt' }, agent: { id: 'sess-shang' } },
|
||||
async () => { firstCalled = true; await gate; return 'written' },
|
||||
)
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
const second = await ctx.handlers['tools/execute'](
|
||||
{ name: 'write', id: 'call-2', arguments: { path: 'b.txt' }, agent: { id: 'sess-shang' } },
|
||||
async () => { secondCalled = true; return 'written' },
|
||||
)
|
||||
assert.equal(secondCalled, false, '同一工作根并发写必须被拒绝')
|
||||
assert.match(String(second), /同一实际路径不能并发写/)
|
||||
release()
|
||||
assert.equal(await first, 'written')
|
||||
assert.equal(firstCalled, true)
|
||||
assert.equal(store.rootLeaseOf('C:/work/shared-root'), undefined, '写完成后释放根租约')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q05c:原生已执行但回执写入失败时,记录标为 unknown 而不是 confirmed', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
const original = store.finishDispatch.bind(store)
|
||||
let first = true
|
||||
store.finishDispatch = async (...args) => {
|
||||
if (first) { first = false; throw new Error('回执写失败') }
|
||||
return original(...args)
|
||||
}
|
||||
let called = false
|
||||
const result = await ctx.handlers['tools/execute'](exec, async () => {
|
||||
called = true
|
||||
dsbot.roomOf().goal = goalAt({ revision: 5, reworks: 1 })
|
||||
return { content: [{ type: 'text', text: '已驳回' }] }
|
||||
})
|
||||
assert.equal(called, true)
|
||||
assert.match(result.content[0].text, /已驳回/)
|
||||
const record = store.peek().dispatches.at(-1)
|
||||
assert.equal(record.status, 'unknown')
|
||||
assert.match(record.note, /回执记录失败/)
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -239,3 +239,24 @@ test('暂停/停止/修订由尚书放行', () => {
|
|||
assert.equal(result.allow, true, `${action} 应放行`)
|
||||
}
|
||||
})
|
||||
import { artifactDigestOf } from '../src/digest.js'
|
||||
|
||||
test('Q07:截断或缺失的成果快照不能用于 pass/complete', () => {
|
||||
const goal = makeGoal()
|
||||
const projectWithWork = { ...project, workDir: 'C:/work/example' }
|
||||
const review = { ...stageReview(goal, 1, 'pass'), artifactDigest: artifactDigestOf({ kind: 'files', digest: 'd', truncated: true, exists: true }) }
|
||||
const truncated = decide({
|
||||
action: 'pass', project: projectWithWork, goal, reviews: [review],
|
||||
artifact: { kind: 'files', digest: 'd', truncated: true, exists: true },
|
||||
})
|
||||
assert.equal(truncated.allow, false)
|
||||
assert.equal(truncated.code, 'artifact-truncated')
|
||||
|
||||
const missingReview = { ...stageReview(goal, 1, 'pass'), artifactDigest: artifactDigestOf({ kind: 'missing', digest: 'm' }) }
|
||||
const missing = decide({
|
||||
action: 'pass', project: projectWithWork, goal, reviews: [missingReview],
|
||||
artifact: { kind: 'missing', digest: 'm', truncated: false, exists: false },
|
||||
})
|
||||
assert.equal(missing.allow, false)
|
||||
assert.equal(missing.code, 'artifact-missing')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { apply } from '../index.js'
|
|||
import { installGovernance } from '../src/governance.js'
|
||||
import { resolveActor } from '../src/identity.js'
|
||||
import { SanshengStore, SanshengStoreError } from '../src/store.js'
|
||||
import { installTools } from '../src/tools.js'
|
||||
|
||||
function fakeCtx(services = {}) {
|
||||
const tools = []
|
||||
|
|
@ -342,3 +343,97 @@ test('Q11b:中途 updateBot 失败时回滚已经修改的模型', async () =>
|
|||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q02:状态损坏时 registry 中的受治理 Bot/群拒绝投递与记忆访问,恢复后放行', async () => {
|
||||
const { readFile, writeFile } = await import('node:fs/promises')
|
||||
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 good = await readFile(env.statePath, 'utf8')
|
||||
await writeFile(env.statePath, '{broken', 'utf8')
|
||||
const broken = new SanshengStore(env.statePath)
|
||||
await assert.rejects(() => broken.load())
|
||||
const governance = installGovernance({ ctx: fakeCtx(), store: broken })
|
||||
assert.equal(governance.checkDelivery({ fromId: project.bots.lead, toId: project.bots.shangshu, roomId: project.roomId }).allow, false)
|
||||
assert.equal(governance.checkMemoryScope({ botId: project.bots.lead, scope: 'team' }).allow, false)
|
||||
assert.equal(governance.checkMemoryScope({ botId: project.bots.lead, scope: 'group', roomId: project.roomId }).allow, false)
|
||||
assert.equal(governance.checkMemoryScope({ botId: project.bots.lead, scope: 'bot', targetBotId: project.bots.gongbu }).allow, false)
|
||||
|
||||
await writeFile(env.statePath, good, 'utf8')
|
||||
const restored = new SanshengStore(env.statePath)
|
||||
await restored.load()
|
||||
const healthy = installGovernance({ ctx: fakeCtx(), store: restored })
|
||||
assert.equal(healthy.checkDelivery({ fromId: project.bots.lead, toId: project.bots.shangshu, roomId: project.roomId }).allow, true)
|
||||
assert.equal(healthy.checkMemoryScope({ botId: project.bots.lead, scope: 'team' }).allow, false)
|
||||
assert.equal(healthy.checkMemoryScope({ botId: project.bots.lead, scope: 'group', roomId: project.roomId }).allow, true)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q03:unknown 身份不能调用用户专属工具(provision/bind/config/control)', async () => {
|
||||
const { mkdtemp } = await import('node:fs/promises')
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-q03-'))
|
||||
const store = new SanshengStore(join(dir, 'state.json'))
|
||||
await store.load()
|
||||
const defs = []
|
||||
const ctx = {
|
||||
tools: { register(def) { defs.push(def); return () => {} } },
|
||||
get() { return undefined },
|
||||
}
|
||||
const dsbot = {
|
||||
selfOf: () => undefined,
|
||||
botOf: () => undefined,
|
||||
isMain: () => false,
|
||||
snapshot: () => ({ rooms: {}, bots: {} }),
|
||||
roomOf: () => undefined,
|
||||
}
|
||||
installTools({ ctx, store, dsbot, isBotSession: id => id === 'bot-session' })
|
||||
const exec = { agent: { id: 'bot-session' } }
|
||||
const run = (name, args) => defs.find(def => def.name === name).execute(args, exec)
|
||||
assert.match(await run('sansheng_bind', { room: 'x' }), /只有用户/)
|
||||
assert.match(await run('sansheng_provision', { project: 'x' }), /只有用户/)
|
||||
assert.match(await run('sansheng_config', { project: 'x' }), /只有用户|身份不明/)
|
||||
assert.match(await run('sansheng_control', { project: 'x', action: 'pause' }), /只能由用户/)
|
||||
assert.match(await run('sansheng_reconcile', { id: 'dsp-x', verdict: 'done' }), /找不到对应身份|当前 DS Bot 状态/)
|
||||
assert.match(await run('sansheng_lease', { project: 'x', action: 'acquire' }), /找不到对应身份|当前 DS Bot 状态/)
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test('Q08:提交成果使用写租约并在成功/失败后释放', 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 submitted = await env.tool('sansheng_submit').execute({ project: project.id, task: 't1' }, userExec)
|
||||
assert.match(submitted, /已提交成果快照/)
|
||||
assert.equal(env.store.leaseOf(project.id), undefined, '提交完成后必须释放租约')
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q04:记忆作用域过滤覆盖群与目标 Bot,Main 身份不能绕过项目归属', 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 projects = Object.values(env.store.peek().projects)
|
||||
const a = projects.find(project => project.name === '项目A')
|
||||
const b = projects.find(project => project.name === '项目B')
|
||||
const governance = installGovernance({ ctx: fakeCtx(), store: env.store })
|
||||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: b.roomId }).allow, false)
|
||||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'bot', targetBotId: b.bots.lead }).allow, false)
|
||||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'bot', targetBotId: a.bots.lead }).allow, true)
|
||||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'group', roomId: a.roomId }).allow, true)
|
||||
// 即使 actor 是 Main,也先按项目归属拒绝(记忆补丁在 Main 豁免之前调用治理)。
|
||||
env.rt.isMain = () => true
|
||||
assert.equal(governance.checkMemoryScope({ botId: a.bots.lead, scope: 'bot', targetBotId: b.bots.lead }).allow, false)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { join } from 'node:path'
|
|||
import { test } from 'node:test'
|
||||
import { evaluateGoalAction } from '../src/gate.js'
|
||||
import { installObserver } from '../src/observe.js'
|
||||
import { detectRework, isGoalMutation, newBootId, newId } from '../src/records.js'
|
||||
import { classifyGoalOutcome, detectRework, isGoalMutation, newBootId, newId } from '../src/records.js'
|
||||
import { SanshengStore } from '../src/store.js'
|
||||
|
||||
async function tempStore() {
|
||||
|
|
@ -233,3 +233,59 @@ test('跨项目隔离:别的项目的 Bot 不能改本项目的目标', () =>
|
|||
assert.equal(verdict.allow, false)
|
||||
assert.equal(verdict.code, 'not-member')
|
||||
})
|
||||
|
||||
test('Q10:重复 draft/start 即使原生返回成功也不记 confirmed', () => {
|
||||
const before = goalAt({ revision: 4, status: 'active' })
|
||||
const startAgain = classifyGoalOutcome({
|
||||
action: 'start',
|
||||
before,
|
||||
after: { ...before },
|
||||
result: { content: [{ type: 'text', text: '目标已启动' }] },
|
||||
})
|
||||
assert.equal(startAgain.status, 'rejected')
|
||||
assert.match(startAgain.note, /目标已启动/)
|
||||
|
||||
const drafting = { ...before, id: 'goal-draft', status: 'drafting' }
|
||||
const draftAgain = classifyGoalOutcome({
|
||||
action: 'draft',
|
||||
before: drafting,
|
||||
after: { ...drafting },
|
||||
result: { content: [{ type: 'text', text: '已起草' }] },
|
||||
})
|
||||
assert.equal(draftAgain.status, 'rejected')
|
||||
|
||||
const draftNew = classifyGoalOutcome({
|
||||
action: 'draft',
|
||||
before: undefined,
|
||||
after: drafting,
|
||||
result: { content: [{ type: 'text', text: '已起草' }] },
|
||||
})
|
||||
assert.equal(draftNew.status, 'confirmed')
|
||||
|
||||
const startFresh = classifyGoalOutcome({
|
||||
action: 'start',
|
||||
before: { ...before, status: 'drafting' },
|
||||
after: before,
|
||||
result: { content: [{ type: 'text', text: '已启动' }] },
|
||||
})
|
||||
assert.equal(startFresh.status, 'confirmed')
|
||||
})
|
||||
|
||||
test('Q06/G06:guard 通过后、执行前复核最新审批,失效则停止原生调用', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject(PROJECT)
|
||||
const { dsbot, ctx } = fakeEnv()
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId(), isBotSession: () => true })
|
||||
let called = false
|
||||
const result = await ctx.handlers['tools/execute'](
|
||||
{ name: 'group_goal', arguments: { action: 'pass', evidence: 'e' }, agent: { id: 'sess-shang' }, __sanshengGate: true },
|
||||
async () => { called = true; return { content: [{ type: 'text', text: '已通过' }] } },
|
||||
)
|
||||
assert.equal(called, false, '审批失效时必须停止执行')
|
||||
assert.match(String(result), /sansheng_review|no-stage-review/)
|
||||
assert.equal(store.peek().dispatches.at(-1).status, 'rejected')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -124,3 +124,39 @@ test('POST /sansheng/project/resolve 按 workspaceId 找项目,找不到返回
|
|||
await route.handler(makeReq({ workspaceId: 'ws-2' }), missing)
|
||||
assert.equal(JSON.parse(missing.body).missing, true)
|
||||
})
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { SanshengStore } from '../src/store.js'
|
||||
|
||||
test('Q09:HTTP 核实拒绝 projectId 与派发所属项目不一致', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-route-'))
|
||||
try {
|
||||
const store = new SanshengStore(join(dir, 'state.json'))
|
||||
await store.load()
|
||||
const project = {
|
||||
id: 'prj-a', name: 'A', workspaceId: 'ws-a', roomId: 'room-a',
|
||||
bots: { lead: 'a-lead', shangshu: 'a-shang', gongbu: 'a-gong' }, maxReworks: 3,
|
||||
}
|
||||
await store.saveProject(project)
|
||||
await store.beginDispatch({ id: 'dsp-b', projectId: 'prj-b', action: 'pass' })
|
||||
await store.reconcileDispatches('boot-route')
|
||||
|
||||
const web = { register() { return () => {} } }
|
||||
const routes = routesOf(web)
|
||||
installRoute({ ctx: fakeCtx(web), store, dsbot: { botOf: () => undefined, roomOf: () => undefined } })
|
||||
const route = routes.find(item => item.path === '/sansheng/reconcile')
|
||||
const res = fakeRes()
|
||||
await route.handler({
|
||||
method: 'POST',
|
||||
on(event, handler) {
|
||||
if (event === 'data') handler(Buffer.from(JSON.stringify({ projectId: 'prj-a', id: 'dsp-b', verdict: 'done' })))
|
||||
if (event === 'end') handler()
|
||||
},
|
||||
}, res)
|
||||
assert.equal(res.statusCode, 409)
|
||||
assert.equal(store.peek().dispatches.find(item => item.id === 'dsp-b').status, 'unknown')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -114,3 +114,119 @@ test('状态文件损坏时 load 明确报错而不是静默清空', async () =>
|
|||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q01:合法 JSON 的错误 schema 不被当成健康空状态,registry 不被覆盖', async () => {
|
||||
const { readFile, writeFile } = await import('node:fs/promises')
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
const file = join(dir, 'state.json')
|
||||
const seed = new SanshengStore(file)
|
||||
await seed.load()
|
||||
await seed.saveProject({ ...project })
|
||||
const registryBefore = await readFile(join(dir, 'registry.json'), 'utf8')
|
||||
const payloads = [
|
||||
'null',
|
||||
'[]',
|
||||
JSON.stringify({ version: 99, projects: {}, reviews: [], dispatches: [], reworks: [], events: [] }),
|
||||
JSON.stringify({ version: 3, projects: [], reviews: [], dispatches: [], reworks: [], events: [] }),
|
||||
JSON.stringify({ version: 3, projects: { 'prj-1': { ...project, bots: { lead: 'only-one' } } }, reviews: [], dispatches: [], reworks: [], events: [] }),
|
||||
]
|
||||
for (const payload of payloads) {
|
||||
await writeFile(file, payload, 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await assert.rejects(() => store.load(), /schema 非法/)
|
||||
assert.equal(store.health().status, 'broken')
|
||||
assert.equal(store.registryProjectForRoom('room-1'), 'prj-1', '错误 schema 不得覆盖既有 registry')
|
||||
assert.equal(await readFile(join(dir, 'registry.json'), 'utf8'), registryBefore)
|
||||
}
|
||||
// 主状态为空但 registry 仍记录项目,也不能当作健康空状态。
|
||||
await writeFile(file, JSON.stringify({ version: 3, seq: 0, projects: {}, reviews: [], dispatches: [], reworks: [], artifacts: {}, leases: {}, events: [] }), 'utf8')
|
||||
const empty = new SanshengStore(file)
|
||||
await assert.rejects(() => empty.load(), /registry 仍记录/)
|
||||
assert.equal(empty.health().status, 'broken')
|
||||
assert.equal(empty.registryProjectForBot('b-lead'), 'prj-1')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q06:事务在落盘前对同步读取不可见', 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 })
|
||||
let released
|
||||
const gate = new Promise(resolve => { released = resolve })
|
||||
const running = store.transact(async state => {
|
||||
state.projects['prj-1'].name = '未提交草稿'
|
||||
await gate
|
||||
return 'ok'
|
||||
})
|
||||
await new Promise(resolve => setTimeout(resolve, 10))
|
||||
assert.equal(store.projectById('prj-1').name, '示例项目', '事务中的草稿不应被读到')
|
||||
released()
|
||||
assert.equal(await running, 'ok')
|
||||
assert.equal(store.projectById('prj-1').name, '未提交草稿')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q09:核实派发必须校验 projectId,不能跨项目改状态', 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 })
|
||||
await store.beginDispatch({ id: 'dsp-q09', projectId: 'prj-1', action: 'pass' })
|
||||
await store.reconcileDispatches('boot-q09')
|
||||
const wrong = await store.resolveDispatch('dsp-q09', 'done', 'user', 'prj-other')
|
||||
assert.equal(wrong.wrongProject, true)
|
||||
assert.equal(store.peek().dispatches.find(item => item.id === 'dsp-q09').status, 'unknown')
|
||||
const right = await store.resolveDispatch('dsp-q09', 'done', 'user', 'prj-1', { withEvent: true })
|
||||
assert.equal(right.changed, true)
|
||||
assert.equal(right.record.status, 'confirmed')
|
||||
const reconcileEvents = store.peek().events.filter(item => item.kind === 'reconcile')
|
||||
assert.equal(reconcileEvents.length, 1, '核实事件与状态更新同一事务写入')
|
||||
assert.equal(reconcileEvents[0].projectId, 'prj-1')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q01b:主状态缺失但 registry 仍在时 health=missing 且保留治理身份', async () => {
|
||||
const { rm } = await import('node:fs/promises')
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
const file = join(dir, 'state.json')
|
||||
const seed = new SanshengStore(file)
|
||||
await seed.load()
|
||||
await seed.saveProject({ ...project })
|
||||
await rm(file)
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
assert.equal(store.health().status, 'missing')
|
||||
assert.equal(store.registryProjectForRoom('room-1'), 'prj-1')
|
||||
assert.equal(store.registryProjectForBot('b-lead'), 'prj-1')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q08:不同项目指向同一工作根也共享独占租约', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-store-'))
|
||||
try {
|
||||
const store = new SanshengStore(join(dir, 'state.json'))
|
||||
await store.load()
|
||||
const first = await store.acquireRootLease('C:\\work\\shared', { holder: 'a', taskId: 't1' })
|
||||
assert.equal(first.ok, true)
|
||||
const second = await store.acquireRootLease('C:/work/shared/', { holder: 'b', taskId: 't2' })
|
||||
assert.equal(second.ok, false)
|
||||
assert.match(second.reason, /同一实际路径不能并发写/)
|
||||
assert.equal((await store.releaseRootLease('C:\\work\\shared', 'a')).ok, true)
|
||||
assert.equal(store.rootLeaseOf('C:/work/shared'), undefined)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in New Issue