Compare commits
9 Commits
7746edbab3
...
fa75b6e9c6
| Author | SHA1 | Date |
|---|---|---|
|
|
fa75b6e9c6 | |
|
|
eb82c92162 | |
|
|
37ee2d4a6f | |
|
|
39d905add8 | |
|
|
ca2dd1b559 | |
|
|
9a97576413 | |
|
|
88e550896a | |
|
|
198dd25d6d | |
|
|
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 # 168 tests
|
||||
node --check sansheng/client.js && node --check sansheng/index.js
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# WP0 基线、接口与发布路线
|
||||
# WP0 基线、接口与发布路线
|
||||
|
||||
日期:2026-11-13(Asia/Shanghai)
|
||||
状态:实施前核对记录。后续验证结果按测试 ID 写入本目录其他文件。
|
||||
|
|
@ -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.7`(本次发布候选) |
|
||||
| 团队底座 | `ds-bot/` = `ds-bot@0.3.2-sansheng.7`(上游 `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.7)
|
||||
|
||||
日期: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
|
||||
结论:**候选版本**。仓库内自动化回归 **168/168 通过**;已在隔离测试 profile(独立 DSH_HOME,宿主 0.2.2-rc.3)完成真实宿主冒烟:原生项目树、原生聊天、右栏三卡与 Bot 切换,DS-Bot 全局 shell 未接管,控制台无 DS-Bot 重挂/设置冲突警告,证据见 `03-host-smoke.md`。真实模型 E2E(E01–E04)、长消息/连续工具流仍缺失;用户日常 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/Q01c(store+apply)、Q02/Q02b(governance+gate 双故障)、Q03(unknown 工具)、Q04(governance + 真实 memory install + peer stub)、Q05/Q05b/Q05c(observer)、Q06/G06(draft+最终复核)、Q07(artifact/gate)、Q08/Q08b/Q08c/Q08d/Q08e/Q08f/Q08g/Q08h(租约+junction+过期+events 终态+嵌套目标+越界拒绝)、Q09(store+HTTP route)、Q10(records)、Q11/Q11b/Q11c/Q11d/Q11e/R4-05(config 回滚+并发+sidecar+真实 selectSessionModel+群失败/CAS)、Q12/Q12b/Q12c(Hook+超时+真实 useSanshengState)、Q13/R4-04(真实 catalog needsKey 服务端+前端)。
|
||||
|
||||
## 2. 入口与布局
|
||||
|
||||
|
|
@ -28,7 +29,10 @@ node --check sansheng/index.js
|
|||
| U02 从项目树打开 A | 真实宿主冒烟通过(测试 profile) | 左栏保持 workspace-groups 项目树;右栏三卡与「Bot 切换」独立于左栏;workspace-groups 右键菜单组件级测试通过 |
|
||||
| U03 右栏重复点击聚焦 | 组件级通过 | `openRolesTab` 优先 better-sidebar/openTabIn;现有测试覆盖回退 |
|
||||
| U04 Better Sidebar 缺失/失败 | 真实宿主冒烟通过(回退入口) | 测试 profile 无 better-sidebar:左栏底部「三省」按钮可打开右栏「角色」页签;见 `03-host-smoke.md` |
|
||||
| U05 小窗口/宽屏/主题 | 部分验证 | 1440×900 浅色截图;深色/窄屏未测 |
|
||||
| U05 小窗口/宽屏/主题 | 真实宿主通过(浅/深/窄) | 1440×900 浅色与深色、900×700 窄屏:原生项目树/输入框/右栏可用;无页面错误;见 `host-dark.png`、`host-narrow.png` |
|
||||
| UI01 原生共存模式 | 真实宿主通过(含 R4-06 卸载) | DS-Bot 走 agent surface;三省卸载撤销标记、发 workbench-gone、清理样式;DS-Bot 晚收到 ready 时释放设置壳;浅色宿主 0 警告 |
|
||||
| UI02 保留项目树不误重挂 | 真实宿主通过 | 控制台无 `sidebar entry missing/remounting` 警告;verifySidebar 在共存模式直接跳过 |
|
||||
| UI03 右栏不被抽屉折叠 | 真实宿主通过(未打开 Bot 详情) | 右栏决策 effect 在共存模式不安装,回调也有 guard;角色页签可打开;Bot 详情交叉打开未操作 |
|
||||
| U06 A/B 切换旧响应不覆盖 | 通过(client 测试) | 请求序号丢弃旧响应;Q12:跨项目失败不再把 A 缓存配上 B 上下文 |
|
||||
| U07 新目标不显示旧验收 | 通过(api-v3) | 按 goalId 过滤 + 历史折叠 |
|
||||
| U08 先 reject 后 pass 不显示旧返工 | 通过(api-v3) | 当前阶段最新判决决定卡片 |
|
||||
|
|
@ -43,9 +47,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 | 真实 memory 模块集成通过 / 真实宿主未验证 | Q04:team/group/target Bot 在 `readScopes`、groupSnapshot、autoRecall、memoryUpdate、writeDenied 前统一走 governance;`memory-q04.test.js` 验证被拒群记忆不注入、显式 recall 拒绝;真实模型/宿主注入仍缺 |
|
||||
| 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 +60,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 +75,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 +89,31 @@ node --check sansheng/index.js
|
|||
| E03 双项目并行 | 未执行 | 自动化隔离测试覆盖数据层,不代替真实模型 |
|
||||
| E04 中断恢复 | 未执行 | 单测覆盖故障窗口,真实重启未验证 |
|
||||
|
||||
## 7. 发布门核对
|
||||
## 7. 审查报告 Q01–Q13 修复证据
|
||||
|
||||
| 项 | 状态 | 回归/证据 |
|
||||
| --- | --- | --- |
|
||||
| Q01 | 已修(第三轮补启动保护) | Q01/Q01b/Q01c:坏 schema/空主状态保留 registry;missing+registry 时 writable=false,启动对账与 provision 拒绝覆盖;v2 迁移仍通过 |
|
||||
| Q02 | 已修(双故障补强) | Q02/Q02b:broken/missing registry 拒绝;主 state+registry 双坏时 governance/gate 显式拒绝 |
|
||||
| Q03 | 已修 | `isolation.test.js` Q03:unknown 对 provision/bind/config/control/reconcile/lease 全部拒绝 |
|
||||
| Q04 | 已修(真实 memory 模块集成) | `memory-q04.test.js` 用 peer stub 加载 ds-bot memory:被拒群记忆不注入、显式 recall 返回 blocked;允许后才读到;仍无真实模型/宿主记忆注入 |
|
||||
| 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 | 部分修(R4-01/02 已修,目标范围仍有限) | 后台 job 改用非消费式 `ctx.jobs.events` 观察终态,不再用 `wait` 抑制原生通知;订阅前已终态可立即释放;文件工具按实际目标路径加锁并拒绝越界;shell/未知第三方工具仍只锁项目根 |
|
||||
| Q09 | 已修 | `store.test.js` Q09 + `route.test.js` Q09:跨项目核实 409 且不写事件;事件与状态同事务 |
|
||||
| Q10 | 已修 | `records.test.js` Q10:重复 draft/start 拒绝,新建/启动确认 |
|
||||
| Q11 | 部分修(R4-05 补强) | 真实 `selectSessionModel` 串行、失败不阻塞下一次、默认模型恢复不覆盖用户新选择;群 Session 失败抛错;补偿前检查 runtime 版本并保留用户新选择;固定模型完整恢复仍未真实宿主注入 |
|
||||
| Q12 | 已修(真实 Hook 级) | `client.test.js` Q12c 用 mini React hooks 挂载真实 `useSanshengState`:切项目先 loading、旧数据清空、B 失败后显示 B 错误;真实浏览器像素时间线仍未自动化 |
|
||||
| Q13 | 已修(R4-04 真实语义) | 真实 `catalog` 的 needsKey 先于 available 判断;服务端拒绝 needsKey/不在目录模型,前端禁用并标注 |
|
||||
|
||||
## 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.6 + ds-bot 0.3.2-sansheng.6(本地补丁 M-01–M-06) |
|
||||
| 数据保留/升级/回退 | v2→v3 只补字段;严格 schema 只拒绝损坏文件并保留 registry;不迁移旧十席数据 |
|
||||
| 真实截图与 UI 复核 | 有测试 profile 浅色截图;真实多项目/深色/窄屏仍缺 |
|
||||
|
|
|
|||
|
|
@ -27,6 +27,11 @@ 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` |
|
||||
| v0.2.4 原生共存模式 | 浏览器 `__SANSENG_WORKBENCH__=true`;DS-Bot 不安装全局 shell(`dsShell=false`);左栏原生 DSH 项目树、主聊天/输入框/设置入口保留;控制台 0 条 DS-Bot 重挂/设置冲突警告;右栏「角色」+「Bot 切换」可打开 | `evidence/host-native-coexistence.png` |
|
||||
| 深色/窄屏 | 深色 1440×900 与窄屏 900×700 下原生项目树/聊天/输入框保持;900 宽时侧栏收成图标,底部「三省」仍可点开右栏角色页签;无页面错误 | `evidence/host-dark.png`、`evidence/host-narrow.png` |
|
||||
| v0.2.5 重启检查 | `/sansheng/health` 200:store `ok`、registry `ok`、`writable:true`、`governance:true`、Bot 4;Q04 memory 集成只改插件代码,未影响隔离宿主加载 | 本次 HTTP 响应 |
|
||||
| v0.2.7 第四轮共存 | 浏览器 `marker=true`、`dsShell=false`、原生项目树/聊天保留、控制台 0 条 DS-Bot 重挂/设置冲突警告;右栏「角色」「Bot 切换」可打开 | 本次 Chromium 探测 |
|
||||
|
||||
HTTP 响应原文(初始空状态):
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# 发布说明(候选版本 v0.2.2 / ds-bot 0.3.2-sansheng.2)
|
||||
# 发布说明(候选版本 v0.2.7 / ds-bot 0.3.2-sansheng.7)
|
||||
|
||||
日期:2026-11-14
|
||||
状态:**候选版本**。可用于隔离测试环境;用户日常 desktop profile 未由实施者修改。
|
||||
|
|
@ -7,16 +7,48 @@
|
|||
|
||||
| 包 | 版本 | 文件 |
|
||||
| --- | --- | --- |
|
||||
| `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.7 | `dist/dsh-sansheng-sansheng-0.2.7.tgz` |
|
||||
| `ds-bot`(上游 0.3.2 + M-01–M-06) | 0.3.2-sansheng.7 | `dist/ds-bot-0.3.2-sansheng.7.tgz` |
|
||||
|
||||
云端预发布:`v0.2.2-sansheng`,https://git.qyhhh.top/DeepsSeekHarness/dsh-sansheng-liubu/releases/tag/v0.2.2-sansheng (两个 tarball 已作为 release assets 上传)。
|
||||
云端发布:**未执行**。按审查报告“不授权推送或发布”的约束,v0.2.7 只在本地构建了两个 tarball;待用户明确授权后再推送/开 PR/合并/发布。此前 `v0.2.2-sansheng` 仍是在线候选版本。
|
||||
|
||||
### v0.2.2 变更
|
||||
### v0.2.7 变更(第四轮复审)
|
||||
|
||||
- 角色卡模型下拉:`/sansheng/state` 返回可用模型目录,角色卡直接切换本项目该角色模型(无 API Key 时显示默认模型,不伪造可选项)。
|
||||
- Q11:模型配置先全部解析校验,再应用;任一无效零修改,中途失败/保存失败回滚 runtime 模型。
|
||||
- Q12:项目切换请求按上下文签名缓存,切到 B 后失败不会显示 A 的旧卡片与可操作内容。
|
||||
- R4-01/R4-02:后台 job 改用非消费式 `ctx.jobs.events` 观察终态,不再调用 `wait` 抑制原生完成通知;只在订阅到终态或订阅前 `get` 为终态时释放租约。
|
||||
- R4-02:文件类写工具按实际目标路径追加租约,父子嵌套根写同一文件会互斥;目标越出项目工作根直接拒绝。
|
||||
- R4-03:registry 严格校验 version/rooms/bots/updatedAt 与映射值;非法 schema 标 broken、阻止启动对账和 provision,且不覆盖坏 registry。
|
||||
- R4-04:真实 catalog 的 needsKey 先于 available 判断,服务端不再放行缺凭据模型。
|
||||
- R4-05:补偿前检查 runtime 是否仍是本次写入值,不覆盖用户新选择;恢复 appliedModel/appliedEffort 存在性;群 Session 失败改为抛错;默认模型恢复不覆盖等待期间的用户选择。
|
||||
- R4-06:三省卸载撤销 `__SANSENG_WORKBENCH__`、发 `sansheng:workbench-gone`、清理样式;DS-Bot 晚收到 ready 时释放设置壳并恢复原 surface 偏好。
|
||||
|
||||
### v0.2.6 变更(Q08 后台 job)
|
||||
|
||||
- 写工具结果里出现后台 job id 且宿主提供 `ctx.jobs` 时,根租约不再随工具调用返回而释放,而是交给 `jobs.wait`,job 完成/终止后才释放;无 jobs 服务或同步失败时仍按原路径释放。
|
||||
- 新增 Q08e 回归:后台 job 未结束前租约保留,结束后释放。
|
||||
|
||||
### v0.2.5 变更(第三轮复审补充)
|
||||
|
||||
- Q04 真实 memory 模块集成测试:peer stub loader 加载 ds-bot `memory.js`,验证被拒群记忆不进入 `agent/pre-step` 注入、显式 recall 返回拒绝,允许后才读取;同时避免注入空的群快照消息。
|
||||
|
||||
- UI01–UI03:三省客户端写入 `__SANSENG_WORKBENCH__` 标记;DS-Bot 进入原生共存模式,不安装全局 shell/conversation/主题/导航,不替换设置入口,不因缺少 TeamSidebar 重挂,不折叠宿主右栏。正向/反向加载顺序通过标记事件处理。
|
||||
- Q01/Q02:主状态缺失但 registry 有证据时 health=missing + writable=false;启动对账/provision/事务拒绝覆盖 registry;registry 自身损坏单独记录,双文件故障时治理和门禁显式拒绝。
|
||||
- Q08:工作根租约用 realpath 去 junction 别名,提交与写工具共用根锁,长工具每 5 分钟续租;后台 job 生命周期仍未覆盖。
|
||||
- Q11:整段 runtime→Store→补偿按项目串行;失败角色本身也进入补偿,保留 model/appliedModel 是否存在;补偿失败写 `config-recovery.jsonl` 和事件。
|
||||
- Q12:切换项目立即刷新唤醒、节流补 trailing;请求 12s 超时;Hook 保留 loading,加载中不显示初始化入口。
|
||||
- Q13:DS-Bot 暴露 `availabilityOf`,配置/创建项目时服务端拒绝 needsKey 或不在目录的模型。
|
||||
- 2026-11-13/14 的 v0.2.3 修复继续保留。
|
||||
|
||||
- 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 +69,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.4.tgz <绝对路径>\ds-bot-0.3.2-sansheng.4.tgz
|
||||
```
|
||||
4. 确认 `dsh.profile.bundles` 含 `dsh-sansheng-sansheng` 与 `ds-bot`。
|
||||
5. 彻底重启 DSH(插件宿主半改动只有重启生效)。
|
||||
|
|
@ -62,7 +94,13 @@ node <path-to-pnpm.cjs> pack --pack-destination ..\dist
|
|||
## 6. 已知限制(必须随版本说明)
|
||||
|
||||
- 真实模型 E2E(E01–E04)未执行;隔离测试 profile 无 API key。
|
||||
- Q04 记忆边界有真实 memory.js 集成测试(peer stub loader),覆盖群快照/显式 recall;真实模型/宿主记忆注入仍未做。
|
||||
- Q08 已覆盖已知写工具、同根/junction 别名、提交与写工具共用根锁、过期租约接管、后台 job `ctx.jobs.events`、文件目标/嵌套根;shell 命令内部写和未知第三方工具仍可能绕过目标锁。
|
||||
- Q11 有真实 `selectSessionModel` 串行/失败恢复、群 Session 失败、默认模型并发和 runtime CAS 回归;固定模型完整恢复未在真实宿主注入;sidecar 在 Store 完全不可写时也可能失败。
|
||||
- Q12 有真实 `useSanshengState` Hook 级测试(mini React hooks);真实浏览器像素时间线仍未自动化。
|
||||
- UI01–UI03 在隔离测试 profile 的浅色/深色 1440×900、窄屏 900×700 验证;三省卸载单测通过;DS-Bot 先加载的完整浏览器 disable/再启用未操作验证。
|
||||
- 真实模型 E2E(E01–E04)、长消息/连续工具流仍缺;不把 154 项单测写成真实 DSH E2E 全通过。
|
||||
- `workspace-groups-remote` 项目树右键菜单未在真实测试 profile 复现(DS Bot 页面占据左栏);组件级 contextMenus 测试通过。用户日常环境若项目树可见,右键「三省六部」应可用;若不可用,用左栏底部「三省」入口。
|
||||
- 深色模式、窄屏、长消息/连续工具流未截图验证。
|
||||
- 长消息/连续工具流未截图验证。
|
||||
- 项目树适配采用宿主原生 `contextMenus` + `sidebar.footer.action` + 右栏页签;不使用私有 DOM。
|
||||
- `ds-bot` 补丁需在升级上游后重放(见 `ds-bot/PATCHES.md` 升级步骤)。
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@
|
|||
- 发布:预发布 `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/`。
|
||||
- 第三轮审查修复 v0.2.7:`dsh-sansheng-sansheng@0.2.7` / `ds-bot@0.3.2-sansheng.7`,168/168 回归;UI01–UI03 原生共存、Q01/Q02 启动保护、Q11–Q13 补强;仍未推送/发布。
|
||||
- 当前状态:候选版本,真实模型 E2E(E01–E04)未执行;日常 desktop profile 未修改。
|
||||
|
||||
> 说明:仓库的 `master` 分支仍是旧版结构(工作台/panel 目录),与 `feat/dsbot` 不在同一历史线。
|
||||
|
|
|
|||
Binary file not shown.
|
After Width: | Height: | Size: 67 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
|
|
@ -23881,7 +23881,16 @@ function freePriority(entries2, { priority, key, id }) {
|
|||
const taken = entries2.filter((entry) => (key === void 0 || entry.options?.key === key) && (id === void 0 || entry.options?.id === id)).map((entry) => (entry.options?.priority ?? 0) - 1);
|
||||
return Math.min(priority, ...taken);
|
||||
}
|
||||
function sanshengNativeCoexistence() {
|
||||
try {
|
||||
return globalThis.__SANSENG_WORKBENCH__ === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function readMode(storage = globalThis.localStorage) {
|
||||
// 三省六部共存模式:保留宿主的项目树、聊天、主题、设置与右栏控制。
|
||||
if (sanshengNativeCoexistence()) return "agent";
|
||||
try {
|
||||
return storage.getItem(STORAGE.surface) === "agent" ? "agent" : "bot";
|
||||
} catch {
|
||||
|
|
@ -28784,7 +28793,16 @@ function apply(ctx) {
|
|||
let sidebarSaved = readSidebar();
|
||||
const sidebarPref = createSource(sidebarSaved.pref);
|
||||
const frame = createSource({ viewport: typeof window === "undefined" ? 0 : window.innerWidth, sidebarWidth: sidebarSaved.width, collapsedWidth: 0, collapsed: false });
|
||||
const surface = createSource({ mode: readMode(), plain: false });
|
||||
const surfaceMode = (() => {
|
||||
if (sanshengNativeCoexistence()) return "agent";
|
||||
try {
|
||||
if (ctx.sidebarRightTabs?.get?.("sansheng-roles") !== undefined) return "agent";
|
||||
} catch {
|
||||
/* no right tabs service */
|
||||
}
|
||||
return readMode();
|
||||
})();
|
||||
const surface = createSource({ mode: surfaceMode, plain: false });
|
||||
const settingsShellHeld = createSource(false);
|
||||
let settingsShell = null;
|
||||
let agentSessionCache = /* @__PURE__ */ new Set();
|
||||
|
|
@ -29376,6 +29394,38 @@ function apply(ctx) {
|
|||
} : null
|
||||
});
|
||||
}
|
||||
const sanshengCoexistence = () => {
|
||||
if (sanshengNativeCoexistence()) return true;
|
||||
try {
|
||||
return ctx.sidebarRightTabs?.get?.("sansheng-roles") !== undefined;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
ctx.effect(() => {
|
||||
let restoreMode;
|
||||
const enterNative = () => {
|
||||
if (!sanshengCoexistence()) return;
|
||||
if (restoreMode === undefined) restoreMode = actions.surfaceMode();
|
||||
if (actions.surfaceMode() === "bot") actions.setSurface("agent");
|
||||
};
|
||||
const leaveNative = () => {
|
||||
if (globalThis.__SANSENG_WORKBENCH__ === true) return;
|
||||
if (restoreMode === "bot") actions.setSurface("bot");
|
||||
restoreMode = undefined;
|
||||
};
|
||||
enterNative();
|
||||
try {
|
||||
window.addEventListener("sansheng:workbench-ready", enterNative);
|
||||
window.addEventListener("sansheng:workbench-gone", leaveNative);
|
||||
return () => {
|
||||
window.removeEventListener("sansheng:workbench-ready", enterNative);
|
||||
window.removeEventListener("sansheng:workbench-gone", leaveNative);
|
||||
};
|
||||
} catch {
|
||||
return void 0;
|
||||
}
|
||||
}, "ds-bot: sansheng coexistence");
|
||||
actions.signInEntry = () => ctx.slots.entries?.("settings.models.sign-in")?.[0] ?? null;
|
||||
actions.canSignIn = () => Boolean(actions.signInEntry());
|
||||
actions.signIn = () => ui2.set((state) => ({ ...state, signIn: (state.signIn ?? 0) + 1 }));
|
||||
|
|
@ -29513,12 +29563,31 @@ function apply(ctx) {
|
|||
}
|
||||
const face = () => ({ actions, hooks: { roster, ui: ui2, activity, work, memoryNews, registry, turnClock, live, computer, cards, heldCards, browserPages, browserTabs, browserHolds, surface, update, frame, sidebarPref, settingsShellHeld } });
|
||||
ctx.effect(() => {
|
||||
if (sanshengNativeCoexistence()) return void 0;
|
||||
try {
|
||||
if (ctx.sidebarRightTabs?.get?.("sansheng-roles") !== undefined) return void 0;
|
||||
} catch {
|
||||
/* no right tabs */
|
||||
}
|
||||
const offStyles = installCompiledStyles(SETTINGS_SHELL_CSS, "settings-shell");
|
||||
settingsShell = installSettingsShell(ctx, { face, actions, ui: ui2, held: settingsShellHeld });
|
||||
return () => {
|
||||
let dropped = false;
|
||||
const drop = () => {
|
||||
if (dropped) return;
|
||||
dropped = true;
|
||||
settingsShell?.dispose();
|
||||
settingsShell = null;
|
||||
offStyles();
|
||||
offStyles?.();
|
||||
};
|
||||
const onReady = () => drop();
|
||||
try {
|
||||
window.addEventListener("sansheng:workbench-ready", onReady);
|
||||
} catch {
|
||||
/* no window */
|
||||
}
|
||||
return () => {
|
||||
try { window.removeEventListener("sansheng:workbench-ready", onReady); } catch { /* no window */ }
|
||||
drop();
|
||||
};
|
||||
}, "ds-bot: settings shell");
|
||||
const queueFace = (sessionId) => ({
|
||||
|
|
@ -29603,11 +29672,13 @@ function apply(ctx) {
|
|||
}
|
||||
};
|
||||
ctx.effect(() => {
|
||||
if (sanshengCoexistence()) return void 0;
|
||||
const sidebar = ctx.get("sidebarRight");
|
||||
if (!sidebar) return void 0;
|
||||
let open = rightColumnOpen(document);
|
||||
const switchWindow = createSwitchWindow((done) => setTimeout(done, 400));
|
||||
const collapseColumn = () => {
|
||||
if (sanshengCoexistence()) return;
|
||||
try {
|
||||
if (sidebar.isExpanded()) sidebar.toggleExpanded();
|
||||
} catch (error) {
|
||||
|
|
@ -29615,6 +29686,7 @@ function apply(ctx) {
|
|||
}
|
||||
};
|
||||
const observer = new MutationObserver(() => {
|
||||
if (sanshengCoexistence()) return;
|
||||
const next = rightColumnOpen(document);
|
||||
const opening = next && !open;
|
||||
open = next;
|
||||
|
|
@ -29630,6 +29702,7 @@ function apply(ctx) {
|
|||
const offMounted = sidebar.mounted.subscribe(() => switchWindow.moved());
|
||||
let drawer = ui2.getSnapshot().details !== null;
|
||||
const offUi = ui2.subscribe(() => {
|
||||
if (sanshengCoexistence()) return;
|
||||
const next = ui2.getSnapshot().details !== null;
|
||||
if (next && !drawer && drawerOpened(rightColumnOpen(document)) === "collapse-column") collapseColumn();
|
||||
drawer = next;
|
||||
|
|
@ -29875,6 +29948,8 @@ function apply(ctx) {
|
|||
let verifyTimer = 0;
|
||||
let verifyAttempts = 0;
|
||||
const verifySidebar = () => {
|
||||
// UI02:共存模式本来就不安装 TeamSidebar,不能把它当成缺失并重挂 shell。
|
||||
if (sanshengCoexistence()) return;
|
||||
if (!groupsFor(surface.getSnapshot()).shell) return;
|
||||
let landed = false;
|
||||
let declared = true;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "ds-bot",
|
||||
"version": "0.3.2-sansheng.2",
|
||||
"version": "0.3.2-sansheng.7",
|
||||
"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) })))
|
||||
|
|
@ -941,7 +948,7 @@ export function install(rt) {
|
|||
if (agent.session?.deriveMessages?.().some(isGroupMemory)) return undefined
|
||||
} catch { /* no history to look in: the snapshot goes in */ }
|
||||
const group = groupSection(roomId, bot)
|
||||
if (group.failed) return undefined
|
||||
if (group.failed || group.text.trim() === '') return undefined
|
||||
return createUserMessage({
|
||||
content: [{ type: 'text', text: group.text }],
|
||||
source: { kind: GROUP_MEMORY_SOURCE, form: 'snapshot', sections: [{ name: GROUP_MEMORY_SOURCE, text: group.text }] },
|
||||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -234,7 +234,12 @@ export function install(rt) {
|
|||
})
|
||||
const saved = result?.selected ?? { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) }
|
||||
if (before?.provider && before?.model && !sameSelection(before, saved)) {
|
||||
await defaults.saveSelection(before).catch(error => rt.warn('ds-bot: the default model was not restored: %s', error))
|
||||
// R4-05:等待期间用户可能已经在原生设置里改了默认模型;只恢复
|
||||
// 仍停留在旧值的情况,不覆盖用户的新选择。
|
||||
const now = defaults?.currentSelection?.()
|
||||
if (now === undefined || sameSelection(now, before) || sameSelection(now, saved)) {
|
||||
await defaults.saveSelection(before).catch(error => rt.warn('ds-bot: the default model was not restored: %s', error))
|
||||
}
|
||||
}
|
||||
sessionSelections.set(sessionId, { provider, model, reasoningEffort })
|
||||
return result
|
||||
|
|
@ -254,11 +259,19 @@ export function install(rt) {
|
|||
const ownChanged = force || bot.appliedModel !== ref || (bot.appliedEffort ?? undefined) !== effort
|
||||
const route = { ...splitRef(ref), ...(effort === undefined ? {} : { reasoningEffort: effort }) }
|
||||
if (ownChanged) await selectSessionModel(rt.chatOf(bot.id), route)
|
||||
let groupFailure
|
||||
for (const sessionId of rt.groupSessionsOf(bot.id)) {
|
||||
const applied = sessionSelections.get(sessionId)
|
||||
if (!force && applied !== undefined && sameSelection(applied, route)) continue
|
||||
await selectSessionModel(sessionId, route)
|
||||
.catch(error => rt.warn('ds-bot: model for %s in a group not applied: %s', bot.name, error))
|
||||
.catch(error => {
|
||||
groupFailure ??= error
|
||||
rt.warn('ds-bot: model for %s in a group not applied: %s', bot.name, error)
|
||||
})
|
||||
}
|
||||
// R4-05:群 Session 失败不能只 warn 后继续推进 appliedModel;配置入口要看到失败。
|
||||
if (groupFailure !== undefined) {
|
||||
throw new Error(`模型已在本人会话应用,但群会话应用失败:${groupFailure?.message ?? groupFailure}`)
|
||||
}
|
||||
if (!ownChanged) return ref
|
||||
bot.appliedModel = ref
|
||||
|
|
@ -322,9 +335,23 @@ export function install(rt) {
|
|||
if (bot !== undefined) await applyModel(bot, { force: true })
|
||||
}
|
||||
|
||||
// Q13:给配置入口一个服务端可用性判断。catalog() 只返回可应答模型,
|
||||
// 但 catalogCache 保存了全部条目(含 needsKey),因此不能只看 ref 是否存在。
|
||||
async function availabilityOf(ref) {
|
||||
const entries = await catalog()
|
||||
// Q13/R4-04:catalog() 返回的是可应答子集,needsKey 条目只在 cache 里;
|
||||
// 必须先查 cache,否则“仍在目录但缺 key”会被误判为可用。
|
||||
const cached = catalogCache.value.find(entry => entry.ref === ref)
|
||||
if (cached?.needsKey === true) {
|
||||
return { available: false, needsKey: true, reason: `模型 ${ref} 的提供方尚未配置凭据。` }
|
||||
}
|
||||
if (entries.some(entry => entry.ref === ref)) return { available: true }
|
||||
return { available: false, needsKey: false, reason: `模型 ${ref} 不在当前可用目录。` }
|
||||
}
|
||||
|
||||
Object.assign(rt, {
|
||||
catalog, cachedCatalog: () => answerable(catalogCache.value), cachedDefault: () => pickDefault(catalogCache.value),
|
||||
defaultRef, defaultModel, defaultBotModel, defaultEffort, isUsable, resolveModel, desiredModel, reasoningOf, resolveEffort, desiredEffort,
|
||||
defaultRef, defaultModel, defaultBotModel, defaultEffort, isUsable, availabilityOf, resolveModel, desiredModel, reasoningOf, resolveEffort, desiredEffort,
|
||||
selectSessionModel, applyModel, waitForModel, syncModels, routeRefused, dropCatalog,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ window.__ModuleLoader__.load({
|
|||
const TAB_KIND = 'sansheng-roles'
|
||||
const CSS_ID = 'dsh-sansheng-roles'
|
||||
const POLL_MS = 4000
|
||||
const REQUEST_TIMEOUT_MS = 12000
|
||||
const ACTIVE_KEY = 'dsh.sansheng.activeProject'
|
||||
const ROLE_ORDER = ['lead', 'shangshu', 'gongbu']
|
||||
const ROLE_MARK = { lead: '丞', shangshu: '尚', gongbu: '工' }
|
||||
|
|
@ -117,6 +118,14 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
}
|
||||
|
||||
function removeCss() {
|
||||
if (typeof document === 'undefined') return
|
||||
try {
|
||||
const selector = 'style[data-plugin-css=' + JSON.stringify(CSS_ID) + ']'
|
||||
document.querySelector(selector)?.remove()
|
||||
} catch (error) { /* 清理失败不影响卸载 */ }
|
||||
}
|
||||
|
||||
function messageOf(error) {
|
||||
if (error === null || error === undefined) return '未知错误'
|
||||
if (error.message) return String(error.message)
|
||||
|
|
@ -321,6 +330,7 @@ window.__ModuleLoader__.load({
|
|||
const ctx = opts.ctx
|
||||
const fetchImpl = opts.fetchImpl || (typeof fetch === 'function' ? fetch : null)
|
||||
const intervalMs = Number.isFinite(opts.intervalMs) ? opts.intervalMs : POLL_MS
|
||||
const requestTimeoutMs = Number.isFinite(opts.requestTimeoutMs) ? opts.requestTimeoutMs : REQUEST_TIMEOUT_MS
|
||||
const onChange = typeof opts.onChange === 'function' ? opts.onChange : () => {}
|
||||
let latestRequestId = 0
|
||||
let stopped = false
|
||||
|
|
@ -340,10 +350,20 @@ 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
|
||||
const controller = typeof AbortController === 'function' ? new AbortController() : null
|
||||
const timeout = controller ? setTimeout(() => controller.abort(), requestTimeoutMs) : null
|
||||
try {
|
||||
if (!fetchImpl) throw new Error('宿主没有 fetch')
|
||||
const response = await fetchImpl(stateUrlOf(context), { cache: 'no-cache' })
|
||||
const response = await fetchImpl(stateUrlOf(context), {
|
||||
cache: 'no-cache',
|
||||
...(controller ? { signal: controller.signal } : {}),
|
||||
})
|
||||
if (!response || response.ok === false) throw new Error('HTTP ' + (response && response.status ? response.status : '???'))
|
||||
const data = await response.json()
|
||||
if (stopped || isStale(requestId, latestRequestId)) return
|
||||
|
|
@ -358,8 +378,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,
|
||||
|
|
@ -369,6 +393,7 @@ window.__ModuleLoader__.load({
|
|||
context,
|
||||
})
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout)
|
||||
if (!stopped && !isStale(requestId, latestRequestId)) schedule(retryImmediately ? 0 : intervalMs)
|
||||
}
|
||||
}
|
||||
|
|
@ -392,6 +417,47 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
}
|
||||
|
||||
function mergePollState(prev, next) {
|
||||
return {
|
||||
loading: next.loading === undefined ? false : next.loading,
|
||||
error: next.error,
|
||||
data: next.data === undefined ? prev.data : next.data,
|
||||
updatedAt: next.updatedAt === undefined ? prev.updatedAt : next.updatedAt,
|
||||
context: next.context || prev.context,
|
||||
}
|
||||
}
|
||||
|
||||
function createWakeGate({ refresh, signatureOf, throttleMs = 1000 }) {
|
||||
let lastWake = 0
|
||||
let timer = null
|
||||
let lastSignature = signatureOf()
|
||||
const fire = () => {
|
||||
lastWake = Date.now()
|
||||
refresh()
|
||||
}
|
||||
const wake = () => {
|
||||
const signature = signatureOf()
|
||||
if (signature !== lastSignature) {
|
||||
lastSignature = signature
|
||||
if (timer) { clearTimeout(timer); timer = null }
|
||||
fire()
|
||||
return
|
||||
}
|
||||
const now = Date.now()
|
||||
if (now - lastWake < throttleMs) {
|
||||
if (!timer) timer = setTimeout(() => { timer = null; fire() }, throttleMs - (now - lastWake))
|
||||
return
|
||||
}
|
||||
fire()
|
||||
}
|
||||
return {
|
||||
wake,
|
||||
dispose() {
|
||||
if (timer) { clearTimeout(timer); timer = null }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function useSanshengState(ctx, activeProjectId) {
|
||||
const [state, setState] = React.useState({ loading: true, error: null, data: null, updatedAt: 0, context: null })
|
||||
const [reloadToken, setReloadToken] = React.useState(0)
|
||||
|
|
@ -403,35 +469,27 @@ window.__ModuleLoader__.load({
|
|||
intervalMs: POLL_MS,
|
||||
onChange(next) {
|
||||
if (!alive) return
|
||||
setState(prev => ({
|
||||
loading: false,
|
||||
error: next.error,
|
||||
data: next.data === undefined ? prev.data : next.data,
|
||||
updatedAt: next.updatedAt === undefined ? prev.updatedAt : next.updatedAt,
|
||||
context: next.context || prev.context,
|
||||
}))
|
||||
setState(prev => mergePollState(prev, next))
|
||||
},
|
||||
})
|
||||
poller.start()
|
||||
const detach = []
|
||||
let lastWake = 0
|
||||
const wake = () => {
|
||||
const now = Date.now()
|
||||
if (now - lastWake < 1000) return
|
||||
lastWake = now
|
||||
poller.refresh()
|
||||
}
|
||||
const gate = createWakeGate({
|
||||
refresh: () => poller.refresh(),
|
||||
signatureOf: () => contextSignature(workspaceContextOf(ctx)),
|
||||
})
|
||||
for (const name of ['sessions', 'workspaces']) {
|
||||
try {
|
||||
const service = serviceOf(ctx, name)
|
||||
const list = service && service.list
|
||||
if (list && typeof list.subscribe === 'function') {
|
||||
detach.push(list.subscribe(wake))
|
||||
detach.push(list.subscribe(gate.wake))
|
||||
}
|
||||
} catch (error) { /* 老宿主没有可订阅的列表 */ }
|
||||
}
|
||||
return () => {
|
||||
alive = false
|
||||
gate.dispose()
|
||||
for (const off of detach) {
|
||||
try { off() } catch (error) { /* 忽略 */ }
|
||||
}
|
||||
|
|
@ -729,7 +787,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, [
|
||||
|
|
@ -1003,7 +1066,9 @@ window.__ModuleLoader__.load({
|
|||
])
|
||||
: null
|
||||
let body
|
||||
if (uninitialized) {
|
||||
if (!project && loading) {
|
||||
body = [h('div', { key: 'loading', className: 'ss-empty', children: '正在载入当前项目状态…' })]
|
||||
} else if (uninitialized) {
|
||||
body = h(InitPanel, { key: 'init', ctx, context, onDone: onRefresh })
|
||||
} else if (project) {
|
||||
const roles = rolesOf(project)
|
||||
|
|
@ -1098,6 +1163,27 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
|
||||
function apply(ctx) {
|
||||
// 原生共存模式的稳定标记:DS-Bot 客户端据此不安装全局 shell/conversation。
|
||||
// 通过 window 事件支持 DS-Bot 先加载、三省后加载的顺序;effect 清理时撤销。
|
||||
ctx.effect(() => {
|
||||
try {
|
||||
globalThis.__SANSENG_WORKBENCH__ = true
|
||||
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
|
||||
const event = typeof Event === 'function' ? new Event('sansheng:workbench-ready') : { type: 'sansheng:workbench-ready' }
|
||||
window.dispatchEvent(event)
|
||||
}
|
||||
} catch (error) { /* 标记失败不阻止工作台 */ }
|
||||
return () => {
|
||||
try {
|
||||
globalThis.__SANSENG_WORKBENCH__ = false
|
||||
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
|
||||
const event = typeof Event === 'function' ? new Event('sansheng:workbench-gone') : { type: 'sansheng:workbench-gone' }
|
||||
window.dispatchEvent(event)
|
||||
}
|
||||
} catch (error) { /* 撤销失败不阻止卸载 */ }
|
||||
removeCss()
|
||||
}
|
||||
}, '三省六部:原生共存标记')
|
||||
ensureCss()
|
||||
const wrap = component => props => h(component, { ...props, __ctx: ctx })
|
||||
|
||||
|
|
@ -1153,6 +1239,10 @@ window.__ModuleLoader__.load({
|
|||
workspaceContextOf,
|
||||
workspaceIdOf,
|
||||
createStatePoller,
|
||||
useSanshengState,
|
||||
React,
|
||||
mergePollState,
|
||||
createWakeGate,
|
||||
normalizeModels,
|
||||
openWorkbench,
|
||||
openRolesTab,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-sansheng-sansheng",
|
||||
"version": "0.2.2",
|
||||
"version": "0.2.7",
|
||||
"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', '交付成果在审查之后发生了变化(文件、未跟踪交付物或提交不同);旧审查已失效,请重新审查并生成新快照。')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,6 +47,10 @@ export function installGates({ ctx, store, dsbot, isBotSession }) {
|
|||
}
|
||||
|
||||
const health = typeof store.health === 'function' ? store.health() : { status: 'ok' }
|
||||
// Q02:主状态与 registry 双故障时门禁无法判断该群是否受治理,直接拒绝。
|
||||
if (health.status !== 'ok' && health.registryStatus === 'broken') {
|
||||
return '三省六部:主状态与治理 registry 均不可读,无法判定该群是否受治理;本次目标修改未执行。'
|
||||
}
|
||||
let project = store.projectByRoom(roomId)
|
||||
if (!project) {
|
||||
const hinted = store.registryProjectForRoom?.(roomId)
|
||||
|
|
@ -90,6 +94,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,108 @@
|
|||
/**
|
||||
* 对外治理服务: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 中有绑定但主状态缺失' }
|
||||
// Q02:主状态与 registry 双故障时,连“非受治理”也不能确定。
|
||||
if (health.status !== 'ok' && health.registryStatus === 'broken') {
|
||||
return { kind: 'unavailable', 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 中有绑定但主状态缺失' }
|
||||
if (health.status !== 'ok' && health.registryStatus === 'broken') {
|
||||
return { kind: 'unavailable', 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 { relative, 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({ ctx, 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,195 @@ 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({ ctx, 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}`
|
||||
const taskId = String(exec.id ?? exec.arguments?.task ?? 'write')
|
||||
const leases = []
|
||||
const releaseAll = async () => {
|
||||
for (const item of leases.reverse()) {
|
||||
await store.releaseRootLease(item.root, item.holder).catch(() => {})
|
||||
}
|
||||
leases.length = 0
|
||||
}
|
||||
const acquire = async (target, leaseHolder) => {
|
||||
try {
|
||||
const lease = await store.acquireRootLease(target, { holder: leaseHolder, taskId })
|
||||
if (lease.ok) leases.push({ root: target, holder: leaseHolder })
|
||||
return lease
|
||||
} catch (error) {
|
||||
return { ok: false, reason: `无法建立工作根写租约(${error?.message ?? error})` }
|
||||
}
|
||||
}
|
||||
const rootLease = await acquire(root, holder)
|
||||
if (!rootLease.ok) return `三省六部:${rootLease.reason} 本次文件写未执行。`
|
||||
|
||||
// R4-02:只锁 project.workDir 无法覆盖父子嵌套根写同一文件。
|
||||
// 文件类工具再按实际目标路径加一把锁;目标越出项目根则明确拒绝。
|
||||
const target = writeTargetOf(exec, root)
|
||||
if (target === OUTSIDE_ROOT) {
|
||||
await releaseAll()
|
||||
return '三省六部:写入目标超出项目工作根,本次文件写未执行。'
|
||||
}
|
||||
if (target) {
|
||||
const targetLease = await acquire(target, `${holder}:target`)
|
||||
if (!targetLease.ok) {
|
||||
await releaseAll()
|
||||
return `三省六部:${targetLease.reason} 本次文件写未执行。`
|
||||
}
|
||||
}
|
||||
|
||||
const renew = setInterval(() => {
|
||||
for (const item of leases) store.acquireRootLease(item.root, { holder: item.holder, taskId }).catch(() => {})
|
||||
}, 5 * 60 * 1000)
|
||||
renew.unref?.()
|
||||
let background = false
|
||||
try {
|
||||
const result = await next()
|
||||
// Q08/R4-01:后台 job 用非消费式 events 观察终态,不能用 wait。
|
||||
const jobId = backgroundJobIdOf(result)
|
||||
let jobs
|
||||
try { jobs = ctx.get?.('jobs', false) } catch { jobs = undefined }
|
||||
if (jobId && jobs && typeof jobs.events?.subscribe === 'function') {
|
||||
const sessionId = exec.agent?.id
|
||||
try {
|
||||
background = watchBackgroundJob({
|
||||
jobs, store, jobId, sessionId, leases, renew, releaseAll,
|
||||
})
|
||||
} catch {
|
||||
background = false
|
||||
}
|
||||
}
|
||||
return result
|
||||
} finally {
|
||||
if (!background) {
|
||||
clearInterval(renew)
|
||||
// 真实执行结束、抛错或取消都释放;进程被杀时最多留到租约过期。
|
||||
await releaseAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const OUTSIDE_ROOT = Symbol('outside-root')
|
||||
|
||||
function stringArg(args, keys) {
|
||||
for (const key of keys) {
|
||||
const value = args?.[key]
|
||||
if (typeof value === 'string' && value.trim() !== '') return value.trim()
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function writeTargetOf(exec, root) {
|
||||
const name = String(exec.name ?? '')
|
||||
const args = exec.arguments ?? {}
|
||||
let target
|
||||
if (name === 'move' || name === 'copy' || name === 'move_file' || name === 'copy_file') {
|
||||
target = stringArg(args, ['destination', 'dest', 'to'])
|
||||
} else {
|
||||
target = stringArg(args, ['path', 'file_path', 'filePath', 'target'])
|
||||
}
|
||||
if (target === undefined) return undefined
|
||||
const absolute = resolve(root, target)
|
||||
const rel = relative(root, absolute)
|
||||
if (rel === '' || rel.startsWith('..') || resolve(root, rel) !== absolute) return OUTSIDE_ROOT
|
||||
return absolute
|
||||
}/** DSH 后台 job id 形如 `<kind>-<16 hex>`;只认工具结果里明确出现的 id。 */
|
||||
function backgroundJobIdOf(result) {
|
||||
const direct = result?.jobId ?? result?.job?.id
|
||||
if (typeof direct === 'string' && direct.trim() !== '') return direct.trim()
|
||||
const text = textOfResult(result)
|
||||
const match = text.match(/\b([a-z][a-z0-9-]*-[0-9a-f]{16})\b/i)
|
||||
return match?.[1]
|
||||
}
|
||||
|
||||
const JOB_TERMINAL = new Set(['completed', 'killed', 'failed'])
|
||||
|
||||
/**
|
||||
* Q08/R4-01:用非消费式的 `jobs.events` 观察终态,不能用 `jobs.wait`——
|
||||
* wait 会把结算标成 awaited,DSH 原生完成通知就不会再投递。
|
||||
* 先订阅再 get,覆盖“订阅前已经结束”的竞态;只有终态才释放租约。
|
||||
*/
|
||||
function watchBackgroundJob({ jobs, jobId, sessionId, renew, releaseAll }) {
|
||||
let done = false
|
||||
let unsubscribe = () => {}
|
||||
let expiry
|
||||
const finish = async () => {
|
||||
if (done) return
|
||||
done = true
|
||||
try { unsubscribe() } catch { /* 已取消 */ }
|
||||
if (expiry) clearTimeout(expiry)
|
||||
clearInterval(renew)
|
||||
await releaseAll()
|
||||
}
|
||||
unsubscribe = jobs.events.subscribe({ owner: sessionId }, event => {
|
||||
if (event?.type === 'settled' && event.job?.id === jobId) void finish()
|
||||
})
|
||||
try {
|
||||
const current = jobs.get(jobId, sessionId)
|
||||
if (current && JOB_TERMINAL.has(current.status)) void finish()
|
||||
} catch {
|
||||
// 读不到状态时不假装任务完成:保持租约,留到 TTL/显式终态事件。
|
||||
expiry = setTimeout(() => { void finish() }, 24 * 60 * 60 * 1000)
|
||||
expiry.unref?.()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
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 })
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { appendFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { clampInt, instructionsFor, ROOM_NOTICE } from './texts.js'
|
||||
import { ROLE_COLOR, ROLE_IDS, ROLE_LABEL } from './roles.js'
|
||||
|
||||
|
|
@ -60,7 +62,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)。' }
|
||||
|
|
@ -90,7 +92,12 @@ export async function provisionProject({ ctx, store, dsbot, args, actor }) {
|
|||
const raw = args.models?.[role]
|
||||
if (raw === undefined || raw === null || String(raw).trim() === '') continue
|
||||
try {
|
||||
models[role] = await rt.resolveModel(String(raw).trim())
|
||||
const resolved = await rt.resolveModel(String(raw).trim())
|
||||
if (typeof rt.availabilityOf === 'function') {
|
||||
const availability = await rt.availabilityOf(resolved)
|
||||
if (!availability.available) return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${availability.reason ?? '未配置凭据或不在目录'}` }
|
||||
}
|
||||
models[role] = resolved
|
||||
} catch (error) {
|
||||
return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}` }
|
||||
}
|
||||
|
|
@ -270,56 +277,157 @@ export async function bindProject({ store, dsbot, rt, args }) {
|
|||
}
|
||||
|
||||
/** 只影响本项目的模型/预算/自动返工/交付范围配置。 */
|
||||
const CONFIG_LOCKS = new Map()
|
||||
|
||||
/** Q11:补偿失败要留下可重新查询的 sidecar,不能只返回一次文本。 */
|
||||
async function recordRecovery(store, projectId, detail) {
|
||||
if (!store?.file) return false
|
||||
try {
|
||||
const file = join(dirname(store.file), 'config-recovery.jsonl')
|
||||
await appendFile(file, `${JSON.stringify({ projectId, at: new Date().toISOString(), ...detail })}\n`, 'utf8')
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeBeforeOf(bot) {
|
||||
return {
|
||||
exists: bot !== undefined,
|
||||
hadModel: bot !== undefined && Object.hasOwn(bot, 'model'),
|
||||
model: bot?.model,
|
||||
hadApplied: bot !== undefined && Object.hasOwn(bot, 'appliedModel'),
|
||||
appliedModel: bot?.appliedModel,
|
||||
hadAppliedEffort: bot !== undefined && Object.hasOwn(bot, 'appliedEffort'),
|
||||
appliedEffort: bot?.appliedEffort,
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreRuntimeModel(rt, item) {
|
||||
if (!item?.botId || !item.before?.exists || !rt || typeof rt.updateBot !== 'function') return
|
||||
const before = item.before
|
||||
const bot = typeof rt.botOf === 'function' ? rt.botOf(item.botId) : undefined
|
||||
// R4-05:补偿前先确认 runtime 仍是本次写入的值;用户/原生设置在窗口里
|
||||
// 改成别的值后,不能用旧快照覆盖用户的新选择。
|
||||
if (bot && item.resolved !== undefined && Object.hasOwn(bot, 'model') && bot.model !== item.resolved) {
|
||||
// runtime 已经是旧值(失败角色可能根本没写成功):仍走一次恢复调用,
|
||||
// 让审计看到补偿;只有既不是新值也不是旧值时才拒绝覆盖用户的新选择。
|
||||
const alreadyBefore = (before.hadModel && bot.model === before.model)
|
||||
|| (!before.hadModel && bot.model == null)
|
||||
if (!alreadyBefore) throw new Error('runtime 模型已被其他设置修改,补偿未覆盖')
|
||||
}
|
||||
// 恢复 appliedModel/appliedEffort 的“存在性”,让 updateBot 的 applyModel
|
||||
// 真正重选 Session,而不是删了 bot.model 却把 Session 留在新模型。
|
||||
if (bot) {
|
||||
if (before.hadApplied) bot.appliedModel = before.appliedModel
|
||||
else delete bot.appliedModel
|
||||
if (before.hadAppliedEffort) bot.appliedEffort = before.appliedEffort
|
||||
else delete bot.appliedEffort
|
||||
}
|
||||
const patch = before.hadModel
|
||||
? { model: before.model }
|
||||
: { model: null }
|
||||
await rt.updateBot(item.botId, patch, undefined)
|
||||
const after = rt.botOf?.(item.botId)
|
||||
if (before.hadModel) {
|
||||
if (!after || after.model !== before.model) throw new Error('恢复后 runtime model 与快照不一致')
|
||||
} else if (after && Object.hasOwn(after, 'model')) {
|
||||
throw new Error('恢复后 runtime 仍保留 model')
|
||||
}
|
||||
}
|
||||
|
||||
async function rollbackRuntime(rt, applied) {
|
||||
const failed = []
|
||||
for (const item of [...applied].reverse()) {
|
||||
try {
|
||||
await restoreRuntimeModel(rt, item)
|
||||
} catch (error) {
|
||||
failed.push(`${ROLE_LABEL[item.role]}(${error?.message ?? error})`)
|
||||
}
|
||||
}
|
||||
return failed
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个项目串行执行整段 runtime → Store → 补偿;否则 A 的失败补偿会撤销 B 的成功修改。
|
||||
*/
|
||||
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 prior = CONFIG_LOCKS.get(project.id) ?? Promise.resolve()
|
||||
let release
|
||||
const gate = new Promise(resolve => { release = resolve })
|
||||
const tail = prior.then(() => gate)
|
||||
CONFIG_LOCKS.set(project.id, tail)
|
||||
await prior
|
||||
try {
|
||||
return await updateProjectConfigLocked({ ctx, store, args })
|
||||
} finally {
|
||||
release()
|
||||
if (CONFIG_LOCKS.get(project.id) === tail) CONFIG_LOCKS.delete(project.id)
|
||||
}
|
||||
}
|
||||
|
||||
async function updateProjectConfigLocked({ 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 = []
|
||||
let rollbackModels = []
|
||||
let appliedModels = []
|
||||
|
||||
if (args.models && typeof args.models === 'object') {
|
||||
const models = { ...project.models }
|
||||
const resolvedModels = []
|
||||
// 先解析校验全部模型,任何一个不可用就零修改(Q11)。
|
||||
// 先解析校验全部模型,任何一个不可用就零修改(Q11/Q13)。
|
||||
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)
|
||||
if (rt && typeof rt.availabilityOf === 'function') {
|
||||
const availability = await rt.availabilityOf(resolved)
|
||||
if (!availability.available) {
|
||||
return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${availability.reason ?? '未配置凭据或不在目录'}。本次没有修改任何模型。` }
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return { ok: false, text: `${ROLE_LABEL[role]}的模型“${raw}”不可用:${error?.message ?? error}。本次没有修改任何模型。` }
|
||||
}
|
||||
const botId = project.bots?.[role]
|
||||
const bot = rt && typeof rt.botOf === 'function' && botId ? rt.botOf(botId) : undefined
|
||||
resolvedModels.push({
|
||||
role,
|
||||
botId,
|
||||
resolved,
|
||||
previousRuntime: bot?.model ?? bot?.appliedModel ?? null,
|
||||
previousConfig: project.models?.[role] ?? null,
|
||||
})
|
||||
resolvedModels.push({ role, botId, resolved, before: runtimeBeforeOf(bot) })
|
||||
}
|
||||
const applied = []
|
||||
for (const item of resolvedModels) {
|
||||
// 先登记再调用:真实 updateBot 可能已改 model 后在 applyModel 抛错。
|
||||
appliedModels.push(item)
|
||||
if (rt && typeof rt.updateBot === 'function' && item.botId) {
|
||||
try {
|
||||
await rt.updateBot(item.botId, { model: item.resolved }, undefined)
|
||||
applied.push(item)
|
||||
} catch (error) {
|
||||
const rollback = []
|
||||
for (const undo of applied.reverse()) {
|
||||
try {
|
||||
await rt.updateBot(undo.botId, { model: undo.previousRuntime }, undefined)
|
||||
} catch (undoError) {
|
||||
rollback.push(`${ROLE_LABEL[undo.role]}(${undoError?.message ?? undoError})`)
|
||||
}
|
||||
const failed = await rollbackRuntime(rt, appliedModels)
|
||||
let recoveryPersisted = false
|
||||
if (failed.length > 0) {
|
||||
recoveryPersisted = await recordRecovery(store, project.id, {
|
||||
reason: `更新${ROLE_LABEL[item.role]}失败`,
|
||||
failed,
|
||||
before: item.before,
|
||||
desired: item.resolved,
|
||||
})
|
||||
await store.addEvent?.({
|
||||
kind: 'config-rollback-failed',
|
||||
projectId: project.id,
|
||||
summary: `更新${ROLE_LABEL[item.role]}失败;回滚失败:${failed.join('、')};before=${JSON.stringify(item.before)}`,
|
||||
}).catch?.(() => {})
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
recoveryRequired: failed.length > 0,
|
||||
text: `更新${ROLE_LABEL[item.role]}模型失败:${error?.message ?? error}。`
|
||||
+ (rollback.length > 0 ? `已回滚其余角色,但${rollback.join('、')}回滚失败,请检查实际模型配置。` : '已回滚本次已修改的模型。'),
|
||||
+ (failed.length > 0
|
||||
? `部分模型回滚失败(${failed.join('、')}),${recoveryPersisted ? '已写入 config-recovery.jsonl' : '待恢复事件写入也失败'},请检查实际模型配置。`
|
||||
: '已回滚本次已修改的模型。'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -327,8 +435,6 @@ export async function updateProjectConfig({ ctx, store, args }) {
|
|||
changed.push(`${ROLE_LABEL[item.role]}模型=${item.resolved}`)
|
||||
}
|
||||
patch.models = models
|
||||
// 保存失败时也要把 runtime 恢复,不能只回滚 Store。
|
||||
rollbackModels = applied
|
||||
}
|
||||
if (args.maxReworks !== undefined) {
|
||||
patch.maxReworks = clampInt(args.maxReworks, project.maxReworks ?? 3, 1, 10)
|
||||
|
|
@ -349,19 +455,31 @@ export async function updateProjectConfig({ ctx, store, args }) {
|
|||
try {
|
||||
await store.updateProject(project.id, patch)
|
||||
} catch (error) {
|
||||
const rollback = []
|
||||
for (const undo of rollbackModels.reverse()) {
|
||||
try {
|
||||
if (rt && typeof rt.updateBot === 'function') await rt.updateBot(undo.botId, { model: undo.previousRuntime }, undefined)
|
||||
} catch (undoError) {
|
||||
rollback.push(`${ROLE_LABEL[undo.role]}(${undoError?.message ?? undoError})`)
|
||||
}
|
||||
const failed = await rollbackRuntime(rt, appliedModels)
|
||||
let recoveryPersisted = false
|
||||
if (failed.length > 0) {
|
||||
recoveryPersisted = await recordRecovery(store, project.id, {
|
||||
reason: '保存配置失败',
|
||||
failed,
|
||||
desired: patch.models ?? {},
|
||||
})
|
||||
await store.addEvent?.({
|
||||
kind: 'config-rollback-failed',
|
||||
projectId: project.id,
|
||||
summary: `保存配置失败;模型回滚失败:${failed.join('、')};desired=${JSON.stringify(patch.models ?? {})}`,
|
||||
}).catch?.(() => {})
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
recoveryRequired: failed.length > 0,
|
||||
text: `保存配置失败:${error?.message ?? error}。`
|
||||
+ (rollback.length > 0 ? `模型回滚失败:${rollback.join('、')},请检查实际模型配置。` : '已回滚运行时模型。'),
|
||||
+ (failed.length > 0
|
||||
? `模型回滚失败(${failed.join('、')}),${recoveryPersisted ? '已写入 config-recovery.jsonl' : '待恢复事件写入也失败'},请检查实际模型配置。`
|
||||
: '已回滚运行时模型。'),
|
||||
}
|
||||
}
|
||||
return { ok: true, text: `已更新项目「${project.name}」(${project.id}):${changed.join(',')}。只影响本项目,其他项目与正在运行的会话不受影响。` }
|
||||
return {
|
||||
ok: true,
|
||||
text: `已更新项目「${project.name}」(${project.id}):${changed.join(',')}。只影响本项目;模型变更会应用到该 Bot 的会话,正在生成的 turn 的实际影响取决于宿主契约,未在此断言不受影响。`,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 { /* 模型目录不可用时仍返回项目状态 */ }
|
||||
|
|
@ -127,7 +128,12 @@ export function installRoute({ ctx, store, dsbot }) {
|
|||
models,
|
||||
current: current.project ?? null,
|
||||
currentMatch: current.matchedBy,
|
||||
health: { status: health.status, error: health.error ?? null },
|
||||
health: {
|
||||
status: health.status,
|
||||
error: health.error ?? null,
|
||||
registryStatus: health.registryStatus ?? null,
|
||||
writable: health.writable !== false,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
send(res, 500, { error: `读取三省六部状态失败:${error?.message ?? error}` })
|
||||
|
|
@ -138,7 +144,7 @@ export function installRoute({ ctx, store, dsbot }) {
|
|||
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, {
|
||||
send(res, health.status === 'broken' || health.writable === false ? 503 : 200, {
|
||||
store: health,
|
||||
governance: (() => {
|
||||
try { return typeof ctx.get('sansheng-governance', false)?.checkDelivery === 'function' } catch { return false }
|
||||
|
|
@ -207,7 +213,12 @@ export function installRoute({ ctx, store, dsbot }) {
|
|||
exclude: body.exclude,
|
||||
},
|
||||
})
|
||||
send(res, result.ok ? 200 : 400, { ok: result.ok, text: result.text, error: result.ok ? undefined : result.text })
|
||||
send(res, result.ok ? 200 : 400, {
|
||||
ok: result.ok,
|
||||
text: result.text,
|
||||
error: result.ok ? undefined : result.text,
|
||||
...(result.recoveryRequired ? { recoveryRequired: true } : {}),
|
||||
})
|
||||
} catch (error) {
|
||||
send(res, error.statusCode ?? 500, { error: String(error?.message ?? error) })
|
||||
}
|
||||
|
|
@ -244,10 +255,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) })
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
||||
import { realpathSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { ROLE_IDS } from './roles.js'
|
||||
|
||||
|
|
@ -35,13 +36,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 : {},
|
||||
}
|
||||
|
|
@ -96,6 +151,28 @@ function registryOf(state) {
|
|||
return { version: 1, rooms, bots, updatedAt: Date.now() }
|
||||
}
|
||||
|
||||
/** R4-03:registry 是保护主状态的证据文件,合法性必须和主状态一样严格。 */
|
||||
function validateRegistry(raw) {
|
||||
if (!isObject(raw)) return { ok: false, error: 'registry 顶层不是对象' }
|
||||
if (raw.version !== 1) return { ok: false, error: `registry.version 必须是 1,实际是 ${String(raw.version)}` }
|
||||
if (!isObject(raw.rooms)) return { ok: false, error: 'registry.rooms 必须是对象' }
|
||||
if (!isObject(raw.bots)) return { ok: false, error: 'registry.bots 必须是对象' }
|
||||
if (typeof raw.updatedAt !== 'number' || !Number.isFinite(raw.updatedAt) || raw.updatedAt < 0) {
|
||||
return { ok: false, error: 'registry.updatedAt 必须是非负有限数字' }
|
||||
}
|
||||
for (const [field, map] of [['rooms', raw.rooms], ['bots', raw.bots]]) {
|
||||
for (const [key, value] of Object.entries(map)) {
|
||||
if (key === '' || typeof value !== 'string' || value === '') {
|
||||
return { ok: false, error: `registry.${field} 的键值必须是非空字符串` }
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
registry: { version: 1, rooms: { ...raw.rooms }, bots: { ...raw.bots }, updatedAt: raw.updatedAt },
|
||||
}
|
||||
}
|
||||
|
||||
function clone(value) {
|
||||
return structuredClone(value)
|
||||
}
|
||||
|
|
@ -116,6 +193,7 @@ export class SanshengStore {
|
|||
#ready
|
||||
#queue = Promise.resolve()
|
||||
#health
|
||||
#registryHealth
|
||||
|
||||
constructor(file) {
|
||||
this.#file = file
|
||||
|
|
@ -124,6 +202,7 @@ export class SanshengStore {
|
|||
this.#registry = { version: 1, rooms: {}, bots: {}, updatedAt: 0 }
|
||||
this.#ready = undefined
|
||||
this.#health = { status: 'missing', path: file, error: null }
|
||||
this.#registryHealth = { status: 'missing', error: null }
|
||||
}
|
||||
|
||||
get file() {
|
||||
|
|
@ -137,13 +216,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) {
|
||||
|
|
@ -153,26 +236,87 @@ export class SanshengStore {
|
|||
}
|
||||
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,
|
||||
if (raw === undefined) {
|
||||
this.#registryHealth = { status: 'missing', error: null }
|
||||
} else if (isObject(raw)) {
|
||||
const checkedRegistry = validateRegistry(raw)
|
||||
if (!checkedRegistry.ok) {
|
||||
this.#registry = { version: 1, rooms: {}, bots: {}, updatedAt: 0 }
|
||||
this.#registryHealth = { status: 'broken', error: checkedRegistry.error }
|
||||
if (this.#health.status === 'ok') {
|
||||
this.#health = {
|
||||
status: 'broken',
|
||||
path: this.#file,
|
||||
error: `registry schema 非法:${checkedRegistry.error}`,
|
||||
registryStatus: 'broken',
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.#registry = checkedRegistry.registry
|
||||
this.#registryHealth = { status: 'ok', error: null }
|
||||
}
|
||||
} else {
|
||||
this.#registryHealth = { status: 'broken', error: 'registry 顶层不是对象' }
|
||||
if (this.#health.status === 'ok') {
|
||||
this.#health = {
|
||||
status: 'broken',
|
||||
path: this.#file,
|
||||
error: 'registry schema 非法:registry 顶层不是对象',
|
||||
registryStatus: 'broken',
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// registry 只是提示文件;读不了时按无提示处理,不影响主状态。
|
||||
} catch (error) {
|
||||
// Q02:registry 本身损坏时不能当作“无提示”;双文件故障必须显式不可判定。
|
||||
this.#registryHealth = { status: 'broken', error: String(error?.message ?? error) }
|
||||
}
|
||||
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}`)
|
||||
}
|
||||
// 主状态缺失 + 仍有 registry 证明:这是“待恢复”而不是首次安装。
|
||||
// transact/启动对账/provision 必须拒绝,直到用户明确恢复主状态。
|
||||
if (this.#health.status === 'missing' && this.#hasRegistryEvidence()) {
|
||||
this.#health = {
|
||||
status: 'missing',
|
||||
path: this.#file,
|
||||
error: '主状态文件缺失,但 registry 仍记录受治理项目;写操作已停止,请先恢复主状态。',
|
||||
protected: true,
|
||||
}
|
||||
}
|
||||
if (this.#health.status === 'ok') await this.#writeRegistry(this.#state).catch(() => {})
|
||||
if (projectError) throw projectError
|
||||
return this.#state
|
||||
})()
|
||||
return this.#ready
|
||||
}
|
||||
|
||||
#hasRegistryEvidence() {
|
||||
return this.#registryHealth.status === 'broken'
|
||||
|| Object.keys(this.#registry.rooms ?? {}).length > 0
|
||||
|| Object.keys(this.#registry.bots ?? {}).length > 0
|
||||
}
|
||||
|
||||
#canWrite() {
|
||||
if (this.#health.status === 'ok') return true
|
||||
// 首次安装:主状态和 registry 都不存在,允许创建第一个项目。
|
||||
if (this.#health.status === 'missing' && !this.#hasRegistryEvidence()) return true
|
||||
return false
|
||||
}
|
||||
|
||||
health() {
|
||||
return { ...this.#health, registry: this.#registryFile }
|
||||
return {
|
||||
...this.#health,
|
||||
registry: this.#registryFile,
|
||||
registryStatus: this.#registryHealth.status,
|
||||
registryError: this.#registryHealth.error,
|
||||
registryEntries: Object.keys(this.#registry.rooms ?? {}).length + Object.keys(this.#registry.bots ?? {}).length,
|
||||
writable: this.#canWrite(),
|
||||
}
|
||||
}
|
||||
|
||||
/** 同步快照;guard 只能同步读取。 */
|
||||
|
|
@ -184,44 +328,48 @@ 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
|
||||
this.#registryHealth = { status: 'ok', error: null }
|
||||
}
|
||||
|
||||
async transact(mutate) {
|
||||
const run = this.#queue.then(async () => {
|
||||
await this.load()
|
||||
const before = clone(this.#state)
|
||||
// Q01/Q02:主状态缺失或损坏且仍有治理证据时,任何事务(包括启动对账)
|
||||
// 都不能把它“修复”成空状态并覆盖 registry。
|
||||
if (!this.#canWrite()) {
|
||||
throw new SanshengStoreError(
|
||||
'state-protected',
|
||||
this.#health.error ?? '治理状态不可写:主状态缺失/损坏但 registry 仍记录受治理项目;请先恢复主状态。',
|
||||
)
|
||||
}
|
||||
// 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 +417,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 +425,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 +441,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 +463,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 +597,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 +690,50 @@ 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 ''
|
||||
// Q08:junction/符号链接别名必须落到同一个物理根;不存在时退回字面 resolve。
|
||||
let physical = text
|
||||
try { physical = realpathSync(text).replace(/\\/g, '/').replace(/\/+$/, '') } catch { /* 目录还不存在时用字面路径 */ }
|
||||
return `root:${physical}`.toLowerCase()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { randomUUID } from 'node:crypto'
|
||||
import { resolve } from 'node:path'
|
||||
import { captureArtifactSnapshot, summarizeSnapshot } from './artifact.js'
|
||||
import { artifactDigestOf, reviewSubjectDigest, sha256 } from './digest.js'
|
||||
import { budgetOf } from './gate.js'
|
||||
|
|
@ -163,6 +164,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 +224,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
|
||||
|
|
@ -271,34 +278,44 @@ async function submit({ store, dsbot, args, exec }) {
|
|||
return '只有工部或尚书的项目 Bot 能提交成果;丞相只做验收。'
|
||||
}
|
||||
const holder = actor.botId ?? 'user'
|
||||
const lease = await store.acquireLease(project.id, { holder, taskId: args.task ?? null })
|
||||
const root = project.workDir ? resolve(project.workDir) : null
|
||||
// Q08:提交快照和真实写工具使用同一个工作根租约,避免采集时并发修改。
|
||||
const lease = root
|
||||
? await store.acquireRootLease(root, { holder, taskId: args.task ?? null })
|
||||
: 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 {
|
||||
// 写租约只覆盖这次实际提交;成功/失败都释放,不能被一次提交永久占住。
|
||||
if (root) await store.releaseRootLease(root, holder).catch(() => {})
|
||||
else 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 +324,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 +397,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 +462,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)
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ function domStub() {
|
|||
createElement() {
|
||||
const node = { attrs: {}, textContent: '' }
|
||||
node.setAttribute = (key, value) => { node.attrs[key] = value }
|
||||
node.remove = () => { for (const [key, value] of styles) if (value === node) styles.delete(key) }
|
||||
return node
|
||||
},
|
||||
head: {
|
||||
|
|
@ -47,18 +48,16 @@ function domStub() {
|
|||
return { document, styles }
|
||||
}
|
||||
|
||||
async function loadClient({ fetch: customFetch } = {}) {
|
||||
async function loadClient({ fetch: customFetch, react: customReact } = {}) {
|
||||
const source = await readFile(new URL('../client.js', import.meta.url), 'utf8')
|
||||
const { document, styles } = domStub()
|
||||
let captured
|
||||
const reactImpl = customReact ?? reactStub()
|
||||
const window = {
|
||||
__ModuleLoader__: {
|
||||
load(options) {
|
||||
captured = options
|
||||
return options.factory((name) => {
|
||||
if (name === 'react') return reactStub()
|
||||
throw new Error(`未知模块 ${name}`)
|
||||
})
|
||||
return { exports: {} }
|
||||
},
|
||||
},
|
||||
localStorage: {
|
||||
|
|
@ -66,13 +65,28 @@ async function loadClient({ fetch: customFetch } = {}) {
|
|||
getItem(key) { return this.store.has(key) ? this.store.get(key) : null },
|
||||
setItem(key, value) { this.store.set(key, String(value)) },
|
||||
},
|
||||
events: [],
|
||||
listeners: new Map(),
|
||||
addEventListener(name, fn) {
|
||||
if (!this.listeners.has(name)) this.listeners.set(name, [])
|
||||
this.listeners.get(name).push(fn)
|
||||
},
|
||||
removeEventListener(name, fn) {
|
||||
const list = this.listeners.get(name) ?? []
|
||||
this.listeners.set(name, list.filter(item => item !== fn))
|
||||
},
|
||||
dispatchEvent(event) {
|
||||
this.events.push(event.type)
|
||||
for (const fn of this.listeners.get(event.type) ?? []) fn(event)
|
||||
return true
|
||||
},
|
||||
}
|
||||
const fetchImpl = typeof customFetch === 'function'
|
||||
? customFetch
|
||||
: () => Promise.reject(new Error('测试里不联网'))
|
||||
const run = new Function('window', 'document', 'fetch', 'nextTick', source)
|
||||
run(window, document, fetchImpl, () => {})
|
||||
return { module: captured.factory((name) => (name === 'react' ? reactStub() : (() => { throw new Error(name) })())), captured, document, styles, window }
|
||||
return { module: captured.factory((name) => (name === 'react' ? reactImpl : (() => { throw new Error(name) })())), captured, document, styles, window }
|
||||
}
|
||||
|
||||
function fakeCtx(options = {}) {
|
||||
|
|
@ -81,6 +95,7 @@ function fakeCtx(options = {}) {
|
|||
const slots = []
|
||||
const menuRegistrations = []
|
||||
const toasts = []
|
||||
const effectCleanups = []
|
||||
const services = {
|
||||
sidebarRightTabs: { register(registration) { tabs.push(registration); return () => {} } },
|
||||
sidebarRight: { openTabIn(sessionId, kind) { services.sidebarRight.opened = [sessionId, kind] } },
|
||||
|
|
@ -95,7 +110,11 @@ function fakeCtx(options = {}) {
|
|||
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() },
|
||||
effect(fn) {
|
||||
const cleanup = fn()
|
||||
if (typeof cleanup === 'function') effectCleanups.push(cleanup)
|
||||
return cleanup
|
||||
},
|
||||
sidebarRightTabs: services.sidebarRightTabs,
|
||||
get(name, fallback) { return services[name] ?? fallback },
|
||||
slots: {
|
||||
|
|
@ -109,6 +128,7 @@ function fakeCtx(options = {}) {
|
|||
},
|
||||
},
|
||||
tabs,
|
||||
effectCleanups,
|
||||
slotsList: slots,
|
||||
services,
|
||||
menuRegistrations,
|
||||
|
|
@ -221,8 +241,8 @@ test('右栏列在没有项目时渲染引导文案', async () => {
|
|||
const element = wrap({ sessionId: 'sess-1' })
|
||||
const tree = element.type(element.props)
|
||||
const text = textOf(tree)
|
||||
assert.match(text, /还没有三省六部项目/)
|
||||
assert.match(text, /sansheng_provision/)
|
||||
assert.match(text, /正在载入当前项目状态|还没有三省六部项目/)
|
||||
assert.match(text, /载入|sansheng_provision/)
|
||||
})
|
||||
|
||||
test('页签标题渲染三省与角色字样', async () => {
|
||||
|
|
@ -612,3 +632,189 @@ test('切到 B 后请求失败,不把 A 的缓存配上 B 的上下文', async
|
|||
assert.match(last.error, /网络断了/)
|
||||
poller.stop()
|
||||
})
|
||||
|
||||
test('Q12:Hook 状态合并保留 loading,切换项目唤醒不受节流丢弃', async () => {
|
||||
const { module } = await loadClient()
|
||||
const merged = module.__test.mergePollState(
|
||||
{ loading: false, error: null, data: { old: true }, updatedAt: 1, context: { workspaceId: 'a' } },
|
||||
{ loading: true, error: null, data: null, updatedAt: 0, context: { workspaceId: 'b' } },
|
||||
)
|
||||
assert.equal(merged.loading, true)
|
||||
assert.equal(merged.data, null)
|
||||
assert.equal(merged.context.workspaceId, 'b')
|
||||
|
||||
let signature = 'a'
|
||||
let refreshes = 0
|
||||
const gate = module.__test.createWakeGate({
|
||||
refresh: () => { refreshes += 1 },
|
||||
signatureOf: () => signature,
|
||||
throttleMs: 20,
|
||||
})
|
||||
gate.wake()
|
||||
assert.equal(refreshes, 1)
|
||||
gate.wake()
|
||||
gate.wake()
|
||||
assert.equal(refreshes, 1, '节流窗口内不立即重复刷新')
|
||||
await new Promise(resolve => setTimeout(resolve, 30))
|
||||
assert.equal(refreshes, 2, '节流窗口结束补一次 trailing 刷新')
|
||||
signature = 'b'
|
||||
gate.wake()
|
||||
assert.equal(refreshes, 3, '项目身份变化立即刷新')
|
||||
gate.dispose()
|
||||
})
|
||||
|
||||
test('Q12b:悬挂请求超时后进入错误状态,不永久卡住轮询', async () => {
|
||||
const { module } = await loadClient()
|
||||
const states = []
|
||||
let calls = 0
|
||||
const fetch = (url, options) => new Promise((resolve, reject) => {
|
||||
calls += 1
|
||||
const signal = options?.signal
|
||||
if (signal) signal.addEventListener('abort', () => reject(new Error('请求超时')))
|
||||
})
|
||||
const ctx = fakeCtx({ workspaces: { items: [{ workspaceId: 'ws-timeout', sessionIds: [] }] } })
|
||||
const poller = module.__test.createStatePoller({
|
||||
ctx,
|
||||
fetchImpl: fetch,
|
||||
onChange: state => states.push(state),
|
||||
intervalMs: 60000,
|
||||
requestTimeoutMs: 20,
|
||||
})
|
||||
poller.start()
|
||||
await new Promise(resolve => setTimeout(resolve, 60))
|
||||
assert.equal(calls >= 1, true)
|
||||
assert.match(states.at(-1).error, /超时/)
|
||||
poller.stop()
|
||||
})
|
||||
|
||||
function hookReact() {
|
||||
let cells = []
|
||||
let cursor = 0
|
||||
let pending = []
|
||||
let scheduled = null
|
||||
let hookFn
|
||||
let current
|
||||
let setCalls = 0
|
||||
let effectCalls = 0
|
||||
const depsChanged = (a, b) => !a || !b || a.length !== b.length || a.some((value, index) => value !== b[index])
|
||||
const render = () => {
|
||||
cursor = 0
|
||||
pending = []
|
||||
current = hookFn()
|
||||
for (const run of pending) run()
|
||||
return current
|
||||
}
|
||||
const schedule = () => {
|
||||
if (scheduled) return
|
||||
scheduled = setTimeout(() => { scheduled = null; render() }, 0)
|
||||
}
|
||||
const React = {
|
||||
__id: 'custom-hook-react',
|
||||
createElement: () => null,
|
||||
Fragment: 'Fragment',
|
||||
useMemo: fn => fn(),
|
||||
useCallback: fn => fn(),
|
||||
useRef: value => ({ current: value }),
|
||||
useState(initial) {
|
||||
const index = cursor++
|
||||
if (!(index in cells)) cells[index] = typeof initial === 'function' ? initial() : initial
|
||||
return [cells[index], value => {
|
||||
setCalls += 1
|
||||
cells[index] = typeof value === 'function' ? value(cells[index]) : value
|
||||
schedule()
|
||||
}]
|
||||
},
|
||||
useEffect(fn, deps) {
|
||||
effectCalls += 1
|
||||
const index = cursor++
|
||||
const previous = cells[index]
|
||||
if (!previous || depsChanged(previous.deps, deps)) {
|
||||
cells[index] = { deps, cleanup: undefined }
|
||||
pending.push(() => { cells[index].cleanup = fn() })
|
||||
}
|
||||
},
|
||||
useLayoutEffect: () => {},
|
||||
}
|
||||
return {
|
||||
React,
|
||||
mount(fn) { hookFn = fn; return render() },
|
||||
get state() { return current },
|
||||
get setCalls() { return setCalls },
|
||||
get effectCalls() { return effectCalls },
|
||||
stop() {
|
||||
if (scheduled) clearTimeout(scheduled)
|
||||
scheduled = null
|
||||
for (const cell of cells) {
|
||||
if (cell && typeof cell.cleanup === 'function') {
|
||||
try { cell.cleanup() } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
test('Q12c:真实 useSanshengState Hook 切换项目保留 loading 并清空旧数据', async () => {
|
||||
let selection = { sessionId: 'sess-a' }
|
||||
const workspaceItems = [
|
||||
{ workspaceId: 'wa', sessionIds: ['sess-a'] },
|
||||
{ workspaceId: 'wb', sessionIds: ['sess-b'] },
|
||||
]
|
||||
const sessionRows = {
|
||||
byId: {
|
||||
'sess-a': { id: 'sess-a', retainedBy: { mainView: 1 } },
|
||||
'sess-b': { id: 'sess-b', retainedBy: { mainView: 0 } },
|
||||
},
|
||||
}
|
||||
const workspaceListeners = []
|
||||
const workspaces = { list: { getSnapshot: () => ({ items: workspaceItems }), subscribe: fn => { workspaceListeners.push(fn); return () => {} } } }
|
||||
const sessions = { list: { getSnapshot: () => sessionRows, subscribe: fn => { return () => {} } } }
|
||||
let fetchCalls = 0
|
||||
const fetch = async url => {
|
||||
fetchCalls += 1
|
||||
if (url.includes('workspaceId=wa')) {
|
||||
return { ok: true, status: 200, json: async () => ({ current: { id: 'A', name: 'A' }, projects: [] }) }
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
throw new Error('B 网络断了')
|
||||
}
|
||||
const ctx = fakeCtx({
|
||||
uiWorkspace: { selection: { getSnapshot: () => selection } },
|
||||
workspaces,
|
||||
sessions,
|
||||
})
|
||||
const hook = hookReact()
|
||||
const { module } = await loadClient({ fetch, react: hook.React })
|
||||
hook.mount(() => module.__test.useSanshengState(ctx, ''))
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
assert.ok(hook.effectCalls >= 1, 'effect calls=' + hook.effectCalls + ' fetch=' + fetchCalls)
|
||||
assert.equal(hook.state.data && hook.state.data.current && hook.state.data.current.id, 'A', JSON.stringify(hook.state))
|
||||
|
||||
selection = { sessionId: 'sess-b' }
|
||||
sessionRows.byId['sess-a'].retainedBy.mainView = 0
|
||||
sessionRows.byId['sess-b'].retainedBy.mainView = 1
|
||||
assert.equal(module.__test.workspaceContextOf(ctx).workspaceId, 'wb')
|
||||
for (const listener of workspaceListeners) listener()
|
||||
await new Promise(resolve => setTimeout(resolve, 15))
|
||||
assert.equal(hook.state.context.workspaceId, 'wb')
|
||||
assert.equal(hook.state.loading, true, '切换后先进入 loading')
|
||||
assert.equal(hook.state.data, null, '旧项目数据立即清空')
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 60))
|
||||
assert.equal(hook.state.context.workspaceId, 'wb')
|
||||
assert.match(hook.state.error, /B 网络断了/)
|
||||
assert.equal(hook.state.data, null)
|
||||
hook.stop()
|
||||
})
|
||||
|
||||
test('R4-06:三省卸载时撤销共存标记、发 workbench-gone 并清理样式', async () => {
|
||||
const ctx = fakeCtx()
|
||||
const { module, styles, window } = await loadClient()
|
||||
module.apply(ctx)
|
||||
assert.equal(globalThis.__SANSENG_WORKBENCH__, true)
|
||||
assert.equal(styles.size, 1, '应注入样式')
|
||||
assert.deepEqual(window.events, ['sansheng:workbench-ready'])
|
||||
for (const cleanup of [...ctx.effectCleanups].reverse()) cleanup()
|
||||
assert.equal(globalThis.__SANSENG_WORKBENCH__, false)
|
||||
assert.equal(styles.size, 0, '卸载后样式应清理')
|
||||
assert.deepEqual(window.events, ['sansheng:workbench-ready', 'sansheng:workbench-gone'])
|
||||
})
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ function goalAt({ revision = 4, reworks = 0 } = {}) {
|
|||
}
|
||||
}
|
||||
|
||||
function fakeEnv({ goal = goalAt(), deliver } = {}) {
|
||||
function fakeEnv({ goal = goalAt(), deliver, jobs } = {}) {
|
||||
const room = {
|
||||
id: 'room-1', name: '派发项目 · 三省六部', admin: 'b-shang',
|
||||
members: ['b-lead', 'b-shang', 'b-gong'],
|
||||
|
|
@ -66,7 +66,11 @@ function fakeEnv({ goal = goalAt(), deliver } = {}) {
|
|||
if (deliver) await deliver(payload)
|
||||
},
|
||||
}
|
||||
const ctx = { handlers: {}, on(event, handler) { this.handlers[event] = handler }, get() { return rt } }
|
||||
const ctx = {
|
||||
handlers: {},
|
||||
on(event, handler) { this.handlers[event] = handler },
|
||||
get(name) { return name === 'jobs' ? jobs : rt },
|
||||
}
|
||||
return { room, dsbot, ctx, calls }
|
||||
}
|
||||
|
||||
|
|
@ -170,3 +174,210 @@ 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()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q08e:后台 job 用非消费式 events 观察终态,不调用 wait、不抑制通知', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject({ ...PROJECT, workDir: 'C:/work/background-root' })
|
||||
let notify
|
||||
const subscriptions = []
|
||||
const waitCalls = []
|
||||
const jobs = {
|
||||
wait(...args) { waitCalls.push(args); return Promise.resolve({ status: 'completed' }) },
|
||||
get: () => ({ id: 'pwsh-0123456789abcdef', status: 'running' }),
|
||||
events: {
|
||||
subscribe(filter, callback) {
|
||||
subscriptions.push({ filter, callback })
|
||||
notify = callback
|
||||
return () => { notify = undefined }
|
||||
},
|
||||
},
|
||||
}
|
||||
const { dsbot, ctx } = fakeEnv({ goal: goalAt(), jobs })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
const result = await ctx.handlers['tools/execute'](
|
||||
{ name: 'pwsh', id: 'call-bg', arguments: { command: 'long' }, agent: { id: 'sess-shang' } },
|
||||
async () => ({ content: [{ type: 'text', text: 'started background job pwsh-0123456789abcdef' }] }),
|
||||
)
|
||||
assert.match(result.content[0].text, /background job/)
|
||||
assert.equal(waitCalls.length, 0, '不能用 wait 消费原生完成通知')
|
||||
assert.deepEqual(subscriptions[0].filter, { owner: 'sess-shang' })
|
||||
assert.match(store.rootLeaseOf('C:/work/background-root')?.holder ?? '', /^b-shang:call-bg:/, 'job 没结束前租约必须保留')
|
||||
|
||||
notify({ type: 'settled', job: { id: 'pwsh-0123456789abcdef', status: 'completed' }, awaited: false })
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
assert.equal(store.rootLeaseOf('C:/work/background-root'), undefined, '终态事件后释放租约')
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q08f:订阅前 job 已终态也能立即释放租约', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject({ ...PROJECT, workDir: 'C:/work/background-race' })
|
||||
const jobs = {
|
||||
get: () => ({ id: 'pwsh-0123456789abcdef', status: 'completed' }),
|
||||
events: { subscribe: () => () => {} },
|
||||
}
|
||||
const { dsbot, ctx } = fakeEnv({ goal: goalAt(), jobs })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
await ctx.handlers['tools/execute'](
|
||||
{ name: 'pwsh', id: 'call-race', arguments: { command: 'fast' }, agent: { id: 'sess-shang' } },
|
||||
async () => ({ content: [{ type: 'text', text: 'started background job pwsh-0123456789abcdef' }] }),
|
||||
)
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
assert.equal(store.rootLeaseOf('C:/work/background-race'), undefined)
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
test('Q08g:父子嵌套根写同一文件时按实际目标路径互斥', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject({ ...PROJECT, id: 'prj-a', roomId: 'room-a', workDir: 'C:/work', bots: { lead: 'b-a', shangshu: 'b-a-shang', gongbu: 'b-a-gong' } })
|
||||
await store.saveProject({ ...PROJECT, id: 'prj-b', roomId: 'room-b', workDir: 'C:/work/sub', bots: { lead: 'b-b', shangshu: 'b-b-shang', gongbu: 'b-b-gong' } })
|
||||
const rooms = {
|
||||
'room-a': { id: 'room-a', name: 'A', members: ['b-a'], admin: 'b-a', sessions: {} },
|
||||
'room-b': { id: 'room-b', name: 'B', members: ['b-b'], admin: 'b-b', sessions: {} },
|
||||
}
|
||||
const bots = { 'b-a': { id: 'b-a', name: 'A' }, 'b-b': { id: 'b-b', name: 'B' } }
|
||||
const dsbot = {
|
||||
selfOf: id => (id === 'sess-a' ? 'b-a' : id === 'sess-b' ? 'b-b' : undefined),
|
||||
roomOfSession: id => (id === 'sess-a' ? 'room-a' : id === 'sess-b' ? 'room-b' : undefined),
|
||||
roomOf: id => rooms[id],
|
||||
botOf: id => bots[id],
|
||||
isMain: () => false,
|
||||
pickRoom: () => ({ error: 'no' }),
|
||||
}
|
||||
const ctx = { handlers: {}, on(event, handler) { this.handlers[event] = handler }, get() { return undefined } }
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
let release
|
||||
const gate = new Promise(resolve => { release = resolve })
|
||||
const first = ctx.handlers['tools/execute'](
|
||||
{ name: 'write', id: 'nested-1', arguments: { path: 'C:/work/sub/shared.txt' }, agent: { id: 'sess-a' } },
|
||||
async () => { await gate; return 'written' },
|
||||
)
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
const second = await ctx.handlers['tools/execute'](
|
||||
{ name: 'write', id: 'nested-2', arguments: { path: 'C:/work/sub/shared.txt' }, agent: { id: 'sess-b' } },
|
||||
async () => 'written',
|
||||
)
|
||||
assert.match(String(second), /同一实际路径不能并发写/)
|
||||
release()
|
||||
await first
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q08h:文件工具目标越出项目工作根时明确拒绝', async () => {
|
||||
const { store, cleanup } = await tempStore()
|
||||
try {
|
||||
await store.saveProject({ ...PROJECT, workDir: 'C:/work/inside' })
|
||||
const { dsbot, ctx } = fakeEnv({ goal: goalAt() })
|
||||
installObserver({ ctx, store, dsbot, bootId: newBootId() })
|
||||
let called = false
|
||||
const result = await ctx.handlers['tools/execute'](
|
||||
{ name: 'write', id: 'outside', arguments: { path: 'C:/elsewhere/secret.txt' }, agent: { id: 'sess-shang' } },
|
||||
async () => { called = true; return 'written' },
|
||||
)
|
||||
assert.equal(called, false)
|
||||
assert.match(String(result), /超出项目工作根/)
|
||||
assert.equal(store.rootLeaseOf('C:/work/inside'), undefined)
|
||||
} finally {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -116,3 +116,21 @@ test('跨项目:A 的 Bot 在 B 的群里操作被拒绝', () => {
|
|||
assert.equal(typeof reason, 'string')
|
||||
assert.match(reason, /不能修改项目「B」的目标/)
|
||||
})
|
||||
|
||||
test('Q02b:主状态与 registry 双故障时门禁拒绝,不按 unbound 放行', () => {
|
||||
const ctx = makeCtx()
|
||||
const store = makeStore({
|
||||
health: () => ({ status: 'broken', registryStatus: '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, /主状态与治理 registry/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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 = []
|
||||
|
|
@ -333,11 +334,248 @@ test('Q11b:中途 updateBot 失败时回滚已经修改的模型', async () =>
|
|||
models: { lead: 'provider/m1', shangshu: 'provider/m2' },
|
||||
}, userExec)
|
||||
assert.match(result, /已回滚/)
|
||||
const updates = env.calls.updated.slice(-2)
|
||||
const updates = env.calls.updated.slice(-3)
|
||||
assert.equal(updates[0].id, project.bots.lead)
|
||||
assert.equal(updates[0].patch.model, 'provider/m1')
|
||||
assert.equal(updates[1].id, project.bots.lead)
|
||||
assert.equal(updates[1].patch.model, null, '回滚到原值')
|
||||
assert.equal(updates[1].id, project.bots.shangshu, '当前失败角色也要进入补偿')
|
||||
assert.equal(updates[1].patch.model, undefined)
|
||||
assert.equal(updates[2].id, project.bots.lead)
|
||||
assert.equal(updates[2].patch.model, undefined, '回滚到原值')
|
||||
} finally {
|
||||
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, '提交完成后必须释放项目租约')
|
||||
assert.equal(env.store.rootLeaseOf('C:/work/a'), 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()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q02b:主状态与 registry 双故障时治理/门禁不可判定为 unbound', async () => {
|
||||
const { 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()
|
||||
await writeFile(env.statePath, '{broken', 'utf8')
|
||||
await writeFile(env.statePath.replace(/state\.json$/, 'registry.json'), '{broken', 'utf8')
|
||||
const broken = new SanshengStore(env.statePath)
|
||||
await assert.rejects(() => broken.load())
|
||||
assert.equal(broken.health().registryStatus, 'broken')
|
||||
const governance = installGovernance({ ctx: fakeCtx(), store: broken })
|
||||
// 连从未见过的 Bot 也不能被静默当作 unbound。
|
||||
assert.equal(governance.checkDelivery({ fromId: 'unknown-a', toId: 'unknown-b' }).allow, false)
|
||||
assert.equal(governance.checkMemoryScope({ botId: 'unknown-a', scope: 'team' }).allow, false)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q13:服务端配置拒绝 needsKey/不可用模型,即使前端绕过下拉', 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]
|
||||
env.rt.availabilityOf = async ref => (ref === 'provider/keyless'
|
||||
? { available: false, needsKey: true, reason: '提供方尚未配置凭据' }
|
||||
: { available: true })
|
||||
const before = env.calls.updated.length
|
||||
const result = await env.tool('sansheng_config').execute({ project: project.id, models: { lead: 'provider/keyless' } }, userExec)
|
||||
assert.match(result, /不可用|凭据/)
|
||||
assert.equal(env.calls.updated.length, before)
|
||||
assert.equal(env.store.projectById(project.id).models.lead, undefined)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q11c:同一项目的并发配置串行,不互相覆盖', 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 original = env.rt.updateBot
|
||||
env.rt.updateBot = async (...args) => {
|
||||
await new Promise(resolve => setTimeout(resolve, 15))
|
||||
return original.apply(env.rt, args)
|
||||
}
|
||||
const [one, two] = await Promise.all([
|
||||
env.tool('sansheng_config').execute({ project: project.id, models: { lead: 'provider/m1' } }, userExec),
|
||||
env.tool('sansheng_config').execute({ project: project.id, models: { shangshu: 'provider/m2' } }, userExec),
|
||||
])
|
||||
assert.match(one, /已更新/)
|
||||
assert.match(two, /已更新/)
|
||||
const fresh = await env.reload()
|
||||
const saved = fresh.projectById(project.id)
|
||||
assert.equal(saved.models.lead, 'provider/m1')
|
||||
assert.equal(saved.models.shangshu, 'provider/m2')
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q01c:真实 apply 启动链在主状态缺失时不覆盖 registry,provision 拒绝', async () => {
|
||||
const { readFile, unlink } = 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 registryBefore = await readFile(env.statePath.replace(/state\.json$/, 'registry.json'), 'utf8')
|
||||
await unlink(env.statePath)
|
||||
const ctx2 = fakeCtx({ 'dsbot-runtime': env.rt })
|
||||
await apply(ctx2, { statePath: env.statePath, dsbotStatePath: env.dsbotStatePath })
|
||||
const provision = ctx2.toolsList.find(def => def.name === 'sansheng_provision')
|
||||
const result = await provision.execute({ project: '项目B', workDir: 'C:/work/b' }, userExec)
|
||||
assert.match(String(result), /恢复|state-protected|缺失/)
|
||||
const registryAfter = await readFile(env.statePath.replace(/state\.json$/, 'registry.json'), 'utf8')
|
||||
assert.equal(registryAfter, registryBefore)
|
||||
const missing = new SanshengStore(env.statePath)
|
||||
await missing.load()
|
||||
assert.equal(missing.health().status, 'missing')
|
||||
assert.equal(missing.health().writable, false)
|
||||
assert.equal(missing.registryProjectForBot(project.bots.lead), project.id)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('Q11d:补偿失败写 config-recovery.jsonl,不再只返回一次文本', async () => {
|
||||
const { readFile } = 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]
|
||||
env.rt.updateBot = async (id, patch) => {
|
||||
if (id === project.bots.shangshu) throw new Error('尚书模型写入永久失败')
|
||||
return { id, ...patch }
|
||||
}
|
||||
const result = await env.tool('sansheng_config').execute({ project: project.id, models: { lead: 'provider/m1', shangshu: 'provider/m2' } }, userExec)
|
||||
assert.match(result, /回滚失败|config-recovery/)
|
||||
const sidecar = await readFile(join(env.dir, 'config-recovery.jsonl'), 'utf8')
|
||||
assert.match(sidecar, /config-recovery|项目|shangshu|provider\/m2/)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
test('R4-05:补偿不覆盖用户/原生设置在窗口里改成的新模型', async () => {
|
||||
const { readFile } = 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 original = env.rt.updateBot
|
||||
env.rt.updateBot = async (id, patch) => {
|
||||
if (id === project.bots.shangshu) {
|
||||
const lead = env.rt.botOf(project.bots.lead)
|
||||
lead.model = 'user/choice'
|
||||
throw new Error('第二模型失败')
|
||||
}
|
||||
return original.call(env.rt, id, patch)
|
||||
}
|
||||
const result = await env.tool('sansheng_config').execute({
|
||||
project: project.id,
|
||||
models: { lead: 'provider/m1', shangshu: 'provider/m2' },
|
||||
}, userExec)
|
||||
assert.match(result, /回滚失败|config-recovery/)
|
||||
assert.equal(env.rt.botOf(project.bots.lead).model, 'user/choice', '不得覆盖用户新选择')
|
||||
assert.equal(env.store.projectById(project.id).models.lead, undefined)
|
||||
assert.match(await readFile(join(env.dir, 'config-recovery.jsonl'), 'utf8'), /user\/choice|补偿未覆盖|runtime/)
|
||||
} finally {
|
||||
await env.cleanup()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,71 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { register } from 'node:module'
|
||||
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
|
||||
// Q04 真实 memory.js 集成:注册 peer stub loader 后加载 ds-bot 的 install。
|
||||
register(new URL('./stubs/peer-loader.mjs', import.meta.url).href)
|
||||
const { install } = await import('../../ds-bot/src/host/memory.js')
|
||||
|
||||
function makeRuntime({ home, allowGroup }) {
|
||||
const handlers = {}
|
||||
const ctx = {
|
||||
get(name, fallback) {
|
||||
if (name === 'sansheng-governance') {
|
||||
return {
|
||||
checkMemoryScope({ scope, roomId, targetBotId }) {
|
||||
if (scope === 'group' && roomId === 'rb') return allowGroup() ? { allow: true } : { allow: false, reason: 'blocked-group' }
|
||||
if (scope === 'bot' && targetBotId === 'b') return { allow: false, reason: 'blocked-target' }
|
||||
return { allow: true }
|
||||
},
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
},
|
||||
on(name, fn) { handlers[name] = fn; return () => {} },
|
||||
effect(fn) { try { return fn() } catch { return () => {} } },
|
||||
systemPrompt: { section: () => () => {} },
|
||||
llm: { resolveModelInfo: async () => undefined },
|
||||
}
|
||||
const bots = { a: { id: 'a', name: 'A', model: 'p/m' }, b: { id: 'b', name: 'B', model: 'p/m' } }
|
||||
const rooms = { rb: { id: 'rb', name: 'B group', members: ['a', 'b'], admin: 'b', sessions: {} } }
|
||||
const rt = {
|
||||
ctx, config: { memoryReview: false }, home,
|
||||
state: { prefs: {}, bots: {}, rooms: {}, privateArchives: [] },
|
||||
teamTools: [], groupOwners: new Map([['sess-a', { roomId: 'rb' }]]), pastOwners: new Map(),
|
||||
botOf: id => bots[id], roomOf: id => rooms[id],
|
||||
selfOf: id => (id === 'sess-a' ? 'a' : undefined),
|
||||
isMain: () => false, isPrivate: () => false, readOnly: () => undefined,
|
||||
warn: () => {}, redactSecrets: text => text, load: async () => {},
|
||||
}
|
||||
install(rt)
|
||||
return { rt, handlers, recall: rt.teamTools.find(tool => tool.name === 'recall') }
|
||||
}
|
||||
|
||||
test('Q04:真实 memory install 不注入被拒群记忆,允许时才读取', async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), 'sansheng-q04-'))
|
||||
try {
|
||||
await mkdir(join(home, 'memory', 'groups', 'rb'), { recursive: true })
|
||||
await writeFile(join(home, 'memory', 'groups', 'rb', 'MEMORY.md'), '- B_SECRET_PROJECT_B [added: 2026-01-01]\n', 'utf8')
|
||||
let allowGroup = false
|
||||
const { handlers, recall } = makeRuntime({ home, allowGroup: () => allowGroup })
|
||||
const hook = handlers['agent/pre-step']
|
||||
const agent = { id: 'sess-a', session: { deriveMessages: () => [] } }
|
||||
const next = async () => ({ kind: 'continue', messages: [{ role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'hello' }] }] })
|
||||
|
||||
const denied = await hook({ agent }, next)
|
||||
const deniedText = denied.messages.map(message => (message.content ?? []).map(part => part.text).join('')).join('\n')
|
||||
assert.doesNotMatch(deniedText, /B_SECRET_PROJECT_B/)
|
||||
assert.equal((await recall.execute({ scope: 'group', query: 'B_SECRET' }, { agent: { id: 'sess-a' } })), 'blocked-group')
|
||||
|
||||
allowGroup = true
|
||||
const allowed = await hook({ agent }, next)
|
||||
const allowedText = allowed.messages.map(message => (message.content ?? []).map(part => part.text).join('')).join('\n')
|
||||
assert.match(allowedText, /B_SECRET_PROJECT_B/)
|
||||
assert.match(await recall.execute({ scope: 'group', query: 'B_SECRET' }, { agent: { id: 'sess-a' } }), /B_SECRET_PROJECT_B/)
|
||||
} finally {
|
||||
await rm(home, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { install } from '../../ds-bot/src/host/models.js'
|
||||
|
||||
function harness() {
|
||||
const calls = []
|
||||
const saved = []
|
||||
let current = { provider: 'old', model: 'oldm' }
|
||||
const ctx = {
|
||||
on() {},
|
||||
get(name) {
|
||||
if (name !== 'agentDefaultModel') return undefined
|
||||
return {
|
||||
currentSelection: () => current,
|
||||
saveSelection: async value => { saved.push(value); current = value },
|
||||
}
|
||||
},
|
||||
sessionController: {
|
||||
async selectModel({ sessionId, provider, model }) {
|
||||
calls.push('start:' + sessionId + ':' + model)
|
||||
await new Promise(resolve => setTimeout(resolve, 15))
|
||||
if (model === 'bad') throw new Error('busy session')
|
||||
calls.push('end:' + sessionId + ':' + model)
|
||||
current = { provider, model }
|
||||
return { selected: { provider, model } }
|
||||
},
|
||||
},
|
||||
}
|
||||
const rt = { ctx, state: {}, warn: () => {} }
|
||||
install(rt)
|
||||
return { rt, calls, saved }
|
||||
}
|
||||
|
||||
test('Q11e:真实 selectSessionModel 串行执行,一次失败不阻塞下一次', async () => {
|
||||
const { rt, calls, saved } = harness()
|
||||
await Promise.all([
|
||||
rt.selectSessionModel('s1', { provider: 'p', model: 'm1' }),
|
||||
rt.selectSessionModel('s2', { provider: 'p', model: 'm2' }),
|
||||
])
|
||||
assert.deepEqual(calls, ['start:s1:m1', 'end:s1:m1', 'start:s2:m2', 'end:s2:m2'])
|
||||
assert.deepEqual(saved, [{ provider: 'old', model: 'oldm' }, { provider: 'old', model: 'oldm' }])
|
||||
|
||||
await assert.rejects(rt.selectSessionModel('s3', { provider: 'p', model: 'bad' }), /busy session/)
|
||||
await rt.selectSessionModel('s4', { provider: 'p', model: 'm4' })
|
||||
assert.deepEqual(calls.slice(-3), ['start:s3:bad', 'start:s4:m4', 'end:s4:m4'])
|
||||
})
|
||||
|
||||
test('R4-05:群 Session 失败不再只 warn,applyModel 明确失败且不推进 appliedModel', async () => {
|
||||
const calls = []
|
||||
const ctx = {
|
||||
on() {},
|
||||
get(name) {
|
||||
if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'p', model: 'm' }), saveSelection: async () => {} }
|
||||
return undefined
|
||||
},
|
||||
llm: {
|
||||
listProviders: () => [{ id: 'p', name: 'P' }],
|
||||
listModels: async () => [{ id: 'm' }],
|
||||
resolveModelInfo: async () => undefined,
|
||||
},
|
||||
sessionController: {
|
||||
async selectModel({ sessionId }) {
|
||||
calls.push(sessionId)
|
||||
if (sessionId === 'group-1') throw new Error('group busy')
|
||||
return { selected: { provider: 'p', model: 'm' } }
|
||||
},
|
||||
},
|
||||
}
|
||||
const bot = { id: 'b1', name: 'B1', model: 'p/m', appliedModel: 'p/m' }
|
||||
const rt = {
|
||||
ctx, state: { bots: { b1: bot } }, warn() {}, save: async () => {},
|
||||
botOf: id => (id === 'b1' ? bot : undefined), chatOf: () => 'chat-b1',
|
||||
groupSessionsOf: () => ['group-1'],
|
||||
}
|
||||
install(rt)
|
||||
await assert.rejects(rt.applyModel(bot, { force: true }), /群会话应用失败/)
|
||||
assert.deepEqual(calls, ['chat-b1', 'group-1'])
|
||||
assert.equal(bot.appliedModel, 'p/m', '群失败不能推进 appliedModel')
|
||||
})
|
||||
|
||||
test('R4-05:selectModel 期间用户改了默认模型,恢复不覆盖用户新选择', async () => {
|
||||
const saved = []
|
||||
let current = { provider: 'old', model: 'oldm' }
|
||||
const ctx = {
|
||||
on() {},
|
||||
get(name) {
|
||||
if (name !== 'agentDefaultModel') return undefined
|
||||
return { currentSelection: () => current, saveSelection: async value => { saved.push(value); current = value } }
|
||||
},
|
||||
sessionController: {
|
||||
async selectModel() {
|
||||
current = { provider: 'user', model: 'picked' }
|
||||
return { selected: { provider: 'p', model: 'm' } }
|
||||
},
|
||||
},
|
||||
}
|
||||
const rt = { ctx, state: {}, warn() {} }
|
||||
install(rt)
|
||||
await rt.selectSessionModel('s1', { provider: 'p', model: 'm' })
|
||||
assert.deepEqual(saved, [], '不得覆盖用户在等待期间的选择')
|
||||
assert.deepEqual(current, { provider: 'user', model: 'picked' })
|
||||
})
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { install } from '../../ds-bot/src/host/models.js'
|
||||
|
||||
function harness(missing) {
|
||||
const ctx = {
|
||||
on() {},
|
||||
get() { return undefined },
|
||||
llm: {
|
||||
listProviders: () => [{ id: 'p', name: 'P' }],
|
||||
listModels: async () => [{ id: 'm1' }, { id: 'm2' }],
|
||||
resolveModelInfo: async () => undefined,
|
||||
},
|
||||
}
|
||||
const rt = { ctx, state: { bots: {} }, warn() {}, missingKeys: () => missing, save: async () => {} }
|
||||
install(rt)
|
||||
return rt
|
||||
}
|
||||
|
||||
test('Q13/R4-04:真实 catalog 的 needsKey 不再被 availabilityOf 当可用', async () => {
|
||||
const missing = new Set(['p'])
|
||||
const rt = harness(missing)
|
||||
const unavailable = await rt.availabilityOf('p/m1')
|
||||
assert.equal(unavailable.available, false)
|
||||
assert.equal(unavailable.needsKey, true)
|
||||
assert.match(unavailable.reason, /凭据/)
|
||||
const other = await rt.availabilityOf('p/nope')
|
||||
assert.equal(other.available, false)
|
||||
missing.clear()
|
||||
rt.dropCatalog()
|
||||
assert.equal((await rt.availabilityOf('p/m1')).available, true)
|
||||
})
|
||||
|
|
@ -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,53 @@ 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 })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q01:主状态缺失但 registry 有证据时 /sansheng/health 返回 503', async () => {
|
||||
const web = { register() { return () => {} } }
|
||||
const routes = routesOf(web)
|
||||
const store = {
|
||||
...fakeStore(),
|
||||
health: () => ({ status: 'missing', writable: false, registryStatus: 'ok', registryEntries: 4, error: '主状态缺失' }),
|
||||
}
|
||||
installRoute({ ctx: fakeCtx(web), store, dsbot: { botOf: () => undefined, roomOf: () => undefined, snapshot: () => ({ bots: {}, rooms: {} }) } })
|
||||
const res = fakeRes()
|
||||
await routes.find(item => item.path === '/sansheng/health').handler({ method: 'GET' }, res)
|
||||
assert.equal(res.statusCode, 503)
|
||||
assert.equal(JSON.parse(res.body).store.writable, false)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -114,3 +114,193 @@ 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.health().registryStatus, 'ok')
|
||||
assert.equal(store.health().writable, false)
|
||||
assert.equal(store.registryProjectForRoom('room-1'), 'prj-1')
|
||||
assert.equal(store.registryProjectForBot('b-lead'), 'prj-1')
|
||||
await assert.rejects(() => store.reconcileDispatches('boot-missing'), /state-protected|写操作已停止/)
|
||||
const after = new SanshengStore(file)
|
||||
await after.load()
|
||||
assert.equal(after.registryProjectForRoom('room-1'), 'prj-1', '启动对账不得覆盖 registry')
|
||||
} 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 })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q08c:junction 别名解析到同一物理工作根', async () => {
|
||||
if (process.platform !== 'win32') return
|
||||
const { execFileSync } = await import('node:child_process')
|
||||
const { mkdir } = await import('node:fs/promises')
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-alias-'))
|
||||
const real = join(dir, 'real-root')
|
||||
const alias = join(dir, 'alias-root')
|
||||
try {
|
||||
await mkdir(real)
|
||||
execFileSync('cmd', ['/c', 'mklink', '/J', alias, real], { stdio: 'ignore' })
|
||||
const store = new SanshengStore(join(dir, 'state.json'))
|
||||
await store.load()
|
||||
assert.equal((await store.acquireRootLease(real, { holder: 'a' })).ok, true)
|
||||
const second = await store.acquireRootLease(alias, { holder: 'b' })
|
||||
assert.equal(second.ok, false, 'junction 别名不能绕过根租约')
|
||||
} finally {
|
||||
try { execFileSync('cmd', ['/c', 'rmdir', alias], { stdio: 'ignore' }) } catch { /* not made */ }
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('Q08d:崩溃遗留的根租约到期后可被新持有者接管', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-expire-'))
|
||||
try {
|
||||
const store = new SanshengStore(join(dir, 'state.json'))
|
||||
await store.load()
|
||||
assert.equal((await store.acquireRootLease(dir, { holder: 'crashed', ttlMs: 30 })).ok, true)
|
||||
await new Promise(resolve => setTimeout(resolve, 60))
|
||||
const next = await store.acquireRootLease(dir, { holder: 'next' })
|
||||
assert.equal(next.ok, true)
|
||||
assert.equal(store.rootLeaseOf(dir).holder, 'next')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('R4-03:registry 的合法 JSON、错误 schema 不再当健康空登记', async () => {
|
||||
const { readFile, writeFile } = await import('node:fs/promises')
|
||||
const dir = await mkdtemp(join(tmpdir(), 'sansheng-registry-'))
|
||||
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 bad = [
|
||||
{ version: 1, rooms: [], bots: [] },
|
||||
{ rooms: {}, bots: {} },
|
||||
{ version: 99, rooms: {}, bots: {}, updatedAt: 1 },
|
||||
{ version: 1, rooms: { 'room-1': 7 }, bots: {}, updatedAt: 1 },
|
||||
{ version: 1, rooms: {}, bots: { 'b-lead': '' }, updatedAt: 1 },
|
||||
{ version: 1, rooms: {}, bots: {}, updatedAt: 'now' },
|
||||
]
|
||||
for (const payload of bad) {
|
||||
await writeFile(join(dir, 'registry.json'), JSON.stringify(payload), 'utf8')
|
||||
const store = new SanshengStore(file)
|
||||
await store.load()
|
||||
assert.equal(store.health().status, 'broken', JSON.stringify(payload))
|
||||
assert.equal(store.health().writable, false)
|
||||
assert.equal(store.health().registryStatus, 'broken')
|
||||
await assert.rejects(() => store.transact(() => {}), error => error.code === 'state-protected')
|
||||
assert.equal(await readFile(join(dir, 'registry.json'), 'utf8'), JSON.stringify(payload), '不得覆盖坏 registry')
|
||||
}
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
export class HarnessError extends Error {}
|
||||
export class BlockAssembler {
|
||||
constructor() { this.blocks = [] }
|
||||
add(block) { this.blocks.push(block); return this }
|
||||
build() { return this.blocks }
|
||||
}
|
||||
export function createUserMessage(input) {
|
||||
return { role: 'user', ...input }
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export function defineTool(def) { return def }
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
export async function resolve(specifier, context, next) {
|
||||
if (specifier === '@deepseek-ai/dsh-llm') {
|
||||
return { url: new URL('./dsh-llm.mjs', import.meta.url).href, shortCircuit: true }
|
||||
}
|
||||
if (specifier === '@deepseek-ai/dsh-tools') {
|
||||
return { url: new URL('./dsh-tools.mjs', import.meta.url).href, shortCircuit: true }
|
||||
}
|
||||
return next(specifier, context)
|
||||
}
|
||||
Loading…
Reference in New Issue