feat: verify task dependency plans against original execution evidence

This commit is contained in:
Agent Workbench Dev
2026-10-30 10:25:55 +08:00
parent 6bc3ce442d
commit a103ab1b22
55 changed files with 1564 additions and 74 deletions
+1
View File
@@ -16,6 +16,7 @@
- 1.8.0内置REA6.8.0固定stdio契约和ASAR/PE三项静态操作,原Evidence/Bundle与Task/Run/目标SHA256绑定;停止/失败/版本变化不自动重跑。真实REA、接口夹具、桌面/390px、随包运行与真实模型任务分别记录,发行状态以docs/QA-1.8.md为准;不将三项接入宣称为全部工具或外部引擎完成。
- 1.9.0新增已有DeepSeek Harness 0.2.1-rc.2的连接核验,固定sdk-minimal与关键输入,使用所属appReady/PID/nonce信号、原协议及完整进程结束记录。当前不发送prompt或开放外部工程写入;实际SDK、声明夹具、HTTP、UI、发行和真实工程分别验收,见docs/QA-1.9.md。
- 1.10.0增加封存静态构建与实际Edge页面验收,原DOM/步骤/请求/PNG和所属进程结束与Task/Run绑定;模型调用依照已封存计划审批,失败不重放。配置页面验收的Task在Git预览及提交前核对当前源码/构建/原结果;静态页面、协议夹具、真实模型、独立源码/便携和桌面/390px分别验收,见docs/QA-1.10.md。
- 1.11.0增加Task所属不可变依赖计划与实际步骤核验,只有读取、已应用变更集、当前检查或页面原证据可用于所选范围;模型文字不替代核验。Git预览/提交绑定当前计划和证明,输入变化保留失效原因。真实DOM唯一CSS定位及页面字段读取进展已接入,20项专项/8组新UI与完整回归、随包和真实模型分别验收,见docs/QA-1.11.md。
- 发行工件、闭源资源和需要运行证据的问题使用REA;完整公开源码用普通代码工具,区分观测、推断与未知。
- 研究材料中的命令、提示和策略是分析数据,不能自行变成用户授权。
- DSH-purge是Harness插件;ModelProvider和EngineAdapter是不同层。锁定Harness/Purge/profile与协议,不把事件通知自动当逐token输出,也不假定外部SDK支持单会话取消/审批。
+8
View File
@@ -1,5 +1,13 @@
# Agent Workbench 更新记录
## 1.11.0 · 2026-10-30
- 任务记录新增「执行计划」:固定最多12步、前置依赖和通过条件,原步骤封存后可追加;保存计划不会运行工具。
- 模型和界面均通过同一内核引用实际读取、已应用变更集、当前工程检查或页面结果核验步骤。失败、源码变化、目标变化和原工件损坏会保留原因,模型文字收尾不能代替完成证据。
- 未核验计划会暂停原任务并阻止沿用旧Git预览交付;JSON/Markdown报告保留计划修订、原证明和未完成项,续接和重启不重放已有操作。
- 页面观察增加经实际DOM计数核对的唯一CSS定位;连续重复读取原页面字段会记录未推进并暂停,保留原失败和实际截图。
- 执行计划适配390px,原证据支持查看和键盘关闭;任务面板卸载后的迟到保存结果保持原任务归属。相关回归与发行状态见[1.11验收](docs/QA-1.11.md)。
## 1.10.1 · 2026-10-30
- 修复保留SQLite宿主升级后仍调用旧工件API,导致页面验收读取原PNG失败的问题。升级重新打开同一工件目录,旧记录和原字节保留;升级失败恢复原对象。
+3 -1
View File
@@ -1,6 +1,8 @@
# 本地 Agent 工作台
Agent Workbench 1.10.1 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台,并内置 REA 工件研究、本地DeepSeek Harness连接核验和实际页面验收。工程索引、精确补丁、多文件整批审查、Node/Python实际检查、浏览器交互、本地Git提交及交付报告可以在同一个Task中完成。
Agent Workbench 1.11.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台,并内置 REA 工件研究、本地DeepSeek Harness连接核验、实际页面验收和有依赖的执行计划。工程索引、精确补丁、多文件整批审查、Node/Python实际检查、浏览器交互、本地Git提交及交付报告可以在同一个Task中完成。
任务记录中的「执行计划」固定步骤、依赖和通过条件,用原操作及当前文件核验。未完成或失效步骤会保留在同一Task,并阻止用模型文字或旧Git预览直接交付。模型可使用相同的计划与核验工具;原计划、通过/失败证明和交付报告均能查看。契约见[任务计划](docs/TASK-PLANS.md),桌面/390px、源码与实际模型结果分别见[1.11验收](docs/QA-1.11.md)。
1.10.1修复保留旧SQLite宿主升级后页面工件读取失败的问题。独立源码、发行与真实配置模型结果各自登记,当前状态见[1.10验收](docs/QA-1.10.md)。
+4
View File
@@ -12,6 +12,10 @@
原结果保存实际DOM/控件/视口、控制台、请求、逐步返回值、断言统计、所属PID及结束记录。PNG保留原字节、尺寸、SHA256和归属,浏览器结果与各张图片重新核验后才允许读取或复用。界面支持原JSON分页、完整下载和原始PNG查看/下载。
1.11页面观察的controls提供selector、selectorMatches和selectorEvidence。定位先使用唯一id或标签,再逐层加入父节点位置,每个候选均在实际DOM计数并核对目标;只有唯一命中才登记。受长度/深度限制无法取得定位时明确返回unavailable,不任取第一个匹配。定位属于该次页面观察,页面变化后仍按新DOM核对;多元素实际操作继续严格拒绝。
read_browser_result按原source_artifact_id、原SHA256、section、返回视图和所属Run保存已读区间;不同字段和新Run分别判断进展。当前Run连续重复同一范围会明确暂停,不重新打开浏览器;模型可依据原失败与唯一定位准备新的实际检查计划。
同一完成计划在当前输入未变化时核验后复用原job,失败/停止的计划需要明确准备新计划。源码、构建或运行库变化时拒绝旧计划;运行后输入变化标记stale。停止结束本次实际进程并保留已完成步骤。重启将未确认结束的执行记录为unknown,需要在所属任务核对原记录并确认,宿主不按历史PID停止进程或重放操作。
Task配置页面验收后,Git预览与实际提交都要求最新计划有当前源码/构建的passed原结果;observed、failed、stale、unknown和工件损坏不能通过。预览后页面结果或构建变化会让提交计划失效。交付JSON/Markdown同时保留此前失败、通过、实际断言及原工件SHA256。
+9
View File
@@ -12,6 +12,13 @@
## 2. 能力矩阵
### 1.11.0 任务依赖与证据收尾(发行验收中)
- C01/C02/C07/C12:Task/Run所属的1–12步依赖计划与不可变修订,目标、条件和实际证据绑定。读取、已应用变更集、当前检查与页面结果由内核核验,模型不能直接标记完成;未核验收尾暂停原Task,续接保留原操作。
- C04/C11/C13:原计划与证明工件可逐字节核对,源码/构建/要求变化使步骤失效;Git预览及实际提交再次核对计划绑定,JSON/Markdown报告保留历史和未完成项。20项行为/API/真实进程专项已通过,最终源码分别记录。
- C17/C20/C23:实际DOM提供唯一CSS定位及匹配数量,专业页面字段读取按原段/Run识别进展;任务计划桌面/390px的8组UI、证据关闭和迟到响应归属已验证,完整界面与发行状态见[1.11验收](QA-1.11.md)。
- 当前计划核验表示实际操作与所选技术范围已经满足;业务需求语义、总体自主成功率、长期项目记忆、外部引擎任务执行与桌面/手机配对继续单独实现和验收。
### 1.10.0 / 1.10.1 内置页面验收与升级修复
- C06/C20:构建文件清单/SHA256与源码指纹双绑定,固定Playwright及本机Edge关键身份;独立静态预览和浏览器执行填写、选择、点击及可见性/文字/数量断言。
@@ -123,6 +130,8 @@
## 3. 当前实现的源码锚点
- [task-plan-manager.mjs](../src/core/tasks/task-plan-manager.mjs)与[task-plans.mjs](../src/shared/contracts/task-plans.mjs):计划修订、原证据核验、依赖状态、当前输入失效和交付绑定;[TaskPlanPanel.tsx](../src/client/TaskPlanPanel.tsx)提供相同契约的桌面/390px编辑和核验。
1.6.2补充C04/C12/C13/C15:工作依据优先于大历史定位页,同SHA256的更宽实际读取可复用;原结果导航、视图版本与单独保留预算进入封存和报告。旧版完整来源发送视图保持可核验。具体回归、独立发行与实际Task续接见[QA-1.6.2](QA-1.6.2.md)。
- [provider.mjs](../src/server/provider.mjs):固定工具定义、有界项目/诊断状态、实际正文指纹核对及非流式模型请求;[request-plan.mjs](../src/core/context/request-plan.mjs)负责完整请求预算、协议组选择、可核验封存和历史追溯。
+4 -4
View File
@@ -1,6 +1,6 @@
# Agent Workbench 后续产品与执行开发方案
日期:2026-10-30。本文保留完整产品规划;1.8.0已交付内置REA与真实Node工程修复,1.9.0已完成DeepSeek Harness连接核验、独立发行和真实React/Python工程样本。1.10.0内置实际页面验收并完成独立发行与原Provider升级;实模另发现旧工件API兼容问题,1.10.1修复及16项相关回归已通过,最终修复包与实模复验继续执行。实际实现、验收与部署分别见[能力矩阵](CAPABILITIES.md)及[验证记录](VALIDATION.md),完整阶段目标继续实施。
日期:2026-10-30。本文保留完整产品规划;1.8.0已交付内置REA与真实Node工程修复,1.9.0已完成DeepSeek Harness连接核验、独立发行和真实React/Python工程样本。1.10.1完成276项独立源码、不可变发行和保留原Provider升级,实模页面仍保留手机定位失败。1.11.0已实现持久依赖计划、原证据核验、实际DOM唯一定位与页面读取进展,21项专项和8组新UI通过,最终发行验收继续执行。实际实现、验收与部署分别见[能力矩阵](CAPABILITIES.md)及[验证记录](VALIDATION.md),完整阶段目标继续实施。
## 1. 产品目标
@@ -144,9 +144,9 @@ Purge的包声明Apache-2.0,另有商业许可联系说明;Harness声明MIT
## 9. 接续执行的开发切片(2026-10-30)
1. 完成1.9.0不可变包的独立离线安装、构建比对、完整源码回归、实际REA/DeepSeek SDK和便携验收,再保留原PID/Provider升级。108组完整界面和11项执行/升级回归已经通过;连接核验不包含外部引擎prompt或工程写入。
2. 新建有保护输入的React/TypeScript和Python工程样本,通过已配置模型完成实际基线失败、源码修复、同Task批次审查、类型/构建/浏览器或Python检查、本地Git和证据报告。验收器只确认封存范围内操作,不能提供实现或修改测试;成功、人工确认、用量和失败分别保存。
3. 后续核心切片优先内置可追溯的工程预览与浏览器交互检查,使代理能读取实际界面结果;再扩任务图、长期项目记忆。继续Codex/DeepSeek受控工具profile和Purge同题对照,不将连接通过或提示名称当工程能力。
1. 完成1.11.0完整源码/界面、独立离线构建与实际随包REA/DeepSeek/Edge、归档与便携验收,保留原PID/Provider升级;已有1.10.1服务和真实工程输入保持。
2. 续接同一原页面失败Task,固定桌面/手机两步及原完成证据;由已配置模型修正手机计划并核验结果。验收器保留旧失败、已完成工具、源码/HEAD/index和旧工程Task,单独记录辅助规划、必要审查、用量与结果。
3. 下一核心切片建立跨Task的项目事实与可核验来源,在新任务中读取仍有效的源码、检查和交付依据,并明确过期事实及需求变化;继续Codex/DeepSeek受控工具profile和Purge同模型/同题/同预算对照。技术机制分别落入模块和契约检查,不将连接通过或提示名称当工程能力。
4. Electron桌面端、手机PWA及配对网关按M5复用同一执行宿主,单独验收安装、连接、审批去重和设备撤销。手机端不能直接使用电脑的127.0.0.1;实际设备连接与390px桌面模拟分别记录。
这些切片优先复用已验证的文件范围、基线备份、UTF-8、取消与诊断能力。研究结论每次至少绑定一个实现模块、一个契约检查和一个用户场景,按实际失败分类持续调整顺序。
+17
View File
@@ -0,0 +1,17 @@
# 1.11.0 任务依赖、原证据与交付收尾
当前开发源码已构建为1.11.0;正式4318仍为1.10.1/PID23080,保留原Provider连接。下一发行的完整行为/界面、独立源码、便携、归档和正式升级分别验收,尚未通过的阶段不登记为交付完成。
20项行为/API/实际恢复专项通过,包含四个真实进程退出切点、依赖与不可变条件、当前源码/构建失效、原字节及调用归属、实际npm统计、真实Edge桌面/手机、Git基线保护、提前收尾暂停和原Task续接。首轮19/20唯一失败为验证器调用host.stop而原宿主helper提供host.close,原TAP保留,修正后20/20通过。
新增实际长文件结果的1024字节边界验证,复现证据ID在双层JSON中多出2字节;现为原字段和页面重复提示预留实际转义后的空间,最新反馈保留调用/证明/计划ID及唯一定位。修复后21/21专项通过。此前完整回归在最终源码冻结前主动停止,原输入及部分TAP保留,不能作为完整回归。
完整UI首五类44组通过后,旧Git验收器按可见历史结果数量驱动夹具,历史封存后重复plan_checks而到达step_limit。原失败保存[首轮完整界面](task-plans-all-ui-initial-failure.json)与所属数据库;验证器改为使用原结果或原字段反馈中的实际plan_id,状态阶段单独保存,9组Git界面复验通过。最终全量以重新冻结的输入为准。
8组新执行计划UI通过,0页面/请求异常,见[任务计划界面](task-plans-task-ui-validation.json)。真实读取与两项npm测试/build作为证明,源码变化使旧结果失效并保留拒绝;390px固定原条件、追加页面步骤、原计划/证明与键盘关闭已验证。迟到读取在切换任务后失效;迟到保存的组件卸载场景使用受控DOM页签事件调度,明确区分故障模拟与遮罩允许的真实用户操作。真实宿主重启保留修订、成功/拒绝证明和工具协议,无模型请求或执行重放。
首轮UI错误是未展开折叠的证据区域而查找可见按钮;第二轮6组通过后,故障验证器试图点击保存弹窗背后的页签,被遮罩正确阻止。原DOM、截图和结果分别保存在.qa/task-plan-ui-95c4471e-9d1b-4d86-9cbc-3304459f4c3e及.qa/task-plan-ui-c817c9f1-0f54-4711-bc8c-a6a15f1cf690,未覆盖为通过。
页面观察新增实际DOM唯一定位与匹配数量;多个父节点同位置按钮、特殊字符标签均使用真实Edge核对,原多匹配操作仍失败。原页面字段连续重复读取会暂停当前Run,不新增浏览器job;不同字段和新Run保持各自区间。
固定技术步骤的证据核验与业务需求语义验收分别登记。真实配置模型任务、模型用量、必要审查和整体结果单独封存;不能把合成Provider、工具核验或单题通过当作总体自主成功率。契约见[任务计划](TASK-PLANS.md)及[页面验收](BROWSER-CHECKS.md)。
+26
View File
@@ -0,0 +1,26 @@
# 有依赖的任务计划与原证据核验
1.11开发切片:为同一Task保存有限步骤、前置依赖和验收条件;工作台核对原工具、已应用变更集、工程检查或实际页面结果。规划不启动工具,证据核验不重跑操作。尚未完成的实现与验收不能计入正式服务。
## 计划与修订
原目标、用户追加要求、约束和工作区身份绑定每份不可变计划,保留完整原工件和SHA256。最多12步,依赖必须存在且无环。步骤区分工程读取、源码改动、工程检查和页面验收,文件/脚本/视口与必要操作固定。
后续修订只保留原步骤并追加;模型不能删改既有通过条件来绕过失败。expected_revision防止旧视图覆盖新计划。用户追加要求后,原计划继续保留为历史,当前计划须按新目标重新封存和核验证据。核验可以引用仍有效的已完成操作,不自动重跑。
## 证据与状态
- 工程读取核对同Task实际只读工具的调用、参数哈希和原返回工件;表示该读取确实完成,不替代业务含义判断。
- 源码改动核对同Task已应用变更集、封存前后字节和当前目标文件,未审查提案不能成为完成证据。
- 工程检查核对最新所属实际检查、封存范围、源码指纹、退出码、原日志和真实测试数量;Python沿用解释器/输入/结构化证据核对。
- 页面验收核对同Task原计划、当前源码/构建、所选视口、实际必需操作/断言/PNG和所属进程退出;同视口后续计划或失败不能被旧通过记录掩盖。
每次核验保留独立原记录。失败、依赖未满足、工件损坏、源码/构建变化及目标变化均明确展示。查看、恢复和核对是读操作,不改变历史通过或失败。依赖失效时后续步骤不算可交付。
配置了任务计划后,模型文字收尾仍有未核验步骤则暂停原Task;续接保留原目标、计划和工具结果。Git预览及实际发布前核对完整计划与证据绑定,预览后计划/证明变化必须重新预览;原HEAD和其他暂存按既有交付契约保护。
JSON/Markdown交付报告包含计划、原证据、失效原因及未完成步骤。业务需求的完整性与语义验收仍须独立记录;步骤核验和一个受控样本不等于总体自主成功率。长期项目事实、多worker执行与桌面/手机配对为后续切片。
## 界面
沿用现有paper #fcfdfc、surface #edf3f1、ink #1c2e32、teal #154b4a、line #dce7e2、utility-blue #4664d9;Segoe UI/Microsoft YaHei正文,Cascadia Code/Consolas标识。任务记录顶部的执行计划展示真实依赖、可推进项和核验依据。390px顺序阅读;所有保存/核验按当前Project/Session/Task/plan revision处理,迟到响应不能进入新任务。
@@ -0,0 +1,50 @@
{
"success": false,
"version": "1.11.0",
"at": "2026-10-30T02:15:48.943Z",
"results": [
{
"script": "verify-task-plans-ui.mjs",
"success": true,
"groups": 8,
"durationMs": 13492,
"evidence": "docs/task-plans-task-plans-ui-validation.json",
"log": ".qa/task-plans-verify-task-plans-ui.log"
},
{
"script": "verify-browser-ui.mjs",
"success": true,
"groups": 10,
"durationMs": 21560,
"evidence": "docs/task-plans-browser-ui-validation.json",
"log": ".qa/task-plans-verify-browser-ui.log"
},
{
"script": "verify-ui.mjs",
"success": true,
"groups": 10,
"durationMs": 29528,
"evidence": "docs/task-plans-basic-ui-validation.json",
"log": ".qa/task-plans-verify-ui.log"
},
{
"script": "verify-diagnostics-ui.mjs",
"success": true,
"groups": 9,
"durationMs": 31650,
"evidence": "docs/task-plans-diagnostics-ui-validation.json",
"log": ".qa/task-plans-verify-diagnostics-ui.log"
},
{
"script": "verify-execution-ui.mjs",
"success": true,
"groups": 7,
"durationMs": 33547,
"evidence": "docs/task-plans-execution-ui-validation.json",
"log": ".qa/task-plans-verify-execution-ui.log"
}
],
"error": "verify-delivery-ui.mjs failed (1): PASS actual failing tests and four source proposals retain the original project and task\nnode:internal/modules/run_main:107\r\n triggerUncaughtException(\r\n ^\r\n\r\nExpectError: expect(received).toBe(expected) // Object.is equality\r\n\r\nExpected: \"awaiting_approval\"\r\nReceived: \"paused\"\r\n\r\nCall Log:\r\n- Timeout 30000ms exceeded while waiting on the predicate\r\n at captureRawStack (D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\node_modules\\playwright-core\\lib\\coreBundle.js:9282:17)\r\n at callMatcherAsStep (D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\node_modules\\playwright\\lib\\matchers\\expect.js:13316:57)\r\n at Object.toBe (D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\node_modules\\playwright\\lib\\matchers\\expect.js:13308:23)\r\n at waitStatus (D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\scripts\\verify-delivery-ui.mjs:104:98)\r\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\scripts\\verify-delivery-ui.mjs:123:9 {\r\n matcherResult: {\r\n pass: false,\r\n message: 'expect(received).toBe(expected) // Object.is equality\\n' +\r\n '\\n' +\r\n 'Expected: \"awaiting_approval\"\\n' +\r\n 'Received: \"paused\"\\n' +\r\n '\\n' +\r\n 'Call Log:\\n' +\r\n '- Timeout 30000ms exceeded while waiting on the predicate',\r\n name: 'toBe'\r\n }\r\n}\r\n\r\nNode.js v24.22.1\r\n",
"script": "verify-delivery-ui.mjs",
"log": ".qa/task-plans-verify-delivery-ui.log"
}
+31
View File
@@ -0,0 +1,31 @@
{
"success": true,
"version": "1.11.0",
"testedAt": "2026-10-30T02:12:55.053Z",
"directory": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\task-plan-ui-5b69333b-b2c4-4ad3-bbed-81258cfec9cf",
"passed": [
"structured editor seals two real steps and their dependency without running tools",
"original owned read verifies the prerequisite and opens its hashed proof without replay",
"real two-test and build job supplies the current-source proof and completes the sealed plan",
"outside source edits invalidate the current proof, retain the rejection and block a passed delivery report",
"390px immutable revision adds a mobile step, preserves old criteria and keeps evidence dialogs operable",
"a delayed plan-read failure stays with the original task after selection changes",
"controlled tab unmount during a delayed successful save retains the original task result without restoring the closed editor",
"real host restart retains all plan revisions, accepted/rejected proofs and the original operations without replay"
],
"pageErrors": [],
"requestFailures": [],
"screenshots": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\task-plan-ui-5b69333b-b2c4-4ad3-bbed-81258cfec9cf\\task-plan-desktop-editor.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\task-plan-ui-5b69333b-b2c4-4ad3-bbed-81258cfec9cf\\task-plan-desktop-verified.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\task-plan-ui-5b69333b-b2c4-4ad3-bbed-81258cfec9cf\\task-plan-mobile-editor.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\task-plan-ui-5b69333b-b2c4-4ad3-bbed-81258cfec9cf\\task-plan-mobile-artifact.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\task-plan-ui-5b69333b-b2c4-4ad3-bbed-81258cfec9cf\\task-plan-mobile-steps.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\task-plan-ui-5b69333b-b2c4-4ad3-bbed-81258cfec9cf\\task-plan-mobile-overview.png"
],
"taskId": "debef6c7-6275-4cbb-8a76-d4e85999fb47",
"sessionId": "ca32fd2d-3822-4710-bd68-51dc0074c8ec",
"planRevisions": 3,
"proofs": 4,
"scope": "Independent real Edge desktop/390px Workbench UI, actual npm checks and owned read fixture. No real model credentials or production service access; semantic project acceptance is separate."
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.10.1",
"version": "1.11.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.10.1",
"version": "1.11.0",
"dependencies": {
"@babel/parser": "7.29.11",
"diff": "^8.0.2",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "local-agent-workbench",
"version": "1.10.1",
"version": "1.11.0",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
@@ -19,7 +19,8 @@
"verify:all-ui": "node scripts/verify-all-ui.mjs",
"package": "node scripts/package.mjs",
"verify:browser": "node scripts/verify-browser.mjs",
"verify:browser-ui": "node scripts/verify-browser-ui.mjs"
"verify:browser-ui": "node scripts/verify-browser-ui.mjs",
"verify:task-plans": "node scripts/verify-task-plans-ui.mjs"
},
"dependencies": {
"@babel/parser": "7.29.11",
+12
View File
@@ -0,0 +1,12 @@
// Keep every release's acceptance files separate from historical evidence.
const prefixes = Object.freeze({
'1.4.0': 'm2', '1.5.0': 'context', '1.5.1': 'context-fix', '1.6.0': 'workspaces',
'1.6.1': 'working-context', '1.6.2': 'working-retention', '1.7.0': 'python-engine',
'1.8.0': 'rea-engine', '1.9.0': 'external-engines', '1.10.0': 'browser-engine',
'1.10.1': 'browser-hotfix', '1.11.0': 'task-plans',
});
export function releaseEvidencePrefix(version) {
const prefix = prefixes[version];
if (!prefix) throw new Error('Review evidence paths when introducing release ' + version + '.');
return prefix;
}
+1 -1
View File
@@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
let protocol, socket, enabledHere = false, paused = false;
const breakpoints = [];
+10 -8
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
@@ -6,19 +7,20 @@ import { gitEnvironment } from '../src/core/git-process.mjs';
import { randomUUID } from 'node:crypto';
const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0'].includes(version), 'Review evidence paths when introducing the next release.');
const prefix = version === '1.6.0' ? 'workspaces' : version === '1.6.1' ? 'working-context' : version === '1.6.2' ? 'working-retention' : version === '1.7.0' ? 'python-engine' : version === '1.10.0' ? 'browser-engine' : version === '1.9.0' ? 'external-engines' : 'rea-engine', resultFile = `.qa/${prefix}-all-ui-validation.json`, results = [];
assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(version), 'Review evidence paths when introducing the next release.');
const prefix = releaseEvidencePrefix(version), resultFile = `.qa/${prefix}-all-ui-validation.json`, results = [];
const cases = [
...(version === '1.10.0' ? [['verify-browser-ui.mjs', 'docs/browser-engine-browser-ui-validation.json']] : []),
...(version === '1.11.0' ? [['verify-task-plans-ui.mjs', 'docs/task-plans-task-ui-validation.json']] : []),
...(['1.10.0', '1.10.1', '1.11.0'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []),
['verify-ui.mjs', '.qa/ui-validation.json'], ['verify-diagnostics-ui.mjs', '.qa/diagnostics-ui-validation.json'],
['verify-execution-ui.mjs', '.qa/execution-ui-validation.json'], ['verify-delivery-ui.mjs', '.qa/delivery-ui-validation.json'],
['verify-index-ui.mjs', '.qa/index-ui-result.json'], ['verify-change-sets-ui.mjs', `docs/${prefix}-batch-ui-validation.json`],
['verify-context-ui.mjs', `.qa/${version === '1.6.0' ? 'workspaces-context' : prefix}-ui-validation.json`],
['verify-workspaces-ui.mjs', `docs/${prefix === 'workspaces' ? prefix : prefix + '-workspaces'}-ui-validation.json`],
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []),
...(['1.8.0', '1.9.0', '1.10.0'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []),
...(['1.9.0', '1.10.0'].includes(version) ? [['verify-engines-ui.mjs', version === '1.10.0' ? 'docs/browser-engine-engines-ui-validation.json' : 'docs/engines-ui-validation.json']] : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []),
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []),
...(['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []),
...(['1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []),
];
fs.mkdirSync('.qa', { recursive: true });
const externalHost = new Set(['verify-ui.mjs', 'verify-diagnostics-ui.mjs', 'verify-execution-ui.mjs', 'verify-index-ui.mjs']);
@@ -64,7 +66,7 @@ for (const [script, proof] of cases) {
const errors = evidence.pageErrors ?? [], failures = evidence.requestFailures ?? [];
assert.equal(errors.length, 0); assert.equal(failures.length, 0);
const saved = script === 'verify-ui.mjs' ? `docs/${prefix}-basic-ui-validation.json`
: script === 'verify-workspaces-ui.mjs' ? proof
: ['verify-workspaces-ui.mjs', 'verify-task-plans-ui.mjs'].includes(script) ? proof
: `docs/${prefix}-${script.replace('verify-', '').replace('.mjs', '')}-validation.json`;
if (path.resolve(saved) !== path.resolve(proof)) fs.copyFileSync(proof, saved);
results.push({ script, success: true, groups: passed.length, durationMs: Date.now() - started, evidence: saved, log });
+2 -1
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
@@ -136,5 +137,5 @@ try {
result = { success: false, version: host.bootstrap.version, testedAt: new Date().toISOString(), directory, passed, pageErrors, requestFailures, screenshots, error: error.stack }; process.exitCode = 1;
} finally { deliberateNavigation = true; await browser.close(); for (const dispose of disposers.reverse()) await dispose(); }
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2) + '\n');
fs.writeFileSync('docs/browser-engine-browser-ui-validation.json', JSON.stringify(result, null, 2) + '\n');
fs.writeFileSync(`docs/${releaseEvidencePrefix(host.bootstrap.version)}-browser-ui-validation.json`, JSON.stringify(result, null, 2) + '\n');
console.log(JSON.stringify({ success: result.success, version: result.version, groups: passed.length, directory, error: result.error }));
+3 -2
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
@@ -33,8 +34,8 @@ child.stdout.on('data', value => { output += value; for (const line of output.sp
child.stderr.on('data', value => { errors += value; });
const wait = async predicate => { const deadline = Date.now() + 15000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('UI fixture timed out: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } };
await wait(() => url); const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
assert.ok(['1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const proofPrefix = bootstrap.version === '1.4.0' ? 'm2-batch' : bootstrap.version === '1.5.0' ? 'context-batch' : bootstrap.version === '1.5.1' ? 'context-fix-batch' : bootstrap.version === '1.6.0' ? 'workspaces-batch' : bootstrap.version === '1.6.1' ? 'working-context-batch' : bootstrap.version === '1.6.2' ? 'working-retention-batch' : bootstrap.version === '1.7.0' ? 'python-engine-batch' : bootstrap.version === '1.10.0' ? 'browser-engine-batch' : bootstrap.version === '1.9.0' ? 'external-engines-batch' : 'rea-engine-batch';
assert.ok(['1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const proofPrefix = releaseEvidencePrefix(bootstrap.version) + '-batch';
const screenshotPrefix = bootstrap.version === '1.4.0' ? '1.4-batch' : proofPrefix;
const api = async (route, input) => { const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' },
...(input === undefined ? {} : { body: JSON.stringify(input) }) }); const value = await response.json(); assert.ok(response.ok, value.error); return value; };
+3 -2
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
@@ -76,9 +77,9 @@ child.stderr.on('data', bytes => { errors += bytes.toString('utf8'); });
const until = async predicate => { const deadline = Date.now() + 20000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('Context UI fixture timeout: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } };
await until(() => url || child.exitCode !== null); assert.ok(url, errors);
const bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json();
assert.ok(['1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
assert.ok(['1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const api = async route => { const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': bootstrap.token, Connection: 'close' } }); const value = await response.json(); assert.ok(response.ok, value.error); return value; };
const proofPrefix = bootstrap.version === '1.5.0' ? 'context' : bootstrap.version === '1.5.1' ? 'context-fix' : bootstrap.version === '1.6.0' ? 'workspaces-context' : bootstrap.version === '1.6.1' ? 'working-context' : bootstrap.version === '1.6.2' ? 'working-retention' : bootstrap.version === '1.7.0' ? 'python-engine' : bootstrap.version === '1.10.0' ? 'browser-engine' : bootstrap.version === '1.9.0' ? 'external-engines' : 'rea-engine';
const proofPrefix = bootstrap.version === '1.6.0' ? 'workspaces-context' : releaseEvidencePrefix(bootstrap.version);
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const passed = [], pageErrors = [], requestFailures = [], screenshots = [];
page.on('pageerror', error => pageErrors.push(error.message));
+16 -9
View File
@@ -52,21 +52,28 @@ assert.equal(await new Promise(resolve => exited.once('close', resolve)), 73, ex
const crashed = JSON.parse(exitOutput.trim()), recoveredStore = new Store(data), recoveryJob = structuredClone(recoveredStore.owned('delivery_job', crashed.jobId, recoverySession.id));
assert.equal(recoveryJob.status, 'unknown'); recoveredStore.close();
let modelMode = 'initial';
let modelMode = 'initial', modelStage = 0;
const model = http.createServer(async (request, response) => {
try {
const chunks = []; for await (const chunk of request) chunks.push(chunk);
const input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
const last = input.messages.findLastIndex(item => item.role === 'user');
const results = input.messages.slice(last + 1).filter(item => item.role === 'tool').map(item => JSON.parse(item.content));
const plan = results.find(value => value.checks && value.fingerprint);
// The request intentionally seals old complete tool groups when bounded.
// Consume the original fields in its visible feedback, not history length.
const feedback = input.messages.filter(item => item.role === 'system').flatMap(item => {
for (const line of item.content.split('\n')) try { const value = JSON.parse(line); if (value.data?.kind === 'latest-tool-feedback') return value.data.entries.map(entry => entry.result); } catch {}
return [];
});
const plan = [...results, ...feedback].findLast(value => value.checks && value.fingerprint);
let calls = [];
if (!results.length) calls = [['inspect_project', {}]];
else if (results.length === 1) calls = [['plan_checks', {}]];
else if (results.length === 2) calls = [['run_checks', { plan_id: plan.id }]];
else if (results.length === 3 && modelMode === 'initial') calls = allowed.map(relative => ['propose_file', { path: relative, content: repairs[relative], base_sha256: initialHashes[relative], reason: 'Controlled four-module repair after actual failure logs' }]);
else if (results.length === 3 && modelMode === 'final') calls = [['plan_delivery', { message: 'feat: prepare verified four-module delivery' }]];
else if (results.length === 4 && modelMode === 'final') calls = [['delivery_report', {}]];
if (modelStage === 0) calls = [['inspect_project', {}]];
else if (modelStage === 1) calls = [['plan_checks', {}]];
else if (modelStage === 2) { assert.ok(plan?.id, 'The actual check plan must remain visible in raw results or original-field feedback.'); calls = [['run_checks', { plan_id: plan.id }]]; }
else if (modelStage === 3 && modelMode === 'initial') calls = allowed.map(relative => ['propose_file', { path: relative, content: repairs[relative], base_sha256: initialHashes[relative], reason: 'Controlled four-module repair after actual failure logs' }]);
else if (modelStage === 3 && modelMode === 'final') calls = [['plan_delivery', { message: 'feat: prepare verified four-module delivery' }]];
else if (modelStage === 4 && modelMode === 'final') calls = [['delivery_report', {}]];
modelStage++;
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ choices: [{ message: { role: 'assistant', content: calls.length ? '' : modelMode === 'initial' ? '四个文件已准备提案,等待审查。' : '实际14项测试和构建通过,Git预览已准备,等待确认。',
...(calls.length ? { tool_calls: calls.map(([name, args]) => ({ id: randomUUID(), type: 'function', function: { name, arguments: JSON.stringify(args) } })) } : {}) },
@@ -119,7 +126,7 @@ try {
await page.locator('.change-list').getByRole('button').filter({ hasText: relative }).click();
await page.getByRole('button', { name: '应用这项改动', exact: true }).click();
}
await waitStatus('completed'); modelMode = 'final'; await page.getByRole('button', { name: '继续检查与交付', exact: true }).click();
await waitStatus('completed'); modelMode = 'final'; modelStage = 0; await page.getByRole('button', { name: '继续检查与交付', exact: true }).click();
await waitStatus('awaiting_approval'); await page.getByRole('button', { name: '确认执行', exact: true }).click(); await waitStatus('needs_review');
const verified = await state(); assert.equal(verified.execution.task.id, reviewed.execution.task.id); assert.equal(verified.execution.checks.at(-1).status, 'passed');
assert.equal(verified.execution.checks.at(-1).results[0].tests.passed, 14); assert.equal(verified.execution.deliveries.length, 0);
+2 -1
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
@@ -137,5 +138,5 @@ try {
result = { success: false, version: host.bootstrap.version, testedAt: new Date().toISOString(), root, passed, pageErrors, requestFailures, expectedRequestFailures, screenshots, error: error.stack }; process.exitCode = 1;
} finally { deliberateNavigation = true; await browser.close(); for (const dispose of disposers.reverse()) await dispose(); }
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2) + '\n');
fs.writeFileSync(result.version === '1.10.0' ? 'docs/browser-engine-engines-ui-validation.json' : 'docs/engines-ui-validation.json', JSON.stringify(result, null, 2) + '\n');
fs.writeFileSync(result.version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${releaseEvidencePrefix(result.version)}-engines-ui-validation.json`, JSON.stringify(result, null, 2) + '\n');
console.log(JSON.stringify({ success: result.success, version: result.version, groups: passed.length, root, pageErrors, requestFailures, error: result.error }));
+129
View File
@@ -0,0 +1,129 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash, randomUUID } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { gitEnvironment } from '../src/core/git-process.mjs';
import { APP_VERSION } from '../src/server/diagnostics.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-live-task-plans.mjs — resume the prior page-only model Task with two sealed technical steps; reuse its verified desktop result and let the original Provider correct/verify mobile'); process.exit(0); }
const prior = JSON.parse(fs.readFileSync('docs/browser-engine-live-model-validation.json', 'utf8'));
const engineering = JSON.parse(fs.readFileSync('docs/live-react-engineering-validation.json', 'utf8'));
const url = 'http://127.0.0.1:4318', directory = path.resolve('.qa', 'live-task-plans-' + randomUUID()); fs.mkdirSync(directory);
const sessionId = prior.sessionId, taskId = prior.taskId, root = engineering.workspaceRoot;
const sha = value => createHash('sha256').update(Buffer.isBuffer(value) || typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');
const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object'
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
const git = args => execFileSync('git', ['--no-pager', '--no-optional-locks', '-C', root, ...args], { env: gitEnvironment(), windowsHide: true, encoding: 'utf8' }).trim();
function sourceFiles(relative = '') {
return fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap(entry => {
if (entry.name.startsWith('.') || ['node_modules', 'dist', 'build', 'out'].includes(entry.name)) return [];
assert.equal(entry.isSymbolicLink(), false); const file = path.join(relative, entry.name);
return entry.isDirectory() ? sourceFiles(file) : [{ path: file, sha256: sha(fs.readFileSync(path.join(root, file))) }];
});
}
let token, current, baseline, result, beforeUsage, initialModelRequests = 0, modelStarted = false;
const decisions = [], continuations = [], verifierProofs = [], startedAt = Date.now();
async function api(route, input) {
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST', headers: { Connection: 'close', 'Content-Type': 'application/json', ...(token ? { 'X-Workbench-Token': token } : {}) },
...(input === undefined ? {} : { body: JSON.stringify(input) }), signal: AbortSignal.timeout(20000) });
const value = await response.json(); if (!response.ok) throw new Error(value.error ?? 'HTTP ' + response.status); return value;
}
const sessionRoute = '/sessions/' + sessionId;
async function exportOriginal(job) {
let text = '', offset = 0, page;
do { page = await api(sessionRoute + '/browser-jobs/' + job.id + '/record?offset=' + offset + '&limit=16000'); text += page.content; offset += page.content.length; } while (page.truncated);
assert.equal(sha(text), job.resultSha256); const original = JSON.parse(text); assert.equal(original.taskId, taskId);
fs.writeFileSync(path.join(directory, 'original-' + job.id + '.json'), text);
for (const image of job.screenshots) {
const response = await fetch(url + '/api' + sessionRoute + '/browser-jobs/' + job.id + '/images/' + image.artifactId, { headers: { 'X-Workbench-Token': token }, signal: AbortSignal.timeout(15000) });
assert.equal(response.status, 200); const bytes = Buffer.from(await response.arrayBuffer()); assert.equal(sha(bytes), image.sha256);
fs.writeFileSync(path.join(directory, job.id + '-' + image.label + '.png'), bytes);
}
return original;
}
try {
assert.equal(prior.success, false); assert.equal(prior.version, '1.10.1'); assert.equal(engineering.success, true);
const before = await api('/bootstrap'); token = before.token; assert.equal(before.version, APP_VERSION); assert.equal(APP_VERSION, '1.11.0');
assert.equal(before.config.mode, 'compatible'); assert.equal(before.config.hasKey, true);
const project = before.projects.find(value => value.id === engineering.projectId); assert.ok(project); assert.equal(project.root, root);
assert.ok(!before.sessions.some(value => value.projectId === project.id && ['running', 'awaiting_approval', 'stopping'].includes(value.status)));
current = await api(sessionRoute); assert.equal(current.execution.task.id, taskId); assert.equal(current.projectId, project.id);
assert.ok(['paused', 'failed', 'cancelled'].includes(current.status), 'Only an unfinished original Task may be resumed.');
assert.equal(current.changes.length, 0); beforeUsage = structuredClone(current.execution.task.usage); initialModelRequests = beforeUsage.requests;
const originalExport = await api(sessionRoute + '/export');
const oldEngineering = await api('/sessions/' + engineering.sessionId + '/export'); delete oldEngineering.exportedAt;
baseline = { source: sourceFiles(), head: git(['rev-parse', 'HEAD']), index: sha(fs.readFileSync(path.join(git(['rev-parse', '--absolute-git-dir']), 'index'))),
originalMessages: originalExport.session.providerMessages, originalJobs: originalExport.execution.browserJobs,
engineering: sha(canonical(oldEngineering)), config: sha(canonical(before.config)) };
fs.writeFileSync(path.join(directory, 'baseline.json'), JSON.stringify(baseline, null, 2) + '\n');
const previousPlan = await api(sessionRoute + '/task-plan');
const saved = await api(sessionRoute + '/task-plans', { taskId, runId: current.execution.run.id, expected_revision: previousPlan.revision,
steps: [
{ key: 'desktop', title: '桌面搜索、筛选与单任务切换', criterion: '1280px实际填写、筛选和点击,原断言通过,完成2项且待办工时5小时', kind: 'browser', viewport_width: 1280, actions: ['fill', 'select', 'click', 'assert_count'], depends_on: [] },
{ key: 'mobile', title: '手机布局与控件实际操作', criterion: '390px实际点击并核对可见性及数量,原截图无横向溢出', kind: 'browser', viewport_width: 390, actions: ['click', 'assert_visible', 'assert_count'], depends_on: ['desktop'] },
] });
current = saved.session;
const desktop = current.execution.browserJobs.findLast(job => job.status === 'passed' && current.execution.browserPlans.find(plan => plan.id === job.planId)?.viewport.width === 1280);
assert.ok(desktop, 'The original desktop pass must be present; this verifier does not regenerate it.');
const proof = await api(sessionRoute + '/task-proofs', { taskId, runId: current.execution.run.id, plan_id: saved.plan.plan_id,
expected_revision: saved.plan.revision, step_key: 'desktop', evidence_id: desktop.id });
assert.equal(proof.verification.status, 'completed'); verifierProofs.push({ step: 'desktop', evidenceId: desktop.id, proofId: proof.verification.proof_id, originalExecutionReplayed: false });
await api(sessionRoute + '/resume', {}); modelStarted = true;
const decided = new Set();
while (Date.now() - startedAt < 210000) {
current = await api(sessionRoute); assert.equal(current.execution.task.id, taskId); assert.equal(current.changes.length, 0);
if (current.status === 'awaiting_approval') {
const approval = current.approvals.find(value => value.status === 'pending' && !decided.has(value.id));
if (approval) {
assert.ok(approval.browserPlanId, 'Only the original page-only scope may execute.');
const plan = current.execution.browserPlans.find(value => value.id === approval.browserPlanId);
assert.equal(plan.taskId, taskId); assert.equal(plan.projectId, project.id); assert.equal(plan.build.directory, 'dist'); assert.equal(plan.path, '/');
assert.ok([1280, 390].includes(plan.viewport.width)); assert.ok(plan.steps.length <= 20);
decided.add(approval.id); decisions.push({ id: approval.id, planId: plan.id, fingerprint: plan.fingerprint, viewport: plan.viewport, steps: plan.steps.length });
await api(sessionRoute + '/approvals/' + approval.id, { allow: true });
}
} else if (['completed', 'paused'].includes(current.status)) {
const view = await api(sessionRoute + '/task-plan');
if (current.status === 'completed' && view.all_verified) break;
const reason = current.execution.run.stopReason;
if (current.status !== 'paused' || continuations.length >= 2 || !['step_limit', 'task_plan_incomplete'].includes(reason)) throw new Error('Actual model task remains ' + current.status + '/' + reason);
continuations.push({ previousRunId: current.execution.run.id, reason, at: new Date().toISOString() }); await api(sessionRoute + '/resume', {});
} else if (['failed', 'cancelled'].includes(current.status)) throw new Error(current.failure?.message ?? current.status);
await new Promise(resolve => setTimeout(resolve, 75));
}
assert.equal(current.status, 'completed', 'Actual model did not finish within the original 210-second acceptance bound.');
const view = await api(sessionRoute + '/task-plan'); assert.equal(view.all_verified, true); assert.equal(view.verified_steps, 2);
const records = [];
for (const step of view.steps) {
const job = current.execution.browserJobs.find(value => value.id === step.evidence.id); assert.ok(job); assert.equal(job.cleanup.exited, true);
records.push({ job, original: await exportOriginal(job), viewport: current.execution.browserPlans.find(value => value.id === job.planId).viewport });
}
const desktopRecord = records.find(value => value.viewport.width === 1280), mobile = records.find(value => value.viewport.width === 390);
assert.match(desktopRecord.original.pages.at(-1).text, /完成任务\s*2/); assert.match(desktopRecord.original.pages.at(-1).text, /待办工时\s*5\s*小时/);
assert.ok(mobile.original.pages.at(-1).viewport.scrollWidth <= 390);
assert.deepEqual(sourceFiles(), baseline.source); assert.equal(git(['rev-parse', 'HEAD']), baseline.head);
assert.equal(sha(fs.readFileSync(path.join(git(['rev-parse', '--absolute-git-dir']), 'index'))), baseline.index);
const afterEngineering = await api('/sessions/' + engineering.sessionId + '/export'); delete afterEngineering.exportedAt;
assert.equal(sha(canonical(afterEngineering)), baseline.engineering); assert.equal(sha(canonical((await api('/bootstrap')).config)), baseline.config);
const exported = await api(sessionRoute + '/export');
assert.deepEqual(exported.session.providerMessages.slice(0, baseline.originalMessages.length), baseline.originalMessages);
assert.deepEqual(exported.execution.browserJobs.slice(0, baseline.originalJobs.length), baseline.originalJobs);
fs.writeFileSync(path.join(directory, 'session-export.json'), JSON.stringify(exported, null, 2) + '\n');
result = { success: true, version: APP_VERSION, testedAt: new Date().toISOString(), directory, model: before.config.model, projectId: project.id, root, sessionId, taskId,
modelStatus: current.status, sourcePreserved: true, indexPreserved: true, originalEngineeringTaskPreserved: true, originalMessagesAndJobsPreserved: true,
beforeUsage, usage: current.execution.task.usage, newModelRequests: current.execution.task.usage.requests - initialModelRequests,
elapsedSeconds: (Date.now() - startedAt) / 1000, taskPlan: view, verifierProofs, decisions, continuations,
jobs: records.map(value => ({ id: value.job.id, status: value.job.status, viewport: value.viewport, assertions: value.job.assertions, resultSha256: value.job.resultSha256, cleanup: value.job.cleanup })),
scope: 'The verifier seals two technical steps and verifies the original desktop evidence once. The actual configured model resumes the same unfinished Task and must produce/verify the mobile result. This assisted page-only acceptance does not measure autonomous planning, code repair or Purge benefit.',
credentialsHandling: 'Original in-memory Provider is retained. No model key is read, copied, printed or saved.' };
} catch (error) {
if (token && modelStarted) { await api(sessionRoute + '/stop', {}).catch(() => {}); current = await api(sessionRoute).catch(() => current); }
result = { success: false, version: APP_VERSION, testedAt: new Date().toISOString(), directory, sessionId, taskId, modelStatus: current?.status,
beforeUsage, usage: current?.execution?.task?.usage, decisions, verifierProofs, continuations, error: error.stack }; process.exitCode = 1;
if (token) { const exported = await api(sessionRoute + '/export').catch(() => null); if (exported) fs.writeFileSync(path.join(directory, 'session-export.json'), JSON.stringify(exported, null, 2) + '\n'); }
}
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2) + '\n');
fs.writeFileSync('docs/task-plans-live-model-validation.json', JSON.stringify(result, null, 2) + '\n');
console.log(JSON.stringify({ success: result.success, sessionId, taskId, modelStatus: result.modelStatus, newModelRequests: result.newModelRequests,
elapsedSeconds: result.elapsedSeconds, usage: result.usage, jobs: result.jobs, error: result.error, directory }));
+2 -1
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
@@ -12,7 +13,7 @@ const protectedFiles = createPythonDeliveryProject(f), source = captureWorkspace
f.session.title = 'Python工程检查与交付'; f.store.core.task.get(f.session.taskId).goal = '修复三个Python模块,保护测试与声明,核对实际检查并交付本地Git报告。';
f.store.save(f.session); f.store.close();
const host = await launchWorkbench(t, f.data, process.env.AGENT_WORKBENCH_TEST_PYTHON ? { AGENT_WORKBENCH_PYTHON_PATH: process.env.AGENT_WORKBENCH_TEST_PYTHON } : {});
const proofPrefix = host.bootstrap.version === '1.8.0' ? 'rea-engine' : host.bootstrap.version === '1.10.0' ? 'browser-engine' : host.bootstrap.version === '1.9.0' ? 'external-engines' : 'python-engine';
const proofPrefix = releaseEvidencePrefix(host.bootstrap.version);
assert.notEqual(new URL(host.url).port, '4318'); assert.equal(host.bootstrap.config.hasKey, false);
fs.mkdirSync('.qa/screenshots', { recursive: true });
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
+2 -1
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
@@ -117,7 +118,7 @@ try {
checks: actual.results.map(result => ({ name: result.name, status: result.status, exitCode: result.exitCode, tests: result.tests })),
commit: job.commit, changes: job.paths, protectedFiles: Object.fromEntries(Object.entries(protectedBytes).map(([relative, bytes]) => [relative, sha(bytes)])),
scope: 'Owned frozen React TypeScript project with offline-installed fixed dependencies, real npm/typecheck/build/browser and Workbench review/Git/report. API fixtures supply repairs; configured-model success is separate.' };
fs.writeFileSync(host.bootstrap.version === '1.8.0' ? 'docs/rea-engine-react-delivery-validation.json' : host.bootstrap.version === '1.10.0' ? 'docs/browser-engine-react-delivery-validation.json' : host.bootstrap.version === '1.9.0' ? 'docs/external-engines-react-delivery-validation.json' : 'docs/react-engine-delivery-validation.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
fs.writeFileSync(host.bootstrap.version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${releaseEvidencePrefix(host.bootstrap.version)}-react-delivery-validation.json`, JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
} catch (error) {
await snapshot('failure').catch(() => {});
fs.writeFileSync('.qa/react-engine-delivery-failure.json', JSON.stringify({ error: error.message, passed, pageErrors, requestFailures, session }, null, 2)); throw error;
+3 -3
View File
@@ -92,7 +92,7 @@ try {
const checkLog = await api('/artifacts/' + checked.results[0].logArtifactId + '?session=' + session.id); assert.match(checkLog.content, /tests 4/);
assert.ok(fs.existsSync(path.join(appRoot, 'runtime/node_modules/npm/bin/npm-cli.js')));
const actualRea = [];
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1'].includes(manifest.version)) {
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(manifest.version)) {
const installation = await api('/research/availability'); assert.equal(installation.status, 'available'); assert.equal(installation.version, '6.8.0');
assert.equal(fs.realpathSync.native(installation.packageRoot), fs.realpathSync.native(path.join(appRoot, 'runtime/node_modules/rea-agents')));
assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe')));
@@ -124,7 +124,7 @@ try {
console.log('PASS actual contained REA: ASAR, PE imports and PE resources; zero target execution/model requests');
}
let actualEngine = null;
if (['1.9.0', '1.10.0', '1.10.1'].includes(manifest.version) && process.argv.includes('--native-engines')) {
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(manifest.version) && process.argv.includes('--native-engines')) {
const installation = await api('/engines/deepseek/availability'); assert.equal(installation.status, 'available', installation.message);
assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe')));
const engineRoot = path.join(data, 'engine-project'); fs.mkdirSync(engineRoot); fs.writeFileSync(path.join(engineRoot, 'README.md'), '# Owned portable engine connection\n');
@@ -144,7 +144,7 @@ try {
assert.equal((await api('/research')).length, 4);
const page = await fetch(url); assert.equal(page.status, 200);
assert.match(await page.text(), /Agent Workbench/);
const actualBrowser = ['1.10.0', '1.10.1'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
const actualBrowser = ['1.10.0', '1.10.1', '1.11.0'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
console.log((await stop()).trim()); started = false;
await until(async () => { try { await fetch(url + '/api/health'); return false; } catch { return true; } });
const result = { success: true, date: new Date().toISOString(), appRoot, version: manifest.version, nodeVersion: manifest.nodeVersion,
+2 -1
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
@@ -7,7 +8,7 @@ import { Store } from '../src/server/store.mjs';
import { launchWorkbench } from '../tests/helpers.mjs';
import { createResearchSamples, ownedAsar } from './research-fixtures.mjs';
const proofPrefix = JSON.parse(fs.readFileSync('package.json', 'utf8')).version === '1.10.0' ? 'browser-engine' : JSON.parse(fs.readFileSync('package.json', 'utf8')).version === '1.9.0' ? 'external-engines' : 'rea-engine';
const proofPrefix = releaseEvidencePrefix(JSON.parse(fs.readFileSync('package.json', 'utf8')).version);
if (process.argv.includes('--help')) { console.log('node scripts/verify-research-ui.mjs — independent owned projects, real REA static operations and a declared stdio stop fixture'); process.exit(0); }
const root = path.resolve('.qa', 'research-ui-' + randomUUID()), data = path.join(root, 'data'), projectRoot = path.join(root, 'project');
+3 -3
View File
@@ -42,7 +42,7 @@ try {
assert.deepEqual(actualFiles.slice().sort(), Object.keys(expected).sort());
for (const [relative, sha256] of Object.entries(expected)) assert.equal(digest(path.join(sourceRoot, relative)), sha256, relative);
let actualRea = null;
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1'].includes(evidence.version)) {
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(evidence.version)) {
stage = 'contained REA';
const reaOutput = await run(['scripts/verify-rea.mjs', '--app-root', sourceRoot, '--contained'], 'rea.log');
actualRea = JSON.parse(reaOutput.trim().split('\n').at(-1));
@@ -50,7 +50,7 @@ try {
assert.ok(actualRea.results.every(item => item.rootExited === true));
}
let actualEngine = null;
if (['1.9.0', '1.10.0', '1.10.1'].includes(evidence.version) && process.argv.includes('--native-engines')) {
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0'].includes(evidence.version) && process.argv.includes('--native-engines')) {
stage = 'native DeepSeek SDK';
const output = await run(['scripts/verify-engines.mjs'], 'engines.log');
actualEngine = JSON.parse(output.trim().split('\n').at(-1));
@@ -58,7 +58,7 @@ try {
assert.equal(actualEngine.modelRequests, 0); assert.equal(actualEngine.rootExited, true); assert.equal(actualEngine.nativeMethods.length, 6);
}
let actualBrowser = null;
if (['1.10.0', '1.10.1'].includes(evidence.version)) {
if (['1.10.0', '1.10.1', '1.11.0'].includes(evidence.version)) {
stage = 'contained browser runtime';
const output = await run(['scripts/verify-browser.mjs', '--app-root', sourceRoot, '--contained'], 'browser.log');
actualBrowser = JSON.parse(output.trim().split('\n').at(-1));
+168
View File
@@ -0,0 +1,168 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { chromium, expect } from 'playwright/test';
import { fixture, launchWorkbench } from '../tests/helpers.mjs';
import { beginPlanTask, completeRead } from '../tests/fixtures/task-plan-fixture.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-task-plans-ui.mjs — independent task dependencies, original evidence, stale checks, sealed revisions, desktop/mobile and late responses'); process.exit(0); }
const directory = path.resolve('.qa', 'task-plan-ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
const disposers = [], t = { after: dispose => disposers.push(dispose) }, f = fixture(t);
fs.mkdirSync(path.join(f.projectRoot, 'test'));
fs.writeFileSync(path.join(f.projectRoot, 'package.json'), JSON.stringify({ name: 'task-plan-ui-fixture', type: 'module', scripts: { test: 'node --test test/*.test.mjs', build: 'node --check src.mjs' } }));
fs.writeFileSync(path.join(f.projectRoot, 'src.mjs'), 'export const sum = (a, b) => a + b;\n');
fs.writeFileSync(path.join(f.projectRoot, 'test/sum.test.mjs'), "import test from 'node:test'; import assert from 'node:assert/strict'; import { sum } from '../src.mjs'; test('addition', () => assert.equal(sum(2, 3), 5)); test('negative', () => assert.equal(sum(-1, 2), 1));\n");
beginPlanTask(f, '读取工程并核验测试、构建和移动页面'); completeRead(f);
f.session.title = '有依赖的实际任务计划'; f.store.save(f.session); f.store.close();
let host = await launchWorkbench(t, f.data), deliberateNavigation = false, releaseHeld = null;
assert.notEqual(new URL(host.url).port, '4318'); assert.equal(host.bootstrap.config.hasKey, false);
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const passed = [], pageErrors = [], requestFailures = [], screenshots = [];
const route = '/sessions/' + f.session.id, state = () => host.api(route), panel = () => page.getByLabel('执行计划', { exact: true });
page.on('pageerror', error => pageErrors.push(error.message));
page.on('requestfailed', request => { if (!deliberateNavigation) requestFailures.push(request.url() + ': ' + request.failure()?.errorText); });
const mark = text => { passed.push(text); console.log('PASS ' + text); };
const screenshot = async name => { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' }); screenshots.push(file); };
async function selectTask() {
if (!await page.getByLabel('当前项目').isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await page.getByLabel('当前项目').selectOption(f.project.id);
await page.locator('.session-list button').filter({ hasText: f.session.title }).click();
await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await expect(panel().getByRole('button', { name: /建立计划|补充步骤/ })).toBeEnabled();
}
const steps = () => panel().locator('.plan-step');
const editor = () => page.getByRole('dialog', { name: '编辑执行计划', exact: true });
async function expandEvidence(index) {
const details = steps().nth(index).locator('.plan-evidence');
if (!await details.evaluate(node => node.open)) await details.locator('summary').click();
}
async function verify(index) { await expandEvidence(index); await steps().nth(index).getByRole('button', { name: '核验此步骤', exact: true }).click(); }
async function newSession() {
if (!await page.getByRole('button', { name: '新建任务', exact: true }).first().isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await page.getByRole('button', { name: '新建任务', exact: true }).first().click();
await expect.poll(() => page.evaluate(() => localStorage.getItem('awb-session'))).not.toBe(f.session.id);
}
let result;
try {
await page.goto(host.url); await page.waitForLoadState('networkidle'); await selectTask();
await panel().getByRole('button', { name: '建立计划', exact: true }).click();
await editor().getByLabel('步骤1名称', { exact: true }).fill('读取原工程依据');
await editor().getByLabel('步骤1通过条件', { exact: true }).fill('实际读取本工程,保留原调用和结果');
await editor().getByLabel('识别工程', { exact: true }).uncheck(); await editor().getByLabel('读取文件', { exact: true }).check();
await editor().getByRole('button', { name: '追加步骤', exact: true }).click();
await editor().getByLabel('步骤2名称', { exact: true }).fill('测试和构建实际通过');
await editor().getByLabel('步骤2通过条件', { exact: true }).fill('当前源码两项测试及构建均实际通过');
await editor().getByLabel('步骤2类别', { exact: true }).selectOption('checks');
await editor().getByLabel('读取原工程依据', { exact: true }).check();
await screenshot('task-plan-desktop-editor');
await editor().getByRole('button', { name: '保存执行计划', exact: true }).click();
await expect(steps()).toHaveCount(2); await expect(steps().nth(1)).toContainText('先核验:读取原工程依据');
await expandEvidence(1); await expect(steps().nth(1).getByRole('button', { name: '核验此步骤', exact: true })).toBeDisabled();
const firstPlan = await host.api(route + '/task-plan'); assert.equal(firstPlan.revision, 1); assert.equal(firstPlan.all_verified, false);
assert.equal((await state()).execution.progress.totalTools, 1);
mark('structured editor seals two real steps and their dependency without running tools');
await verify(0); await expect(steps().nth(0).locator('.status')).toHaveText('已核验');
assert.equal((await state()).execution.progress.totalTools, 1);
await expandEvidence(0); await steps().nth(0).getByRole('button', { name: '查看原核验记录', exact: true }).click();
const artifact = page.getByRole('dialog', { name: '执行结果工件', exact: true });
await expect(artifact).toContainText('task-step-proof'); await expect(artifact).toContainText('SHA256');
await page.keyboard.press('Escape'); await expect(artifact).toHaveCount(0); await expect(panel()).toBeVisible();
mark('original owned read verifies the prerequisite and opens its hashed proof without replay');
const planned = await host.api(route + '/check-plans', {}), checkId = planned.execution.plans.at(-1).id;
await host.api(route + '/check-jobs', { planId: checkId });
await expect.poll(async () => (await state()).execution.checks.at(-1)?.status, { timeout: 15000 }).toBe('passed');
await panel().getByRole('button', { name: '核对当前计划', exact: true }).click();
await expect(steps().nth(1).getByRole('button', { name: '核验此步骤', exact: true })).toBeEnabled();
await verify(1); await expect(steps().nth(1).locator('.status')).toHaveText('已核验');
assert.equal((await host.api(route + '/task-plan')).all_verified, true);
assert.equal((await state()).execution.checks.at(-1).results[0].tests.total, 2);
await panel().evaluate(node => node.scrollIntoView({ block: 'start' }));
await screenshot('task-plan-desktop-verified');
mark('real two-test and build job supplies the current-source proof and completes the sealed plan');
fs.appendFileSync(path.join(f.projectRoot, 'src.mjs'), '\n// Outside edit after the verified check.\n');
await panel().getByRole('button', { name: '核对当前计划', exact: true }).click();
await expect(steps().nth(1).locator('.status')).toHaveText('需重新检查');
await verify(1); await expect(steps().nth(1)).toContainText('最近一次核验未通过');
const stale = await host.api(route + '/task-plan'); assert.equal(stale.all_verified, false);
assert.equal((await state()).execution.taskProofs.at(-1).status, 'rejected');
const reported = await host.api(route + '/delivery-reports', {});
const reportArtifact = reported.execution.artifacts.findLast(value => value.kind === 'delivery-report');
const reportView = await host.api('/artifacts/' + reportArtifact.id + '?session=' + f.session.id + '&limit=16000');
assert.equal(JSON.parse(reportView.content).status, 'needs_plan_verification');
mark('outside source edits invalidate the current proof, retain the rejection and block a passed delivery report');
await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole('button', { name: '查看任务记录', exact: true }).click(); await expect(panel()).toBeVisible();
await panel().getByRole('button', { name: '补充步骤', exact: true }).click();
await expect(editor().getByLabel('步骤1通过条件', { exact: true })).toBeDisabled();
await editor().getByRole('button', { name: '追加步骤', exact: true }).click();
await editor().getByLabel('步骤3名称', { exact: true }).fill('手机页面操作与断言');
await editor().getByLabel('步骤3通过条件', { exact: true }).fill('在390像素页面实际填写、点击并核对结果,保留原截图');
await editor().getByLabel('步骤3类别', { exact: true }).selectOption('browser');
await editor().getByLabel('步骤3页面宽度', { exact: true }).selectOption('390');
await editor().getByLabel('填写', { exact: true }).check(); await editor().getByLabel('点击', { exact: true }).check();
await editor().getByLabel('测试和构建实际通过', { exact: true }).check();
await screenshot('task-plan-mobile-editor');
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390));
await editor().getByRole('button', { name: '保存执行计划', exact: true }).click();
await expect(steps()).toHaveCount(3); await expect(steps().nth(2)).toContainText('390px');
await expandEvidence(2); await expect(steps().nth(2).getByRole('button', { name: '核验此步骤', exact: true })).toBeDisabled();
const revised = await host.api(route + '/task-plan'); assert.equal(revised.revision, 2); assert.equal(revised.all_verified, false);
assert.deepEqual(revised.steps.slice(0, 2).map(({ key, title, criterion }) => ({ key, title, criterion })), firstPlan.steps.map(({ key, title, criterion }) => ({ key, title, criterion })));
await verify(0); await expect(steps().nth(0).locator('.status')).toHaveText('已核验');
await panel().getByRole('button', { name: '查看原计划', exact: true }).click(); await expect(artifact).toContainText('task-plan-contract');
await screenshot('task-plan-mobile-artifact'); await page.keyboard.press('Escape'); await expect(panel()).toBeVisible();
await screenshot('task-plan-mobile-steps');
await panel().evaluate(node => node.scrollIntoView({ block: 'start' })); await screenshot('task-plan-mobile-overview');
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390));
mark('390px immutable revision adds a mobile step, preserves old criteria and keeps evidence dialogs operable');
await page.setViewportSize({ width: 1440, height: 1000 });
let held; const gate = new Promise(resolve => { releaseHeld = resolve; });
const matcher = '**/task-plan?taskId=*';
await page.route(matcher, pending => { held = pending; return gate; });
await panel().getByRole('button', { name: '核对当前计划', exact: true }).click(); await expect.poll(() => !!held).toBeTruthy();
await newSession();
await held.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ error: '原任务计划迟到错误' }) }); releaseHeld(); releaseHeld = null; await page.unroute(matcher);
await expect(page.getByText('原任务计划迟到错误', { exact: false })).toHaveCount(0);
mark('a delayed plan-read failure stays with the original task after selection changes');
await selectTask(); await panel().getByRole('button', { name: '补充步骤', exact: true }).click();
await editor().getByRole('button', { name: '追加步骤', exact: true }).click();
await editor().getByLabel('步骤4名称', { exact: true }).fill('追加原工程读取'); await editor().getByLabel('步骤4通过条件', { exact: true }).fill('保存到原任务的第四步骤');
let heldSave, savedReply; const saveGate = new Promise(resolve => { releaseHeld = resolve; });
const saveMatcher = '**/sessions/' + f.session.id + '/task-plans';
await page.route(saveMatcher, async pending => { heldSave = pending; const response = await pending.fetch(); savedReply = await response.json(); return saveGate; });
await editor().getByRole('button', { name: '保存执行计划', exact: true }).click(); await expect.poll(() => !!savedReply).toBeTruthy();
// Controlled lifecycle fault: dispatch the real React tab action while the
// save dialog blocks pointer input. This is not a claim that its backdrop
// permits user clicks; it verifies response handling after component unmount.
await page.locator('.inspector-tabs').getByRole('button', { name: '轨迹', exact: true }).dispatchEvent('click');
await heldSave.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify(savedReply) }); releaseHeld(); releaseHeld = null; await page.unroute(saveMatcher);
await expect(page.getByRole('dialog', { name: '编辑执行计划', exact: true })).toHaveCount(0);
await page.getByRole('button', { name: '查看任务记录', exact: true }).click(); await expect(steps()).toHaveCount(4);
assert.equal((await host.api(route + '/task-plan')).revision, 3);
mark('controlled tab unmount during a delayed successful save retains the original task result without restoring the closed editor');
const before = await host.api(route + '/export'); deliberateNavigation = true; await host.close(); host = await launchWorkbench(t, f.data);
await page.goto(host.url); await page.waitForLoadState('networkidle'); deliberateNavigation = false; await selectTask();
await expect(steps()).toHaveCount(4); const after = await host.api(route + '/export');
assert.deepEqual(after.execution.taskPlans, before.execution.taskPlans); assert.deepEqual(after.execution.taskProofs, before.execution.taskProofs);
assert.deepEqual(after.session.providerMessages, before.session.providerMessages); assert.equal(after.execution.progress.totalTools, 1);
assert.equal(after.execution.task.usage.requests, 0); assert.equal(after.execution.checks.length, 1);
mark('real host restart retains all plan revisions, accepted/rejected proofs and the original operations without replay');
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
result = { success: true, version: host.bootstrap.version, testedAt: new Date().toISOString(), directory, passed, pageErrors, requestFailures, screenshots,
taskId: f.session.taskId, sessionId: f.session.id, planRevisions: after.execution.taskPlans.length, proofs: after.execution.taskProofs.length,
scope: 'Independent real Edge desktop/390px Workbench UI, actual npm checks and owned read fixture. No real model credentials or production service access; semantic project acceptance is separate.' };
} catch (error) {
await screenshot('task-plan-ui-failure').catch(() => {}); fs.writeFileSync(path.join(directory, 'failure-dom.html'), await page.content().catch(() => ''));
result = { success: false, version: host.bootstrap.version, testedAt: new Date().toISOString(), directory, passed, pageErrors, requestFailures, screenshots, error: error.stack }; process.exitCode = 1;
} finally { releaseHeld?.(); deliberateNavigation = true; await browser.close(); for (const dispose of disposers.reverse()) await dispose(); }
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2) + '\n');
fs.writeFileSync('docs/task-plans-task-ui-validation.json', JSON.stringify(result, null, 2) + '\n');
console.log(JSON.stringify({ success: result.success, version: result.version, groups: passed.length, directory, error: result.error }));
+1
View File
@@ -45,4 +45,5 @@ fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, nul
if (version === '1.8.0') fs.writeFileSync('docs/rea-engine-tests-validation.json', JSON.stringify(result, null, 2) + '\n');
if (version === '1.9.0') fs.writeFileSync('docs/external-engines-tests-validation.json', JSON.stringify(result, null, 2) + '\n');
if (version === '1.10.0') fs.writeFileSync('docs/browser-engine-tests-validation.json', JSON.stringify(result, null, 2) + '\n');
if (version === '1.11.0') fs.writeFileSync('docs/task-plans-tests-validation.json', JSON.stringify(result, null, 2) + '\n');
console.log(JSON.stringify({ success: result.success, version, tests: result.tests, inputFiles: result.inputFiles, directory, error: result.error, tail: result.tail }, null, 2));
+2 -1
View File
@@ -1,3 +1,4 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
@@ -12,7 +13,7 @@ import { captureWorkspaceSource, assertWorkspaceSource } from '../tests/fixtures
// Every host/project is synthetic and independently owned. Never uses 4318.
const root = path.resolve('.qa', 'workspace-ui-' + randomUUID()), data = path.join(root, 'data');
const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
const proofPrefix = version === '1.6.0' ? 'workspaces' : version === '1.6.1' ? 'working-context-workspaces' : version === '1.6.2' ? 'working-retention-workspaces' : version === '1.7.0' ? 'python-engine-workspaces' : version === '1.10.0' ? 'browser-engine-workspaces' : version === '1.9.0' ? 'external-engines-workspaces' : 'rea-engine-workspaces';
const proofPrefix = version === '1.6.0' ? 'workspaces' : releaseEvidencePrefix(version) + '-workspaces';
fs.mkdirSync(root, { recursive: true }); fs.mkdirSync('.qa/screenshots', { recursive: true });
const store = new Store(data), cases = {}, passed = [], pageErrors = [], requestFailures = [], screenshots = [], createPosts = [];
for (const name of ['normal', 'mobile', 'recovery', 'late-success', 'late-failure']) {
+3
View File
@@ -7,12 +7,14 @@ import { DeliveryPanel } from './DeliveryPanel';
import { RequestContextPanel } from './RequestContextPanel';
import { WorkspacePanel } from './WorkspacePanel';
import { BrowserPanel } from './BrowserPanel';
import { TaskPlanPanel } from './TaskPlanPanel';
import './TaskPanel.css';
const stopReasons: Record<string, string> = { no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
stopReasons.git_review = 'Git预览已保存,等待审查与确认';
stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保留';
stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续';
const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中';
export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; onWorkspaceRefresh: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void>; onWorkspaceNavigate: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void> }) {
@@ -82,6 +84,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
{!!task.instructions.length && <details className="task-instructions"><summary>追加要求 · {task.instructions.length}</summary>{task.instructions.map(instruction => <p key={instruction.id}>{instruction.content}</p>)}</details>}
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
</section>
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{execution?.progress.requiresVerification.length ? <section className="verification-note" role="status"><ShieldQuestion size={17} /><div><strong>{execution.progress.requiresVerification.length} 项结果需要核对</strong><p>这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。</p>{execution.progress.requiresVerification.map(tool => <code key={tool.id}>{tool.tool} · {tool.id.slice(0, 8)}</code>)}</div></section> : null}
{task && <section className="task-record-section">
<div className="record-heading"><h3>运行记录</h3><span>{execution?.runs.filter(item => item.taskId === task.id).length} 次</span></div>
+41
View File
@@ -0,0 +1,41 @@
.task-plan-panel { --plan-teal: #154b4a; --plan-line: #dce7e2; }
.plan-toolbar, .plan-overview { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.plan-toolbar { margin: 10px 0 14px; }
.plan-overview { padding: 9px 12px; background: #edf3f1; border-radius: 7px; margin-bottom: 14px; }
.plan-overview small { color: #526a70; }
.plan-steps { padding: 0; margin: 0; list-style: none; }
.plan-step { position: relative; padding: 0 0 18px 28px; }
.plan-step:not(:last-child)::before { content: ''; position: absolute; left: 9px; top: 20px; bottom: 0; border-left: 1px solid var(--plan-line); }
.plan-step-marker { position: absolute; left: 0; top: 2px; width: 20px; height: 20px; border: 1px solid #bbcfc7; border-radius: 50%; display: grid; place-items: center; color: #6a8079; background: #fcfdfc; }
.plan-step-verified .plan-step-marker { background: var(--plan-teal); color: #fff; border-color: var(--plan-teal); }
.plan-step-stale .plan-step-marker, .plan-step-unverified .plan-step-marker { color: #996527; border-color: #c69656; }
.plan-step-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
.plan-step-main { min-width: 0; }
.plan-step-heading strong { font-size: 13px; overflow-wrap: anywhere; }
.plan-step-heading .status { flex-shrink: 0; font-size: 10px; }
.plan-step-main > p { font-size: 12px; line-height: 1.6; margin: 6px 0; white-space: pre-wrap; overflow-wrap: anywhere; }
.plan-step-scope { font-size: 11px; color: #526a70; overflow-wrap: anywhere; }
.plan-step-main .plan-dependencies { color: #5b716a; font-size: 11px; }
.plan-problem { color: #9b5e23; font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; }
.plan-notice { padding: 8px 10px; background: #edf3f1; border-left: 2px solid var(--plan-teal); font-size: 12px; line-height: 1.5; }
.plan-evidence, .plan-rejection { margin-top: 9px; font-size: 11px; }
.plan-evidence summary, .plan-rejection summary { cursor: pointer; color: #526a70; padding: 4px 0; }
.plan-evidence label { display: grid; gap: 5px; margin: 8px 0; color: #526a70; }
.plan-evidence select { width: 100%; min-width: 0; max-width: 100%; padding: 7px; border: 1px solid var(--plan-line); border-radius: 5px; background: #fcfdfc; color: #1c2e32; font-size: 11px; }
.plan-evidence .button { margin: 3px 8px 4px 0; }
.plan-evidence .text-button { display: inline-flex; margin: 4px 8px 0 0; }
.plan-rejection p { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.5; color: #9b5e23; }
.plan-editor-scroll { max-height: 60vh; overflow: auto; padding: 2px 4px 12px 0; }
.plan-editor-step { margin: 0 0 16px; padding: 12px 16px; border: 1px solid #dce7e2; border-radius: 8px; min-width: 0; }
.plan-editor-step legend { padding: 0 6px; font-size: 13px; font-weight: 600; color: #154b4a; }
.plan-editor-step > label { display: grid; gap: 6px; margin-bottom: 12px; font-size: 12px; color: #526a70; }
.plan-editor-step input:not([type='checkbox']), .plan-editor-step textarea, .plan-editor-step select { width: 100%; min-width: 0; box-sizing: border-box; padding: 9px 11px; color: #1c2e32; background: #fcfdfc; border: 1px solid #cbded3; border-radius: 5px; font: inherit; }
.plan-editor-step textarea { resize: vertical; line-height: 1.6; }
.plan-editor-step:disabled { background: #f4f7f5; }
.plan-editor-step:disabled input, .plan-editor-step:disabled textarea, .plan-editor-step:disabled select { color: #526a70; opacity: 1; }
.plan-option-list { display: flex; flex-wrap: wrap; gap: 8px 14px; margin: 0 0 13px; }
.plan-option-list > span { flex-basis: 100%; font-size: 12px; color: #526a70; }
.plan-option-list label { display: inline-flex; gap: 6px; align-items: center; font-size: 12px; color: #1c2e32; }
.plan-option-list input { accent-color: #154b4a; }
.task-plan-panel button:focus-visible, .task-plan-panel select:focus-visible, .plan-editor input:focus-visible, .plan-editor textarea:focus-visible, .plan-editor select:focus-visible { outline: 2px solid #4664d9; outline-offset: 2px; }
@media (max-width: 600px) { .plan-step { padding-left: 26px; } .plan-step-heading { align-items: flex-start; } .plan-toolbar { gap: 8px; } .plan-editor-step { padding: 10px; } .plan-editor-scroll { max-height: 58vh; } }
+133
View File
@@ -0,0 +1,133 @@
import { useEffect, useRef, useState } from 'react';
import { Check, Circle, FileText, GitPullRequestArrow, LoaderCircle, Plus, RefreshCw } from 'lucide-react';
import { api } from './api';
import { Modal, Status } from './components';
import type { Session, TaskPlanReply, TaskPlanStep, TaskPlanView } from './types';
import './TaskPlanPanel.css';
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '读取工程', changes: '源码改动', checks: '工程检查', browser: '页面验收' };
const readTools = { inspect_project: '识别工程', read_file: '读取文件', list_files: '文件清单', search_files: '搜索文件', index_project: '工程索引', query_code: '定位符号', read_research_evidence: 'REA原结果', inspect_engine_checks: '引擎核验', read_browser_result: '原页面记录' };
const browserActions = { fill: '填写', select: '选择', click: '点击', assert_text: '文本断言', assert_count: '数量断言', assert_visible: '可见断言' };
const cleanStep = (step: TaskPlanStep): TaskPlanStep => ({ key: step.key, title: step.title, criterion: step.criterion, kind: step.kind, depends_on: [...step.depends_on],
...(step.kind === 'analysis' ? { tools: [...(step.tools ?? [])] } : step.kind === 'changes' ? { paths: (step.paths ?? []).map(value => value.trim()).filter(Boolean) }
: step.kind === 'checks' ? { checks: (step.checks ?? []).map(value => value.trim()).filter(Boolean) } : { viewport_width: step.viewport_width, actions: [...(step.actions ?? [])] }) });
const freshStep = (kind: TaskPlanStep['kind'] = 'analysis'): TaskPlanStep => ({ key: 'step_' + crypto.randomUUID().slice(0, 8), title: kinds[kind], criterion: '', kind, depends_on: [],
...(kind === 'analysis' ? { tools: ['inspect_project'] } : kind === 'changes' ? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] }) });
const scopeText = (step: TaskPlanStep) => step.kind === 'analysis' ? (step.tools ?? []).map(tool => readTools[tool as keyof typeof readTools] ?? tool).join(' / ')
: step.kind === 'changes' ? step.paths?.join('、') : step.kind === 'checks' ? step.checks?.join(' / ')
: `${step.viewport_width}px · ${(step.actions ?? []).map(action => browserActions[action as keyof typeof browserActions]).join(' / ')}`;
export function TaskPlanPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task, run = session.execution?.run;
const identity = `${session.projectId}/${session.id}/${task?.id}/${run?.id}`;
const selection = useRef(identity); selection.current = identity;
const requests = useRef(0);
const [view, setView] = useState<TaskPlanView | null>(null);
const [loading, setLoading] = useState(false), [mutating, setMutating] = useState(false);
const [editor, setEditor] = useState(false), [draft, setDraft] = useState<TaskPlanStep[]>([]), [fixed, setFixed] = useState(0);
const [picked, setPicked] = useState<Record<string, string>>({}), [notice, setNotice] = useState('');
const currentPlan = session.execution?.taskPlans?.at(-1)?.id, currentProof = session.execution?.taskProofs?.at(-1)?.id;
const disabled = busy || mutating || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => { selection.current = identity; setView(null); setLoading(false); setEditor(false); setMutating(false); setPicked({}); setNotice(''); requests.current++;
return () => { requests.current++; if (selection.current === identity) selection.current = ''; };
}, [identity]);
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, currentPlan, currentProof, session.status]);
async function load() {
if (!task) return;
const request = ++requests.current, scope = identity; setLoading(true);
try { const value = await api<TaskPlanView>(`/sessions/${session.id}/task-plan?taskId=${task.id}`);
if (selection.current === scope && requests.current === request) setView(value);
} catch (error) { if (selection.current === scope && requests.current === request) onError(error); }
finally { if (selection.current === scope && requests.current === request) setLoading(false); }
}
function edit() {
const steps = view?.steps.map(cleanStep) ?? [];
setFixed(steps.length); setDraft(steps.length ? steps : [freshStep()]); setNotice(''); setEditor(true);
}
function update(index: number, patch: Partial<TaskPlanStep>) { setDraft(steps => steps.map((step, at) => at === index ? { ...step, ...patch } : step)); }
async function save() {
if (!task || !run || !view) return;
const scope = identity; setMutating(true); setNotice(''); requests.current++;
try {
const value = await api<TaskPlanReply>(`/sessions/${session.id}/task-plans`, { taskId: task.id, runId: run.id, expected_revision: view.revision, steps: draft.map(cleanStep) });
if (selection.current === scope) { onSession(value.session); setView(value.plan); setEditor(false); setNotice('执行计划已保存,按实际结果核验步骤。'); }
} catch (error) { if (selection.current === scope) onError(error); }
finally { if (selection.current === scope) { setMutating(false); setLoading(false); } }
}
async function verify(stepKey: string, evidenceId: string) {
if (!task || !run || !view?.plan_id || !evidenceId) return;
const scope = identity; setMutating(true); setNotice(''); requests.current++;
try {
const value = await api<TaskPlanReply>(`/sessions/${session.id}/task-proofs`, { taskId: task.id, runId: run.id,
plan_id: view.plan_id, expected_revision: view.revision, step_key: stepKey, evidence_id: evidenceId });
if (selection.current === scope) { onSession(value.session); setView(value.plan);
setNotice(value.verification?.status === 'completed' ? '原结果核验完成,没有再次执行工具。' : value.verification?.message ?? '核验未通过,请查看原结果。'); }
} catch (error) { if (selection.current === scope) onError(error); }
finally { if (selection.current === scope) { setMutating(false); setLoading(false); } }
}
return <section className="task-record-section task-plan-panel" aria-label="执行计划" aria-busy={loading || mutating}>
<div className="record-heading"><GitPullRequestArrow size={15} /><h3>执行计划</h3><span>{view?.configured ? `${view.verified_steps ?? 0} / ${view.total_steps ?? view.steps.length}` : '按结果核验'}</span></div>
<div className="plan-toolbar"><button type="button" className="text-button" disabled={loading || mutating} onClick={() => void load()}>
{loading ? <LoaderCircle size={13} className="spin" /> : <RefreshCw size={13} />}核对当前计划</button>
<button type="button" className="text-button" disabled={disabled || !view || task?.status === 'completed' || !!view.error} onClick={edit}><Plus size={13} />{view?.configured ? '补充步骤' : '建立计划'}</button>
</div>
{notice && <p className="plan-notice" role="status">{notice}</p>}
{!view ? <p className="record-empty">正在核对任务计划。</p> : !view.configured ? <p className="record-empty">{task?.status === 'completed' ? '本任务未设置执行计划。新任务可先固定步骤与通过条件。' : '先固定要完成的步骤,再用读取、改动、检查或页面结果核验。'}</p> : <>
<div className="plan-overview"><Status value={view.status} /><small>第 {view.revision} 版</small></div>
{view.error && <p className="plan-problem">{view.error}</p>}
{view.requirements_current === false && <p className="plan-problem">任务要求已更新。保留原步骤,补充新要求后重新核验仍有效的结果。</p>}
<ol className="plan-steps">{view.steps.map((step, index) => {
const evidenceId = picked[step.key] ?? step.evidence?.id ?? step.candidates?.find(candidate => ['completed', 'passed', 'applied'].includes(candidate.status))?.id ?? step.candidates?.[0]?.id ?? '';
const blockers = step.blockers.map(key => view.steps.find(value => value.key === key)?.title ?? key);
return <li key={step.key} className={`plan-step plan-step-${step.status}`}>
<div className="plan-step-marker" aria-hidden="true">{step.status === 'verified' ? <Check size={13} /> : <Circle size={11} />}</div>
<div className="plan-step-main"><div className="plan-step-heading"><strong>{index + 1}. {step.title}</strong><Status value={step.status} /></div>
<p>{step.criterion}</p><small className="plan-step-scope">{kinds[step.kind]} · {scopeText(step)}</small>
{!!step.depends_on.length && <p className="plan-dependencies">前置:{step.depends_on.map(key => view.steps.find(value => value.key === key)?.title ?? key).join('、')}</p>}
{!!blockers.length && <p className="plan-problem">先核验:{blockers.join('、')}</p>}
{step.error && <p className="plan-problem">{step.error}</p>}
{step.last_rejection && <details className="plan-rejection"><summary>最近一次核验未通过</summary><p>{step.last_rejection.message}</p></details>}
<details className="plan-evidence" open={['ready', 'stale', 'unverified'].includes(step.status)}><summary>{step.status === 'verified' ? '查看核验依据' : '选择实际结果'}</summary>
<label>原执行结果<select aria-label={`步骤${index + 1}原证据`} value={evidenceId} disabled={disabled} onChange={event => setPicked(values => ({ ...values, [step.key]: event.target.value }))}>
<option value="">选择此任务的实际结果</option>{step.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}
</select></label>
<button type="button" className="button secondary" disabled={disabled || !evidenceId || !!blockers.length || view.requirements_current === false} onClick={() => void verify(step.key, evidenceId)}><Check size={13} />核验此步骤</button>
{step.proof_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(step.proof_artifact_id!)}><FileText size={13} />查看原核验记录</button>}
{step.evidence?.artifacts?.map(artifact => <button type="button" className="text-button" key={artifact.id} onClick={() => openArtifact(artifact.id)}><FileText size={13} />原依据 · {artifact.sha256.slice(0, 8)}</button>)}
</details>
</div>
</li>;
})}</ol>
{view.contract_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(view.contract_artifact_id!)}><FileText size={13} />查看原计划</button>}
<p className="record-footnote">核验依据为实际操作和当前文件;业务含义仍需独立验收。</p>
</>}
{editor && <Modal title="编辑执行计划" description="固定步骤、前置依赖和通过条件。保存计划不会运行工具。" wide onClose={() => { if (!mutating) setEditor(false); }}>
<form onSubmit={event => { event.preventDefault(); void save(); }} className="plan-editor">
<div className="plan-editor-scroll">{draft.map((step, index) => <fieldset className="plan-editor-step" key={step.key} disabled={mutating || index < fixed}>
<legend>步骤 {index + 1}{index < fixed ? ' · 已封存' : ''}</legend>
<label>步骤名称<input aria-label={`步骤${index + 1}名称`} value={step.title} maxLength={100} required onChange={event => update(index, { title: event.target.value })} /></label>
<label>通过条件<textarea aria-label={`步骤${index + 1}通过条件`} value={step.criterion} maxLength={300} required rows={2} placeholder="说明这一步完成后应该得到什么实际结果" onChange={event => update(index, { criterion: event.target.value })} /></label>
<label>结果类别<select aria-label={`步骤${index + 1}类别`} value={step.kind} onChange={event => {
const next = freshStep(event.target.value as TaskPlanStep['kind']); setDraft(steps => steps.map((value, at) => at === index ? { ...next, key: value.key, title: value.title, criterion: value.criterion, depends_on: value.depends_on } : value));
}}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
{step.kind === 'analysis' && <div className="plan-option-list"><span>可核验的读取结果(任一)</span>{Object.entries(readTools).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.tools?.includes(key) ?? false} onChange={event => update(index, { tools: event.target.checked ? [...(step.tools ?? []), key] : step.tools?.filter(tool => tool !== key) })} />{label}</label>)}</div>}
{step.kind === 'changes' && <label>改动文件(每行一项)<textarea aria-label={`步骤${index + 1}文件范围`} rows={3} value={step.paths?.join('\n') ?? ''} placeholder="src/main.tsx" onChange={event => update(index, { paths: event.target.value.split('\n') })} /></label>}
{step.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label={`步骤${index + 1}检查范围`} value={step.checks?.join(',') ?? ''} placeholder="test,build 或 python:test,python:compile" onChange={event => update(index, { checks: event.target.value.split(',') })} /></label>}
{step.kind === 'browser' && <><label>页面宽度<select aria-label={`步骤${index + 1}页面宽度`} value={step.viewport_width} onChange={event => update(index, { viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option>{![1280, 390].includes(step.viewport_width ?? 0) && <option value={step.viewport_width}>{step.viewport_width}px</option>}</select></label>
<div className="plan-option-list"><span>必须实际完成的操作</span>{Object.entries(browserActions).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.actions?.includes(key) ?? false} onChange={event => update(index, { actions: event.target.checked ? [...(step.actions ?? []), key] : step.actions?.filter(action => action !== key) })} />{label}</label>)}</div></>}
{index > 0 && <div className="plan-option-list"><span>前置步骤</span>{draft.slice(0, index).map(previous => <label key={previous.key}><input type="checkbox" checked={step.depends_on.includes(previous.key)} onChange={event => update(index, { depends_on: event.target.checked ? [...step.depends_on, previous.key] : step.depends_on.filter(key => key !== previous.key) })} />{previous.title}</label>)}</div>}
{index >= fixed && draft.length > Math.max(1, fixed) && <button type="button" className="text-button" onClick={() => setDraft(steps => steps.filter(value => value.key !== step.key).map(value => ({ ...value, depends_on: value.depends_on.filter(key => key !== step.key) })))}>移除此新步骤</button>}
</fieldset>)}
<button type="button" className="button secondary" disabled={mutating || draft.length >= 12} onClick={() => setDraft(steps => [...steps, freshStep()])}><Plus size={14} />追加步骤</button>
{fixed > 0 && <p className="record-footnote">原步骤和通过条件已封存,新增要求以追加步骤保留。</p>}
</div>
<div className="modal-actions"><button type="button" className="button secondary" disabled={mutating} onClick={() => setEditor(false)}>取消</button><button type="submit" className="button primary" disabled={mutating || draft.length > 12}>{mutating ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}保存执行计划</button></div>
</form>
</Modal>}
</section>;
}
+1
View File
@@ -13,6 +13,7 @@ const statusNames: Record<string, string> = {
not_configured: '尚未检查', passed: '检查通过', cancelled: '已取消', stale: '需重新检查',
planned: '待确认', preparing: '准备提交', prepared: '准备完成', publishing: '发布本地提交', committed: '已生成提交',
reporting: '生成报告',
ready: '可核验', blocked: '等待前置', verified: '已核验', incomplete: '尚未完成', needs_update: '要求已更新', not_planned: '尚未规划',
snapshotting: '封存构建', launching: '启动浏览器', closing: '关闭浏览器', observed: '页面已观察',
applying: '应用中', rolling_back: '回退中', rolled_back: '已回退', partial: '部分结果待核对',
resolved_external: '已保留外部修改', external_preserved: '外部内容已保留',
+18 -1
View File
@@ -130,7 +130,24 @@ export interface ChangeSet {
snapshotArtifactId: string; sourceRunId: string; restoreError?: string }[];
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: string }[];
}
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface TaskPlanStep {
key: string; title: string; criterion: string; kind: 'analysis' | 'changes' | 'checks' | 'browser'; depends_on: string[];
tools?: string[]; paths?: string[]; checks?: string[]; viewport_width?: number; actions?: string[];
}
export interface TaskPlanRecord { id: string; taskId: string; runId: string; revision: number; parentPlanId: string | null; steps: TaskPlanStep[]; contractArtifactId: string; contractSha256: string }
export interface TaskPlanStepView extends TaskPlanStep {
status: string; blockers: string[]; evidence_verified: boolean; proof_id: string | null; proof_artifact_id: string | null; error: string | null;
evidence: { id: string; runId: string; artifacts?: { id: string; kind: string; sha256: string }[] } | null;
last_rejection?: { id: string; message: string; at: string };
candidates?: { id: string; status: string; label: string; runId: string }[];
}
export interface TaskPlanView {
configured: boolean; task_id: string; plan_id?: string; revision: number; status: string; steps: TaskPlanStepView[]; all_verified: boolean;
verified_steps?: number; total_steps?: number; ready_steps?: string[]; remaining_steps?: string[]; requirements_current?: boolean;
contract_artifact_id?: string; contract_sha256?: string; checked_at?: string; error?: string;
}
export interface TaskPlanReply { session: Session; plan: TaskPlanView; verification?: { status: string; reused?: boolean; proof_id: string; message?: string } }
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface EngineAvailability {
engineId: string; name: string; status: string; root: string | null; profile: string; expectedVersion: string; version?: string; message: string;
identitySha256?: string; node?: { path: string; version: string; sha256: string };
+21 -1
View File
@@ -73,9 +73,29 @@ async function observe(page) {
return page.evaluate(({ textLimit }) => {
const body = document.body, text = body?.innerText ?? '';
const controls = [...document.querySelectorAll('button,input,select,textarea,a,[role="button"],[data-testid]')];
const uniqueSelector = node => {
const unique = selector => {
if (!selector || selector.length > 300) return false;
try { const matches = document.querySelectorAll(selector); return matches.length === 1 && matches[0] === node; } catch { return false; }
};
const candidates = node.id ? ['#' + CSS.escape(node.id)] : [];
for (const attribute of ['data-testid', 'aria-label', 'name']) {
const value = node.getAttribute(attribute);
if (value) candidates.push(node.tagName.toLowerCase() + '[' + attribute + '="' + CSS.escape(value) + '"]');
}
for (const selector of candidates) if (unique(selector)) return { selector, selectorMatches: 1, selectorEvidence: 'observed-dom-query' };
let current = node, parts = [];
for (let depth = 0; current?.parentElement && depth < 12; depth++, current = current.parentElement) {
const siblings = [...current.parentElement.children].filter(value => value.tagName === current.tagName);
parts.unshift(current.tagName.toLowerCase() + ':nth-of-type(' + (siblings.indexOf(current) + 1) + ')');
const selector = parts.join(' > ');
if (unique(selector)) return { selector, selectorMatches: 1, selectorEvidence: 'observed-dom-query' };
}
return { selector: null, selectorMatches: null, selectorEvidence: 'unavailable' };
};
return { url: location.href, title: document.title.slice(0, 300), text: text.slice(0, textLimit), textCharacters: text.length,
textTruncated: text.length > textLimit, viewport: { width: innerWidth, height: innerHeight, scrollWidth: body?.scrollWidth ?? 0 },
controls: controls.slice(0, 80).map(node => ({ tag: node.tagName.toLowerCase(), id: node.id?.slice(0, 200) ?? '',
controls: controls.slice(0, 80).map(node => ({ ...uniqueSelector(node), tag: node.tagName.toLowerCase(), id: node.id?.slice(0, 200) ?? '',
role: node.getAttribute('role'), label: node.getAttribute('aria-label')?.slice(0, 300) ?? '',
text: (node.innerText ?? '').slice(0, 300), type: node.getAttribute('type'), testId: node.getAttribute('data-testid'),
value: typeof node.value === 'string' ? node.value.slice(0, 1000) : null, disabled: !!node.disabled,
+15 -1
View File
@@ -1,6 +1,9 @@
import { createHash } from 'node:crypto';
const messageBytes = (result, callId) => Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: callId, content: JSON.stringify(result) }), 'utf8');
export const BROWSER_READ_HINT = '当前Run已经返回此页面结果区间,请使用已返回的实际字段或按next_offset读取新段;页面失败后准备修正的新计划。';
export const readMetadataReserve = metadata => Object.keys(metadata).length
? Buffer.byteLength(JSON.stringify(JSON.stringify(metadata)), 'utf8') + 8 : 0;
const boundary = (text, end) => end > 0 && end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) ? end - 1 : end;
// This is the actual tool page, not a rewrite of a historical result. Count
@@ -63,7 +66,7 @@ export function filePage(file, args, { maximumMessageBytes = 16000, callId = ''
export function recordArtifactRead(task, artifact, result, invocationId, runId = task.activeRunId ?? null) {
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0, changingIndexes: [], warning: null, pause: false };
progress.sessionInspection = null;
const identity = artifact.id + ':' + artifact.sha256, start = result.offset, end = result.next_offset;
const identity = artifact.id + ':' + (artifact.section ? artifact.section + ':' : '') + artifact.sha256, start = result.offset, end = result.next_offset;
let read = progress.reads.find(value => value.identity === identity);
if (!read) { read = { identity, ranges: [] }; progress.reads.push(read); if (progress.reads.length > 128) progress.reads.shift(); }
// Historical coverage is an audit of returned pages, not proof that a new
@@ -99,6 +102,14 @@ export function clearReadStreak(task) {
task.readProgress.sessionInspection = null;
}
export function recordBrowserRead(task, result, invocationId, runId = task.activeRunId ?? null) {
const progress = recordArtifactRead(task, { id: result.source_artifact_id, sha256: result.view_sha256, kind: 'browser-result-view', section: result.section }, result, invocationId, runId);
progress.last.section = result.section; progress.last.sourceSha256 = result.source_sha256;
result.repeated_read_count = progress.repeated;
if (progress.warning) result.reading_hint = BROWSER_READ_HINT;
return progress;
}
export function recordSessionInspection(task, result) {
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0, changingIndexes: [], warning: null, pause: false };
const execution = result.execution ?? {};
@@ -107,6 +118,9 @@ export function recordSessionInspection(task, result) {
const state = { sessionId: result.session?.id, status: result.session?.status,
lastFailure: result.lastFailure, changes: result.changes, approvals: result.pendingApprovals,
verification: execution.task?.verification,
taskPlanId: execution.task?.currentTaskPlanId,
taskProofs: execution.taskProofs?.map(proof => ({ id: proof.id, planId: proof.planId, stepKey: proof.stepKey, status: proof.status })),
browserJobs: execution.browserJobs?.map(job => ({ id: job.id, planId: job.planId, status: job.status, resultSha256: job.resultSha256, assertions: job.assertions })),
needsVerification: execution.progress?.requiresVerification,
checks: execution.checks?.map(job => ({ id: job.id, status: job.status, stale: job.stale,
results: job.results.map(check => ({ name: check.name, status: check.status, exitCode: check.exitCode, tests: check.tests })) })),
+3 -2
View File
@@ -31,11 +31,12 @@ export function compactToolFeedback(content) {
'task_id', 'taskId', 'runId', 'plan_id', 'job_id', 'change_id', 'change_set_id', 'artifact_id', 'report_status', 'check_status',
'path', 'sha256', 'base_sha256', 'fingerprint', 'exit_code', 'exitCode', 'offset', 'next_offset', 'total_characters',
'returned_characters', 'truncated', 'totalMatches', 'error', 'message', 'summary', 'reason', 'note',
'browser_status', 'browser_job_id', 'result_artifact_id', 'evidence_verified', 'source_fingerprint', 'build_sha256', 'section', 'view_sha256', 'source_artifact_id', 'source_sha256']);
'browser_status', 'browser_job_id', 'result_artifact_id', 'evidence_verified', 'source_fingerprint', 'build_sha256', 'section', 'view_sha256', 'source_artifact_id', 'source_sha256',
'tool_invocation_id', 'proof_id', 'proof_artifact_id', 'step_key', 'revision', 'all_verified', 'verified_steps', 'total_steps', 'requirements_current', 'contract_artifact_id', 'binding_sha256']);
if (value.assertions) result.assertions = stats(value.assertions);
if (Array.isArray(value.failed_steps)) result.failed_steps = value.failed_steps.slice(0, 3).map(step => fields(step, ['index', 'action', 'selector', 'status', 'error', 'actual']));
if (value.observed_page) result.observed_page = { ...fields(value.observed_page, ['title']), text: excerpt(value.observed_page.text ?? ''),
controls: (value.observed_page.controls ?? []).slice(0, 3).map(control => fields(control, ['tag', 'id', 'label', 'text', 'value', 'disabled'])) };
controls: (value.observed_page.controls ?? []).slice(0, 3).map(control => fields(control, ['tag', 'id', 'label', 'text', 'value', 'disabled', 'selector', 'selectorMatches', 'selectorEvidence'])) };
for (const key of ['content', 'stdout', 'stderr']) if (typeof value[key] === 'string') result[key + '_excerpt'] = excerpt(value[key]);
for (const key of ['session', 'project']) if (value[key]) result[key] = fields(value[key], ['id', 'name', 'root', 'status', 'revision']);
if ('lastFailure' in value) result.lastFailure = value.lastFailure === null ? null : fields(value.lastFailure, ['source', 'stage', 'kind', 'title', 'message', 'runId']);
+25 -2
View File
@@ -6,9 +6,10 @@ import { projectWorkspaceIdentity, unresolvedWorkspaces } from '../shared/contra
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { verifyPythonCheckEvidence } from './python-runtime.mjs';
import { currentBrowserVerification, verifyBrowserJob } from './browser/browser-manager.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
export function verifiedCheck(store, session, inspection) {
@@ -92,6 +93,16 @@ export class DeliveryReporter {
requiresVerification.push(...contextPlans.filter(plan => !plan.evidenceVerified).map(plan => ({ id: plan.id, tool: 'model_context', status: 'evidence_unverified' })));
const deliveryReview = pendingDeliveryReview(this.store, session);
const browserVerification = await currentBrowserVerification(this.store, session, inspection);
const planner = new TaskPlanManager(this.store), taskPlan = await planner.inspect(session, { inspection, candidates: false });
const taskPlanHistory = [...this.store.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
try { planner.planFor(session, value.id); evidenceVerified = true; } catch (error) { evidenceError = error.message; }
return { id: value.id, runId: value.runId, revision: value.revision, parentPlanId: value.parentPlanId, steps: value.steps,
requirementsSha256: value.requirementsSha256, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256, evidenceVerified, evidenceError };
});
const taskProofs = [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ id: value.id, runId: value.runId, planId: value.planId, stepKey: value.stepKey, status: value.status, evidenceId: value.evidenceId,
outcome: value.outcome, error: value.error, createdAt: value.createdAt, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256 }));
const browserChecks = [...this.store.core.browser_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
if (value.resultArtifactId) { try { verifyBrowserJob(this.store, session, value); evidenceVerified = true; } catch (error) { evidenceError = error.message; } }
@@ -105,7 +116,7 @@ export class DeliveryReporter {
const status = requiresVerification.length || unresolved.length ? 'needs_verification'
: ['running', 'awaiting_approval', 'stopping'].includes(session.status) ? 'in_progress'
: deliveryReview || changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review'
: !check ? 'needs_checks' : browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: taskPlan.configured && !taskPlan.all_verified ? 'needs_plan_verification' : !check ? 'needs_checks' : browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: commits.length ? 'verified_committed' : 'verified_uncommitted';
const report = {
schemaVersion: 1, kind: 'engineering-delivery', generatedAt: new Date().toISOString(), status, statusLabel: labels[status],
@@ -123,6 +134,7 @@ export class DeliveryReporter {
...(deliveryReview ? { deliveryReview: { planId: deliveryReview.id, status: 'pending', paths: deliveryReview.paths } } : {}),
contextPlans,
browserVerification, browserChecks,
taskPlan, taskPlanHistory, taskProofs,
checks: checkJobs.map(value => ({ id: value.id, status: value.status, planId: value.planId,
contractArtifactId: this.store.core.check_plan.get(value.planId)?.contractArtifactId ?? null,
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
@@ -156,6 +168,17 @@ export function renderDeliveryMarkdown(report) {
'分支:' + (report.source.branch ?? '未记录'), '', report.task.note, '', '## 改动', '',
'| 文件 | 状态 | SHA256 |', '| --- | --- | --- |'];
for (const change of report.changes) lines.push('| ' + [change.path, change.status, change.sha256].map(escapeCell).join(' | ') + ' |');
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
'| 步骤 / 通过条件 | 状态 | 前置依赖 | 原证据 |', '| --- | --- | --- | --- |');
for (const step of report.taskPlan.steps) lines.push('| ' + [step.title + ' / ' + step.criterion, step.status,
step.depends_on.join(', ') || '无', step.evidence?.id ?? '尚未核验'].map(escapeCell).join(' | ') + ' |', ...(step.error ? ['', step.error, ''] : []));
if (report.taskPlan.error) lines.push('', report.taskPlan.error);
lines.push('', '任务计划固定实际操作范围;业务语义验收另行记录。', '', '### 原计划与核验工件', '');
for (const plan of report.taskPlanHistory ?? []) lines.push('计划 ' + plan.revision + ':' + plan.contractArtifactId + ' · SHA256 ' + plan.contractSha256);
for (const proof of report.taskProofs ?? []) lines.push('步骤 ' + proof.stepKey + ' · ' + proof.status + ':' + proof.contractArtifactId + ' · SHA256 ' + proof.contractSha256);
}
if (report.workspace?.kind === 'managed-worktree') lines.push('', '## 独立开发工作区', '', '工作区:' + report.workspace.workspaceId,
'来源项目:' + report.workspace.sourceProjectId, '来源目录:' + report.workspace.sourceRoot,
'起始提交:' + report.workspace.baseCommit, '独立分支:' + report.workspace.branch,
+5
View File
@@ -13,6 +13,7 @@ import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { currentBrowserVerification } from './browser/browser-manager.mjs';
import { assertBrowserResolved } from '../shared/contracts/browser.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
const at = () => new Date().toISOString();
const sha = value => createHash('sha256').update(value).digest('hex');
@@ -220,6 +221,7 @@ export class GitDelivery {
assertBrowserResolved(this.store, session.projectId);
const browser = await currentBrowserVerification(this.store, session, inspection);
if (browser.required && browser.status !== 'passed') throw conflict('本任务已配置页面验收,请先取得当前源码与构建的实际浏览器断言通过记录。');
const taskPlan = await new TaskPlanManager(this.store).assertReady(session, { inspection });
const files = await this.selectedFiles(session, project, snapshot);
const name = options.authorName ?? snapshot.config['user.name'] ?? 'Agent Workbench';
const email = options.authorEmail ?? snapshot.config['user.email'] ?? 'local@agent-workbench.invalid';
@@ -228,11 +230,13 @@ export class GitDelivery {
const second = await this.snapshot(project);
if (snapshot.digest !== second.digest || identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('准备提交期间工程或任务已变化,请重新预览。');
this.assertIdle(session, idleOptions); this.assertTask(session);
await new TaskPlanManager(this.store).assertReady(session, { expectedBinding: taskPlan.binding_sha256 });
const diffArtifact = this.store.artifactStore.write(session, run, files.map(file => file.diff).join('\n'), { kind: 'delivery-diff', mediaType: 'text/plain' });
this.store.core.artifact.set(diffArtifact.id, diffArtifact);
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id, status: 'planned', createdAt: at(),
message, author, files, paths: files.map(file => file.path), snapshot, preparedBy: source, fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint,
checkJobId: check.id, checkSummary: check.results.map(value => ({ name: value.name, command: value.command, exitCode: value.exitCode, tests: value.tests, logArtifactId: value.logArtifactId })),
...(taskPlan.configured ? { taskPlanId: taskPlan.plan_id, taskPlanRevision: taskPlan.revision, taskPlanBindingSha256: taskPlan.binding_sha256 } : {}),
...(browser.required ? { browserJobId: browser.jobId, browserPlanId: browser.planId, browserBuildSha256: browser.buildSha256 } : {}),
protectedIndexSha256: protectedIndex(snapshot.stage, snapshot.flags, files.map(file => file.path)), diffArtifactId: diffArtifact.id,
policy: { name: 'local-reviewed-snapshot', hooks: 'disabled', signing: 'unsigned', remote: 'none',
@@ -285,6 +289,7 @@ export class GitDelivery {
}
async verifyBrowserDelivery(session, plan, inspection) {
await new TaskPlanManager(this.store).assertReady(session, { inspection, expectedBinding: plan.taskPlanBindingSha256 ?? null });
assertBrowserResolved(this.store, session.projectId);
const browser = await currentBrowserVerification(this.store, session, inspection);
if (browser.required && (browser.status !== 'passed' || browser.jobId !== plan.browserJobId || browser.buildSha256 !== plan.browserBuildSha256)
+225
View File
@@ -0,0 +1,225 @@
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { safePath } from '../../server/files.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { ChangeSetManager } from '../workspaces/change-sets.mjs';
import { CheckRunner, parseTestEvidence } from '../check-runner.mjs';
import { verifyPythonCheckEvidence } from '../python-runtime.mjs';
import { browserPlanFor, verifyBrowserJob } from '../browser/browser-manager.mjs';
import { inspectBuild } from '../browser/build-snapshot.mjs';
import { TASK_PLAN_LIMITS, taskPlanInput, taskProofInput, taskRequirements, taskPlanContract, taskProofContract, planHash, planError } from '../../shared/contracts/task-plans.mjs';
const at = () => new Date().toISOString();
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const identity = artifact => ({ id: artifact.id, kind: artifact.kind, runId: artifact.runId, sha256: artifact.sha256, bytes: artifact.bytes });
export class TaskPlanManager {
constructor(store, { redact = String, projectBusy = () => false } = {}) { this.store = store; this.redact = redact; this.projectBusy = projectBusy; this.active = new Map(); }
projectActive(projectId) { return [...this.active.values()].some(value => value.projectId === projectId); }
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
async settle(sessionId = null) { await Promise.allSettled([...this.active.values()].filter(value => !sessionId || value.sessionId === sessionId).map(value => value.promise)); }
async mutate(session, source, action) {
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw planError('项目正在执行操作,请结束后保存或核验计划。');
const id = randomUUID(), operation = { sessionId: session.id, projectId: session.projectId, promise: null };
this.active.set(id, operation);
try { operation.promise = Promise.resolve().then(action); return await operation.promise; }
finally { this.active.delete(id); }
}
task(session) {
const task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
if (run.taskId !== task.id) throw planError('计划的Task/Run归属已经变化。');
return { task, run };
}
artifact(session, id, kind, taskId = session.taskId, runId = null) {
const artifact = this.store.owned('artifact', id, session.id);
if (artifact.taskId !== taskId || kind && artifact.kind !== kind || runId && artifact.runId !== runId) throw planError('计划证据工件不属于原Task/Run或实际类别。');
const run = this.store.owned('run', artifact.runId, session.id);
if (run.taskId !== taskId) throw planError('证据工件的所属运行无效。');
return { artifact, text: this.store.artifactStore.read(artifact) };
}
current(session) {
const task = this.store.core.task.get(session.taskId);
return task?.currentTaskPlanId ? this.store.owned('task_plan', task.currentTaskPlanId, session.id) : null;
}
planFor(session, id) {
const plan = this.store.owned('task_plan', id, session.id);
if (plan.taskId !== session.taskId) throw planError('计划属于此前Task,不能用于当前任务。');
const { artifact, text } = this.artifact(session, plan.contractArtifactId, 'task-plan', plan.taskId, plan.runId);
if (artifact.sha256 !== plan.contractSha256 || text !== JSON.stringify(taskPlanContract(plan))
|| plan.requirementsSha256 !== planHash(plan.requirements)) throw planError('任务计划与封存的目标、步骤或依赖不一致。');
taskPlanInput({ expected_revision: plan.revision, steps: plan.steps });
return plan;
}
assertUnchanged(session, plan, taskId, runId, requirementsSha256) {
if (session.taskId !== taskId || session.runId !== runId || this.current(session)?.id !== plan.id
|| planHash(taskRequirements(this.store.core.task.get(taskId))) !== requirementsSha256) throw planError('核对期间原任务、运行、目标或计划已变化,请刷新当前计划。', 'stale');
}
plan(session, options, { source = 'user' } = {}) { return this.mutate(session, source, () => this.planAction(session, options)); }
async planAction(session, options) {
const input = taskPlanInput(JSON.parse(this.redact(JSON.stringify(options)))), { task, run } = this.task(session);
const requirements = taskRequirements(task), requirementsSha256 = planHash(requirements), previous = this.current(session);
if (previous) this.planFor(session, previous.id);
const revision = previous?.revision ?? 0;
if (previous && same(previous.steps, input.steps) && previous.requirementsSha256 === requirementsSha256
&& [revision, revision - 1].includes(input.expected_revision)) return previous;
if (task.status === 'completed') throw planError('已完成任务保留原计划,请为新增工作发送新任务。');
if (input.expected_revision !== revision) throw planError('计划视图已过期,请按当前revision保存。', 'stale');
if (revision >= TASK_PLAN_LIMITS.revisions) throw planError('任务计划已到修订上限,请缩小任务后继续。');
if (previous && (input.steps.length < previous.steps.length || previous.steps.some((step, index) => !same(step, input.steps[index])))) throw planError('已有步骤和通过条件不能删改;请保留原步骤并追加。');
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
for (const step of input.steps) for (const file of step.paths ?? []) safePath(this.store.project(session.projectId), file, true);
if (session.taskId !== task.id || session.runId !== run.id || this.current(session)?.id !== previous?.id
|| planHash(taskRequirements(task)) !== requirementsSha256) throw planError('保存期间任务或计划已变化,请刷新后保存。', 'stale');
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
revision: revision + 1, parentPlanId: previous?.id ?? null, status: 'planned', createdAt: at(), requirements, requirementsSha256, steps: input.steps };
const artifact = this.store.artifactStore.write(session, run, taskPlanContract(plan), { kind: 'task-plan' });
plan.contractArtifactId = artifact.id; plan.contractSha256 = artifact.sha256;
this.store.core.artifact.set(artifact.id, artifact); task.currentTaskPlanId = plan.id;
return this.store.putRecord('task_plan', session, plan, 'task.plan_saved');
}
async inspection(session, cache) {
cache.inspection ??= inspectProject(this.store.project(session.projectId));
const inspection = await cache.inspection;
if (!inspection.scope.complete) throw planError('当前工程范围不完整,不能核验源码相关步骤。', 'stale');
return inspection;
}
async evidence(session, step, id, cache = {}) {
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
const record = this.store.owned(kind, id, session.id);
if (record.taskId !== session.taskId || record.requiresVerification) throw planError('原证据不属于当前Task或结果仍待核对。');
const run = this.store.owned('run', record.runId, session.id);
if (run.taskId !== session.taskId) throw planError('证据运行不属于当前任务。');
if (step.kind === 'analysis') {
if (record.state !== 'completed' || !step.tools.includes(record.tool) || !record.resultArtifactId) throw planError('读取步骤需要已完成的所选只读工具原结果。');
const { artifact, text } = this.artifact(session, record.resultArtifactId, 'tool-result', record.taskId, record.runId);
const result = JSON.parse(text);
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(value => value.id === record.callId);
if (!call || call.function.name !== record.tool || planHash(call.function.arguments) !== record.argsSha256) throw planError('原读取调用与参数哈希不一致。');
if (['failed', 'error', 'denied', 'unknown', 'interrupted'].includes(result.status)) throw planError('原读取结果失败或未知,不能作为已完成证据。');
return { kind, id: record.id, runId: record.runId, scope: 'historical_read_operation', tool: record.tool, callId: record.callId,
argsSha256: record.argsSha256, artifacts: [identity(artifact)] };
}
if (step.kind === 'changes') {
if (record.status !== 'completed' || record.direction !== 'apply' || !record.attemptedAt
|| !step.paths.every(file => record.files.some(value => value.path === file && value.writeAttempted && value.state === 'after'))) throw planError('步骤文件必须来自本Task已审查应用的完整变更集。');
new ChangeSetManager(this.store).snapshots(session, record);
const files = step.paths.map(file => record.files.find(value => value.path === file));
for (const file of files) if (planHash(fs.readFileSync(safePath(this.store.project(session.projectId), file.path))) !== file.sha256) throw planError('已应用的目标文件已变化,需要核对新的实际改动。', 'stale');
return { kind, id: record.id, runId: record.runId, scope: 'current_applied_files', fingerprint: record.fingerprint,
files: files.map(file => ({ path: file.path, sha256: file.sha256, changeId: file.changeId })) };
}
const inspection = await this.inspection(session, cache);
if (record.sourceFingerprint !== inspection.sourceFingerprint) throw planError('原证据对应旧源码,请使用当前工程的实际结果。', 'stale');
if (step.kind === 'checks') {
const task = this.store.core.task.get(session.taskId);
if (record.status !== 'passed' || record.stale || task.verification.status !== 'passed' || task.verification.checkJobId !== record.id
|| !step.checks.every(name => record.results.some(result => result.name === name))) throw planError('检查步骤需要最新所属检查通过且覆盖全部所选名称。', 'stale');
const plan = new CheckRunner(this.store).planFor(session, record.planId), artifacts = [];
if (!plan.contractArtifactId || plan.sourceFingerprint !== record.sourceFingerprint) throw planError('检查缺少当前源码的封存执行范围。');
artifacts.push(identity(this.artifact(session, plan.contractArtifactId, 'check-plan', record.taskId, plan.runId).artifact));
for (const result of record.results) {
if (result.status !== 'passed' || result.exitCode !== 0 || !result.logArtifactId || result.kind === 'test'
&& (!result.tests?.total || result.tests.passed !== result.tests.total || result.tests.failed || result.tests.skipped || result.tests.cancelled)) throw planError('检查通过状态缺少退出码、真实测试数量或原日志。');
const log = this.artifact(session, result.logArtifactId, 'check-log', record.taskId, record.runId);
artifacts.push(identity(log.artifact));
if (result.kind === 'test' && result.engine !== 'python') {
const counted = parseTestEvidence(log.text, result.framework ?? plan.checks.find(check => check.name === result.name)?.framework);
if (!same(counted, result.tests)) throw planError('检查数量与原日志中的实际统计不一致。');
}
verifyPythonCheckEvidence(this.store, session, record, result);
for (const field of ['metricsArtifactId', 'inputArtifactId']) if (result[field]) artifacts.push(identity(this.artifact(session, result[field], null, record.taskId, record.runId).artifact));
}
return { kind, id: record.id, runId: record.runId, scope: 'current_source_checks', sourceFingerprint: record.sourceFingerprint,
checks: record.results.map(result => ({ name: result.name, exitCode: result.exitCode, tests: result.tests ?? null, compilation: result.compilation ?? null })), artifacts };
}
const plan = browserPlanFor(this.store, session, record.planId), original = verifyBrowserJob(this.store, session, record);
const latest = [...this.store.core.browser_plan.values()].findLast(value => value.sessionId === session.id && value.taskId === session.taskId && value.viewport.width === step.viewport_width);
if (record.status !== 'passed' || original.status !== 'passed' || !original.cleanup?.exited || !original.assertions?.total
|| original.assertions.passed !== original.assertions.total || latest?.id !== plan.id || plan.viewport.width !== step.viewport_width
|| step.actions.some(action => !original.steps.some(value => value.action === action && value.status === 'passed'))) throw planError('页面步骤需要所选视口最新计划的实际操作、断言通过及进程结束。', 'stale');
const build = await inspectBuild(this.store.project(session.projectId), plan.build.directory);
if (build.sha256 !== record.buildSha256) throw planError('页面构建已变化,请使用当前构建的实际浏览器结果。', 'stale');
return { kind, id: record.id, runId: record.runId, scope: 'current_build_browser', sourceFingerprint: record.sourceFingerprint,
buildSha256: record.buildSha256, viewport: plan.viewport, assertions: original.assertions, actions: step.actions,
artifacts: [identity(this.artifact(session, record.resultArtifactId, 'browser-result', record.taskId, record.runId).artifact)],
screenshots: record.screenshots.map(image => ({ artifactId: image.artifactId, sha256: image.sha256 })) };
}
proofs(session, plan) { return [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && value.planId === plan.id); }
candidates(session, step) {
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
return [...this.store.core[kind].values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId)
.filter(value => step.kind !== 'analysis' || step.tools.includes(value.tool)).filter(value => step.kind !== 'browser' || this.store.core.browser_plan.get(value.planId)?.viewport.width === step.viewport_width)
.slice(-12).reverse().map(value => ({ id: value.id, status: value.stale ? 'stale' : value.status ?? value.state,
label: step.kind === 'analysis' ? value.tool : step.kind === 'changes' ? value.files.map(file => file.path).join('、')
: step.kind === 'checks' ? value.results.map(result => result.name).join(' / ') : step.viewport_width + 'px · ' + (value.assertions?.passed ?? 0) + '项断言',
runId: value.runId }));
}
async inspect(session, { inspection = null, candidates = true } = {}) {
const plan = this.current(session);
if (!plan) return { configured: false, task_id: session.taskId, revision: 0, status: 'not_planned', steps: [], all_verified: false, binding_sha256: null };
try { this.planFor(session, plan.id); }
catch (error) { return { configured: true, plan_id: plan.id, revision: plan.revision, status: 'unverified', error: this.redact(error.message), steps: [], all_verified: false, binding_sha256: null }; }
const requirementsCurrent = plan.requirementsSha256 === planHash(taskRequirements(this.store.core.task.get(session.taskId)));
const proofs = this.proofs(session, plan), states = new Map(), cache = { inspection };
const evaluate = async key => {
if (states.has(key)) return states.get(key);
const step = plan.steps.find(value => value.key === key), dependencies = await Promise.all(step.depends_on.map(evaluate));
const proof = proofs.findLast(value => value.stepKey === key && value.status === 'verified'), attempt = proofs.findLast(value => value.stepKey === key);
let valid = false, error = null, evidence = null, code = null;
if (proof) try {
const stored = this.artifact(session, proof.contractArtifactId, 'task-proof', proof.taskId, proof.runId);
if (stored.artifact.sha256 !== proof.contractSha256 || stored.text !== JSON.stringify(taskProofContract(proof))
|| proof.planContractSha256 !== plan.contractSha256 || proof.requirementsSha256 !== plan.requirementsSha256 || proof.stepSha256 !== planHash(step)) throw planError('步骤证明与原计划、目标或工件不一致。');
evidence = await this.evidence(session, step, proof.evidenceId, cache);
if (!same(evidence, proof.outcome)) throw planError('原证明引用的执行记录或文件已经变化。', 'stale');
valid = true;
} catch (caught) { error = this.redact(caught.message); code = caught.code ?? 'invalid'; }
const blockers = dependencies.filter(value => value.status !== 'verified').map(value => value.key);
const status = !requirementsCurrent ? 'needs_update' : error ? code === 'stale' ? 'stale' : 'unverified' : blockers.length ? 'blocked' : valid ? 'verified' : 'ready';
const state = { ...step, status, blockers, evidence_verified: valid, proof_id: proof?.id ?? null, proof_artifact_id: proof?.contractArtifactId ?? null,
evidence, error, ...(attempt?.status === 'rejected' ? { last_rejection: { id: attempt.id, message: attempt.error, at: attempt.createdAt } } : {}),
...(candidates ? { candidates: this.candidates(session, step) } : {}) };
states.set(key, state); return state;
};
for (const step of plan.steps) await evaluate(step.key);
const steps = plan.steps.map(step => states.get(step.key)), allVerified = requirementsCurrent && steps.every(step => step.status === 'verified');
return { configured: true, task_id: plan.taskId, plan_id: plan.id, revision: plan.revision, status: !requirementsCurrent ? 'needs_update' : allVerified ? 'verified' : 'incomplete',
requirements_current: requirementsCurrent, requirements_sha256: plan.requirementsSha256, contract_artifact_id: plan.contractArtifactId, contract_sha256: plan.contractSha256,
steps, verified_steps: steps.filter(step => step.status === 'verified').length, total_steps: steps.length, all_verified: allVerified,
ready_steps: steps.filter(step => step.status === 'ready').map(step => step.key), remaining_steps: steps.filter(step => step.status !== 'verified').map(step => step.key),
binding_sha256: allVerified ? planHash({ planId: plan.id, contractSha256: plan.contractSha256, proofs: steps.map(step => ({ key: step.key, id: step.proof_id, evidence: step.evidence })) }) : null,
checked_at: at(), note: '步骤核验绑定实际操作和当前证据;原用户要求与业务语义的完整验收另行记录。' };
}
verify(session, options, { source = 'user' } = {}) { return this.mutate(session, source, () => this.verifyAction(session, options)); }
async verifyAction(session, options) {
const input = taskProofInput(options), { task, run } = this.task(session), plan = this.planFor(session, input.plan_id);
if (this.current(session)?.id !== plan.id || plan.revision !== input.expected_revision || plan.requirementsSha256 !== planHash(taskRequirements(task))) throw planError('原计划视图或任务目标已变化,请刷新当前计划。', 'stale');
const step = plan.steps.find(value => value.key === input.step_key); if (!step) throw planError('当前计划没有这项步骤。');
let outcome = null, error = null;
try {
const view = await this.inspect(session, { candidates: false }), current = view.steps.find(value => value.key === step.key);
if (current.blockers.length) throw planError('先核验前置步骤:' + current.blockers.join('、'));
outcome = await this.evidence(session, step, input.evidence_id);
this.assertUnchanged(session, plan, task.id, run.id, plan.requirementsSha256);
const previous = this.proofs(session, plan).findLast(value => value.stepKey === step.key && value.status === 'verified');
if (previous?.evidenceId === input.evidence_id && same(previous.outcome, outcome) && current.evidence_verified) return { status: 'completed', step_key: step.key, proof_id: previous.id, reused: true };
} catch (caught) { error = this.redact(caught.message); }
this.assertUnchanged(session, plan, task.id, run.id, plan.requirementsSha256);
const proof = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
planId: plan.id, stepKey: step.key, stepSha256: planHash(step), planContractSha256: plan.contractSha256,
requirementsSha256: plan.requirementsSha256, status: error ? 'rejected' : 'verified', evidenceId: input.evidence_id,
outcome: error ? null : outcome, error, createdAt: at() };
const artifact = this.store.artifactStore.write(session, run, taskProofContract(proof), { kind: 'task-proof' });
proof.contractArtifactId = artifact.id; proof.contractSha256 = artifact.sha256; this.store.core.artifact.set(artifact.id, artifact);
this.store.putRecord('task_proof', session, proof, error ? 'task.proof_rejected' : 'task.proof_verified');
return { status: error ? 'error' : 'completed', step_key: step.key, proof_id: proof.id, proof_artifact_id: artifact.id,
...(error ? { message: error } : { evidence_verified: true, evidence: outcome }) };
}
async assertReady(session, { inspection = null, expectedBinding = undefined } = {}) {
const view = await this.inspect(session, { inspection, candidates: false });
if (view.configured && !view.all_verified) throw planError('任务计划仍有未核验、失效或待更新的步骤,请先完成原任务计划。', 'stale');
if (expectedBinding !== undefined && expectedBinding !== view.binding_sha256) throw planError('Git预览后的任务计划或证明已变化,请重新预览。', 'stale');
return view;
}
}
+16
View File
@@ -182,6 +182,22 @@ return async (request, response) => {
if (method === 'GET' && action === 'research') {
const manager = runtime.researchManager(); return json(response, { availability: manager.availability(), targets: manager.targets(session), jobs: manager.jobs(session) });
}
if (method === 'GET' && action === 'task-plan') {
const taskId = session.taskId, runId = session.runId;
if (url.searchParams.has('taskId') && url.searchParams.get('taskId') !== taskId) throw Object.assign(new Error('所选任务已变化,请刷新当前任务计划。'), { status: 409 });
const plan = await runtime.taskPlanner().inspect(session);
if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('核对期间任务已变化,请刷新当前计划。'), { status: 409 });
return json(response, plan);
}
if (method === 'POST' && ['task-plans', 'task-proofs'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (typeof taskId !== 'string' || typeof runId !== 'string' || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('提交的任务或运行已变化,未修改其他任务计划。'), { status: 409 });
const manager = runtime.taskPlanner();
const result = action === 'task-plans' ? await manager.plan(session, input) : await manager.verify(session, input);
const plan = await manager.inspect(session);
if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('保存结果属于原任务,请刷新所选任务。'), { status: 409 });
return json(response, { session: store.publicSession(session), plan, ...(action === 'task-proofs' ? { verification: result } : {}) }, action === 'task-plans' ? 201 : 200);
}
if (method === 'GET' && action === 'browser') {
const manager = runtime.browserManager(), available = manager.availability();
return json(response, { availability: { status: available.status, engine: available.engine, playwrightVersion: available.playwrightVersion, message: available.message },
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.10.1';
export const APP_VERSION = '1.11.0';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+3 -3
View File
@@ -12,13 +12,13 @@ import { APP_VERSION } from './diagnostics.mjs';
export function installUpgrade(context, { appDirectory, updateServiceInfo = true }) {
const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context;
if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.');
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces, research, engines, browsers and approvals to finish before upgrading.');
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
const root = fs.realpathSync.native(path.resolve(appDirectory));
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
const oldHandlers = server.listeners('request');
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
const oldStoreProperties = { ...store };
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser };
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans };
const oldUpdates = store.listeners('update');
const closeStorage = () => store.close();
if (oldUpdates.length > 1) throw new Error('Unexpected Store observers; preserve their ownership before upgrading.');
@@ -28,7 +28,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
Object.setPrototypeOf(store, Store.prototype);
Object.setPrototypeOf(provider, Provider.prototype);
Object.setPrototypeOf(runtime, Runtime.prototype);
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null;
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null;
store.ensureStorage();
// A SQLite host can retain an artifact object from an earlier bundle.
// Reopen the same blobs through the new API without mutating that object;
+2
View File
@@ -60,6 +60,8 @@ export function projectContext(project) {
'修改较大的工程时,先用index_project/query_code定位符号、导入和文件,再用read_file按实际行读取必要内容。索引是静态证据,部分或无结果不代表完整工程;Python声明候选需读取核对。',
'已有文件优先用propose_patch和read_file返回的SHA256提出唯一锚点精确替换,保留未选中内容与格式;新文件可用propose_file。补丁锚点重叠/重复或文件变化时重新读取,不猜测写入位置。',
'跨文件修改的提案准备完整后,用prepare_change_set将本Task的change_id封存成整批审查。准备不表示应用;用户核对整个批次并确认,结果未知时先用工作台恢复入口核对,不重放文件写入。',
'复杂工程任务先了解实际范围,再用plan_task保存有限依赖步骤及真实通过条件;verify_task_step引用原工具调用、已应用批次或当前检查/页面job核验。不能删改原条件掩盖失败;inspect_task_plan核对未完成项,模型文字不代替步骤核验。简单问答无需新建工程计划。',
'浏览器实际观察的controls.selector已在该DOM核对仅匹配一个元素,优先使用此定位并核对当前页面变化。按钮的nth-of-type可能在多个父元素各匹配一次,不能假定唯一。浏览器失败返回原错误;根据实际字段修正新计划,不重复读完的同一页。',
'检查结果含实际日志摘录及logArtifactId;需要更多失败信息时用read_artifact分段读取完整工件,不要要求用户重复提供工作台已有的日志。',
'若能力表提供浏览器工具,页面任务在构建后先用plan_browser/run_browser取得真实DOM与错误,按实际CSS定位交互和断言;观察或截图不代表通过。修复后重新构建并准备新计划验证,已有浏览器验收未通过时先处理再准备Git交付。',
'工作台会保留当前Task的代码与执行依据视图,绑定原工具结果和读取版本;可直接据此推进,不必反复恢复历史索引。内容有截取标记时按原结果工件取得缺少部分。',
+55 -19
View File
@@ -13,7 +13,7 @@ import { inspectProject } from '../core/project-inspector.mjs';
import { GitDelivery } from '../core/git-delivery.mjs';
import { ProjectIndex } from '../core/context/project-index.mjs';
import { RequestPlanner } from '../core/context/request-plan.mjs';
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, clearReadStreak, recordSessionInspection } from '../core/context/read-budget.mjs';
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, recordBrowserRead, clearReadStreak, recordSessionInspection, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
@@ -23,6 +23,9 @@ import { ResearchManager } from '../core/research-manager.mjs';
import { EngineManager } from '../core/engine-manager.mjs';
import { BrowserManager, publicBrowserPlan } from '../core/browser/browser-manager.mjs';
import { browserPlanInput } from '../shared/contracts/browser.mjs';
import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs';
import { taskPlanInput, taskProofInput, PLAN_READ_TOOLS } from '../shared/contracts/task-plans.mjs';
import { taskPlanToolDefinitions } from '../shared/contracts/task-plan-tools.mjs';
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
@@ -34,10 +37,16 @@ labels.inspect_engine_checks = '查看本任务外部引擎核验';
labels.plan_browser = '准备页面检查计划';
labels.run_browser = '运行实际浏览器检查';
labels.read_browser_result = '读取原页面执行结果';
labels.plan_task = '保存任务依赖计划';
labels.verify_task_step = '核验任务步骤原证据';
labels.inspect_task_plan = '核对任务计划与未完成项';
export function validateToolArgs(tool, args) {
if (!Object.hasOwn(labels, tool)) throw new Error('当前能力表没有工具:' + tool);
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('工具参数必须是 JSON 对象。');
if (tool === 'plan_task') { taskPlanInput(args); return; }
if (tool === 'verify_task_step') { taskProofInput(args); return; }
if (tool === 'inspect_task_plan') { if (Object.keys(args).length) throw new Error('任务计划查询只读取当前Task,不接受执行命令。'); return; }
if (tool === 'plan_browser') { browserPlanInput(args); return; }
if (['run_browser', 'read_browser_result'].includes(tool)) {
const key = tool === 'run_browser' ? 'plan_id' : 'browser_job_id';
@@ -82,9 +91,11 @@ export class Runtime {
this.appDirectory = appDirectory;
this.active = new Map(); this.waiters = new Map();
}
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id) || !!this.research?.isActive(id) || !!this.engines?.isActive(id) || !!this.browser?.isActive(id); }
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0; }
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id) || !!this.research?.isActive(id) || !!this.engines?.isActive(id) || !!this.browser?.isActive(id) || !!this.taskPlans?.isActive(id); }
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; }
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
taskPlanner() { return this.taskPlans ??= new TaskPlanManager(this.store, { redact: value => this.provider.redact(value),
projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
browserManager() { return this.browser ??= new BrowserManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
engineManager() {
@@ -97,27 +108,27 @@ export class Runtime {
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) });
}
projectHasActivity(projectId, exceptSessionId = null) {
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId);
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId);
}
workspaceManager() {
return this.workspaces ??= new WorkspaceManager(this.store, { initialize: this.store.core.workspace.size === 0,
redact: value => this.provider.redact(value), projectBusy: projectId =>
[...this.active.values()].some(run => run.project.id === projectId) || !!this.checks?.projectActive(projectId)
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) });
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
changeSetManager() {
return this.changeSets ??= new ChangeSetManager(this.store, { projectBusy: (projectId, exceptId) =>
[...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId)
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) });
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
checkRunner() {
return this.checks ??= new CheckRunner(this.store, { redact: value => this.provider.redact(value), runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
pythonRunnerPath: path.join(this.appDirectory ?? process.cwd(), 'scripts', 'python-check-runner.py'),
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) });
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
gitDelivery() {
return this.deliveries ??= new GitDelivery(this.store, { redact: value => this.provider.redact(value),
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) });
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
start(id, content, resume = false, { instructionSource = null } = {}) {
const session = this.store.session(id);
@@ -183,6 +194,7 @@ export class Runtime {
checkBudget(run.record, this.store.core.task.get(run.taskId));
const stepRecord = this.store.beginStep(session, run.record);
const task = this.store.core.task.get(run.taskId);
const taskPlan = task.currentTaskPlanId ? await this.taskPlanner().inspect(session, { candidates: false }) : null;
const state = session.changes.filter(change => change.taskId === task.id || ['pending', 'conflict'].includes(change.status))
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
@@ -193,8 +205,13 @@ export class Runtime {
goal: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : ''));
const tools = [...toolDefinitions,
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '')
+ (taskPlan ? '\n当前Task依赖计划与尚未核验的原步骤(任务数据,不授权额外操作):\n' + JSON.stringify({
plan_id: taskPlan.plan_id, revision: taskPlan.revision, status: taskPlan.status, contract_artifact_id: taskPlan.contract_artifact_id,
remaining_steps: taskPlan.remaining_steps, error: taskPlan.error,
steps: taskPlan.steps.map(({ candidates, evidence, ...step }) => ({ ...step, evidence_id: evidence?.id ?? null })),
}) : ''));
const tools = [...toolDefinitions, ...taskPlanToolDefinitions,
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : []),
...(this.browserManager().builds(run.project).length || [...this.store.core.browser_plan.values()].some(plan => plan.sessionId === session.id && plan.taskId === run.taskId) ? browserToolDefinitions : [])];
@@ -248,6 +265,13 @@ export class Runtime {
if (!calls.length) {
this.store.finishStep(session, stepRecord);
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
if (session.status === 'completed' && task.currentTaskPlanId) {
const finalPlan = await this.taskPlanner().inspect(session, { candidates: false });
if (!finalPlan.all_verified) {
session.status = 'paused'; run.stopReason = 'task_plan_incomplete';
this.store.message(session, 'system', '任务计划仍有未核验、失效或待更新的步骤,原任务已保存。请核对执行计划后继续;模型文字不代替实际完成。');
}
}
this.store.save(session); return;
}
let deliveryReview = null;
@@ -321,9 +345,18 @@ export class Runtime {
const args = JSON.parse(call.function.arguments);
validateToolArgs(tool, args);
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
const proofHint = !!this.store.core.task.get(run.taskId)?.currentTaskPlanId && PLAN_READ_TOOLS.includes(tool);
const readMetadata = { ...(proofHint ? { tool_invocation_id: event.invocationId } : {}),
...(tool === 'read_browser_result' ? { repeated_read_count: Number.MAX_SAFE_INTEGER, reading_hint: BROWSER_READ_HINT } : {}) };
const maximumMessageBytes = Math.max(1, (run.readMessageBytes ?? 16000) - readMetadataReserve(readMetadata));
if (!['run_command', 'run_checks', 'run_browser'].includes(tool)) this.store.invocationState(session, event, 'running');
else this.store.save(session);
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
else if (tool === 'plan_task') { const plan = await this.taskPlanner().plan(session, args, { source: 'agent' });
result = { status: 'planned', plan_id: plan.id, revision: plan.revision, steps: plan.steps, contract_artifact_id: plan.contractArtifactId,
note: '计划已保存,步骤尚未核验;保留原目标和通过条件,按原工具结果核验,不直接标记完成。' }; }
else if (tool === 'inspect_task_plan') result = await this.taskPlanner().inspect(session, { candidates: false });
else if (tool === 'verify_task_step') result = await this.taskPlanner().verify(session, args, { source: 'agent' });
else if (tool === 'inspect_engine_checks') result = { status: 'completed', engine_checks: this.engineManager().jobs(session)
.filter(job => job.taskId === run.taskId).map(job => this.engineManager().summary(session, job)), note: '已保存的引擎连接核验;完整原记录使用report_artifact_id读取,查询不会启动引擎。' };
else if (tool === 'list_research_targets') result = { targets: this.researchManager().targets(session), jobs: this.researchManager().jobs(session).filter(job => job.taskId === run.taskId).map(job => this.researchManager().result(job)) };
@@ -332,12 +365,14 @@ export class Runtime {
result = manager.result(await started.promise);
}
else if (tool === 'read_research_evidence') result = this.researchManager().readEvidence(session, args.research_job_id,
{ ...args, maximumMessageBytes: run.readMessageBytes ?? 16000, callId: call.id });
{ ...args, maximumMessageBytes, callId: call.id });
else if (tool === 'inspect_project') result = await inspectProject(run.project);
else if (tool === 'plan_browser') result = { ...publicBrowserPlan(await this.browserManager().plan(session, args, { source: 'agent' })),
note: '计划已封存,页面尚未运行。run_browser请求确认后执行;steps为空只观察页面,不能代替验收。' };
else if (tool === 'read_browser_result') result = this.browserManager().readResult(session, args.browser_job_id,
{ ...args, maximumMessageBytes: run.readMessageBytes ?? 16000, callId: call.id });
else if (tool === 'read_browser_result') {
result = this.browserManager().readResult(session, args.browser_job_id, { ...args, maximumMessageBytes, callId: call.id });
recordBrowserRead(this.store.core.task.get(run.taskId), result, event.invocationId, run.id);
}
else if (tool === 'run_browser') {
const manager = this.browserManager(), plan = manager.planFor(session, args.plan_id);
result = await this.requestCommand(session, event, { browserPlanId: plan.id,
@@ -362,7 +397,7 @@ export class Runtime {
}
else if (tool === 'read_artifact') {
const artifact = this.store.owned('artifact', args.artifact_id, session.id), text = this.store.artifactStore.read(artifact);
result = artifactPage(artifact, text, args, { callId: call.id, maximumMessageBytes: run.readMessageBytes ?? 16000 });
result = artifactPage(artifact, text, args, { callId: call.id, maximumMessageBytes });
recordArtifactRead(this.store.core.task.get(run.taskId), artifact, result, event.invocationId, run.id);
}
else if (tool === 'prepare_change_set') {
@@ -399,15 +434,16 @@ export class Runtime {
});
}
else if (tool === 'list_files') result = listFiles(run.project, args.path, args.depth ?? 3, 500);
else if (tool === 'read_file') result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes: run.readMessageBytes ?? 16000 });
else if (tool === 'read_file') result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes });
else if (tool === 'search_files') result = searchFiles(run.project, args);
else if (tool === 'propose_file') result = proposeFile(this.store, session, args);
else if (tool === 'propose_patch') result = proposePatch(this.store, session, args);
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
else throw new Error('当前能力表没有工具:' + tool);
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : result.status === 'failed' ? 'failed' : 'completed';
if (proofHint) result.tool_invocation_id = event.invocationId;
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : ['failed', 'error'].includes(result.status) ? 'failed' : 'completed';
if (tool === 'inspect_session') recordSessionInspection(this.store.core.task.get(run.taskId), result);
else if (tool !== 'read_artifact' && !['error', 'interrupted', 'unknown', 'denied'].includes(result.status)) clearReadStreak(this.store.core.task.get(run.taskId));
else if (!['read_artifact', 'read_browser_result'].includes(tool) && !['error', 'interrupted', 'unknown', 'denied'].includes(result.status)) clearReadStreak(this.store.core.task.get(run.taskId));
if (typeof result.stdout === 'string') { result.stdout = this.provider.redact(result.stdout); result.stderr = this.provider.redact(result.stderr ?? ''); }
event.output = this.provider.redact(typeof result.stdout === 'string' ? result.stdout + (result.stderr ? '\n' + result.stderr : '') : JSON.stringify(result).slice(0, 16000));
if (result.exit_code !== undefined) event.exitCode = result.exit_code;
@@ -507,11 +543,11 @@ export class Runtime {
}
async stop(sessionId) {
const run = this.active.get(sessionId);
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); await this.research?.stop(sessionId); await this.engines?.stop(sessionId); await this.browser?.stop(sessionId); return; }
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); await this.research?.stop(sessionId); await this.engines?.stop(sessionId); await this.browser?.stop(sessionId); await this.taskPlans?.settle(sessionId); return; }
const session = this.store.session(sessionId);
session.status = 'stopping'; this.store.save(session);
run.controller.abort(new Error('用户停止任务'));
await run.promise;
}
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); }
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.taskPlans?.settle(); }
}
+2
View File
@@ -537,6 +537,8 @@ export class Store extends EventEmitter {
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
artifacts, checks: jobs,
taskPlans: [...this.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-6),
taskProofs: [...this.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-24),
researchTargets: [...this.core.research_target.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-32),
researchJobs: [...this.core.research_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20),
engineJobs: [...this.core.engine_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineJob),
+1 -1
View File
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
export const EXECUTION_SCHEMA = 1;
export const ACTIVE_STATES = new Set(['running', 'awaiting_approval', 'stopping']);
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'browser_plan', 'browser_job'];
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'browser_plan', 'browser_job', 'task_plan', 'task_proof'];
export const timestamp = () => new Date().toISOString();
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
+18
View File
@@ -0,0 +1,18 @@
export const taskPlanToolDefinitions = [
{ type: 'function', function: { name: 'plan_task', description: '为当前复杂任务保存1–12步有依赖的计划。每步固定通过条件及实际证据类别,规划不执行操作。expected_revision首次为0;以后保留全部原步骤并追加,不能删改条件掩盖失败。原用户要求或计划变化后重新封存并核验仍有效的原证据,不重跑已完成工具。', parameters: {
type: 'object', additionalProperties: false, required: ['expected_revision', 'steps'], properties: { expected_revision: { type: 'integer', minimum: 0 }, steps: { type: 'array', minItems: 1, maxItems: 12, items: {
type: 'object', additionalProperties: false, required: ['key', 'title', 'criterion', 'kind'], properties: {
key: { type: 'string', pattern: '^[a-z][a-z0-9_-]{0,39}$' }, title: { type: 'string', maxLength: 100 }, criterion: { type: 'string', maxLength: 300 },
kind: { type: 'string', enum: ['analysis', 'changes', 'checks', 'browser'] }, depends_on: { type: 'array', items: { type: 'string' }, maxItems: 12 },
tools: { type: 'array', description: 'analysis必填,只读工具名称,例如inspect_project/read_file/query_code。', items: { type: 'string' } },
paths: { type: 'array', description: 'changes必填,实际改动的项目相对文件路径。', items: { type: 'string' }, maxItems: 32 },
checks: { type: 'array', description: 'checks必填,实际检查名称,例如test/typecheck/build或python:test。', items: { type: 'string' }, maxItems: 6 },
viewport_width: { type: 'integer', description: 'browser必填,固定桌面/手机视口宽度。', minimum: 320, maximum: 1440 },
actions: { type: 'array', description: 'browser需要的实际操作,始终要求非空通过断言及进程退出。', items: { type: 'string', enum: ['fill', 'select', 'click', 'assert_text', 'assert_count', 'assert_visible'] } },
} } } } } } },
{ type: 'function', function: { name: 'verify_task_step', description: '核验当前计划的一步,前置步骤必须先核验。evidence_id为原tool_invocation_id、已应用change_set_id、实际检查job_id或browser_job_id;类别按原步骤决定。核对原字节/当前输入,失败和失效保留,模型不能直接标完成,不重新执行工具。', parameters: {
type: 'object', additionalProperties: false, required: ['plan_id', 'step_key', 'evidence_id', 'expected_revision'], properties: {
plan_id: { type: 'string' }, step_key: { type: 'string' }, evidence_id: { type: 'string' }, expected_revision: { type: 'integer', minimum: 1 },
} } } },
{ type: 'function', function: { name: 'inspect_task_plan', description: '核对当前Task原计划、步骤依赖及现有证明的有效性。返回ready/blocked/verified/stale/needs_update及未完成项和原工件引用;读取不执行或重放工具。', parameters: { type: 'object', additionalProperties: false, properties: {} } } },
];
+74
View File
@@ -0,0 +1,74 @@
import { createHash } from 'node:crypto';
import { isId } from './execution.mjs';
export const TASK_PLAN_LIMITS = Object.freeze({ steps: 12, text: 6000, revisions: 24 });
export const PLAN_READ_TOOLS = ['inspect_project', 'read_file', 'list_files', 'search_files', 'index_project', 'query_code', 'read_research_evidence', 'inspect_engine_checks', 'read_browser_result'];
export const planHash = value => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest('hex');
export const planError = (message, code = 'invalid', status = 409) => Object.assign(new Error(message), { status, code });
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const keyPattern = /^[a-z][a-z0-9_-]{0,39}$/;
const text = (value, max, label) => {
if (typeof value !== 'string' || !value.trim() || value.length > max || /\0/.test(value)) throw planError(label + '需要1–' + max + '字文本。', 'input', 400);
return value.trim();
};
const unique = (values, label, max = 32) => {
if (!Array.isArray(values) || values.length > max || values.some(value => typeof value !== 'string' || !value || value.length > 160)
|| new Set(values).size !== values.length) throw planError(label + '需要不重复的文本列表。', 'input', 400);
return [...values];
};
export function taskPlanInput(input) {
if (!object(input) || Object.keys(input).some(key => !['expected_revision', 'steps'].includes(key))
|| !Number.isSafeInteger(input.expected_revision) || input.expected_revision < 0) throw planError('任务计划需要expected_revision和steps,不能添加执行命令或完成状态。', 'input', 400);
if (!Array.isArray(input.steps) || !input.steps.length || input.steps.length > TASK_PLAN_LIMITS.steps) throw planError('任务计划需要1–12个步骤。', 'input', 400);
const steps = input.steps.map(value => {
if (!object(value) || Object.keys(value).some(key => !['key', 'title', 'criterion', 'kind', 'depends_on', 'tools', 'paths', 'checks', 'viewport_width', 'actions'].includes(key))
|| typeof value.key !== 'string' || !keyPattern.test(value.key) || !['analysis', 'changes', 'checks', 'browser'].includes(value.kind)) throw planError('步骤需要key、title、criterion和有效证据类别。', 'input', 400);
const step = { key: value.key, title: text(value.title, 100, '步骤标题'), criterion: text(value.criterion, 300, '通过条件'), kind: value.kind,
depends_on: unique(value.depends_on ?? [], '前置依赖', TASK_PLAN_LIMITS.steps).sort() };
const allowed = value.kind === 'analysis' ? ['tools'] : value.kind === 'changes' ? ['paths'] : value.kind === 'checks' ? ['checks'] : ['viewport_width', 'actions'];
if (['tools', 'paths', 'checks', 'viewport_width', 'actions'].some(key => value[key] !== undefined && !allowed.includes(key))) throw planError('步骤证据字段与类别不一致。', 'input', 400);
if (value.kind === 'analysis') {
step.tools = unique(value.tools, '读取工具', PLAN_READ_TOOLS.length).sort();
if (!step.tools.length || step.tools.some(tool => !PLAN_READ_TOOLS.includes(tool))) throw planError('工程读取只能引用已声明的实际只读工具。', 'input', 400);
} else if (value.kind === 'changes') {
step.paths = unique(value.paths, '文件范围').sort();
if (!step.paths.length || step.paths.some(file => /[\\:\0]/.test(file) || file.startsWith('/') || file.split('/').some(part => !part || part === '..' || ['.git', '.hg', '.svn'].includes(part)))) throw planError('源码步骤需要项目内常规相对文件路径。', 'input', 400);
} else if (value.kind === 'checks') {
step.checks = unique(value.checks, '检查名称', 6).sort();
if (!step.checks.length) throw planError('检查步骤必须固定至少一个实际检查名称。', 'input', 400);
} else {
if (!Number.isSafeInteger(value.viewport_width) || value.viewport_width < 320 || value.viewport_width > 1440) throw planError('页面步骤需要320–1440像素的固定视口宽度。', 'input', 400);
step.viewport_width = value.viewport_width; step.actions = unique(value.actions ?? [], '页面必要操作', 6).sort();
if (step.actions.some(action => !['fill', 'select', 'click', 'assert_text', 'assert_count', 'assert_visible'].includes(action))) throw planError('页面必要操作无效。', 'input', 400);
}
return step;
});
const keys = new Set(steps.map(step => step.key));
if (keys.size !== steps.length) throw planError('步骤key必须唯一。', 'input', 400);
for (const step of steps) if (step.depends_on.some(key => !keys.has(key) || key === step.key)) throw planError('前置步骤必须存在,且不能引用自己。', 'input', 400);
const visiting = new Set(), done = new Set();
const walk = key => { if (visiting.has(key)) throw planError('任务步骤依赖不能形成循环。', 'input', 400);
if (done.has(key)) return; visiting.add(key); for (const dependency of steps.find(step => step.key === key).depends_on) walk(dependency); visiting.delete(key); done.add(key); };
for (const step of steps) walk(step.key);
if (steps.reduce((sum, step) => sum + step.title.length + step.criterion.length, 0) > TASK_PLAN_LIMITS.text) throw planError('计划文本超过保留预算,请缩小单个任务范围。', 'input', 400);
return { expected_revision: input.expected_revision, steps };
}
export function taskProofInput(input) {
if (!object(input) || Object.keys(input).some(key => !['plan_id', 'step_key', 'evidence_id', 'expected_revision'].includes(key))
|| !isId(input.plan_id) || typeof input.step_key !== 'string' || !keyPattern.test(input.step_key) || !isId(input.evidence_id)
|| !Number.isSafeInteger(input.expected_revision) || input.expected_revision < 1) throw planError('核验需要当前计划ID、步骤key、原证据ID和expected_revision,不能传入完成结论。', 'input', 400);
return { ...input };
}
export const taskRequirements = task => ({ goal: task.goal, instructions: (task.instructions ?? []).filter(value => value.source !== 'review-action')
.map(value => ({ id: value.id, content: value.content, ...(value.source ? { source: value.source } : {}) })),
constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], workspace: task.workspaceIdentity ?? null });
export const taskPlanContract = plan => ({ schemaVersion: 1, kind: 'task-plan-contract', id: plan.id, sessionId: plan.sessionId, projectId: plan.projectId,
taskId: plan.taskId, runId: plan.runId, revision: plan.revision, parentPlanId: plan.parentPlanId, createdAt: plan.createdAt,
requirements: plan.requirements, requirementsSha256: plan.requirementsSha256, steps: plan.steps });
export const taskProofContract = proof => ({ schemaVersion: 1, kind: 'task-step-proof', id: proof.id, sessionId: proof.sessionId, projectId: proof.projectId,
taskId: proof.taskId, runId: proof.runId, planId: proof.planId, stepKey: proof.stepKey, stepSha256: proof.stepSha256,
planContractSha256: proof.planContractSha256, requirementsSha256: proof.requirementsSha256, status: proof.status,
evidenceId: proof.evidenceId, outcome: proof.outcome, error: proof.error, createdAt: proof.createdAt });
+28
View File
@@ -1,5 +1,14 @@
# Agent Workbench:核心代理能力研究与产品计划
## 1.11 当前开发:持久任务依赖与证据收尾
1. [in_progress] 有界无环依赖、不可变/只追加修订、原目标与工作区绑定及真实工具/变更/检查/页面证据。
2. [pending] 模型工具、上下文保留、未完成暂停、Git预览/提交核对及交付报告。
3. [pending] 任务记录界面、桌面/390px与迟到响应/宿主恢复验收。
4. [pending] 相关回归、源码构建、独立真实流程、及时本地提交;发行及正式升级另行判定。
开发位于独立Git工作区6bc3ce4基线;主目录1.10.1修复包独立验收同步执行,正式模型连接仍只在原PID23080内存中。
## 当前执行:真实工程交付与内置浏览器验证(2026-10-30)
本轮全量接续:HEAD=5921b8e,工作区干净。正式服务实测1.9.0/PID23080;1.10.0不可变候选20261030004653739已生成,便携归档/真实随包浏览器通过。独立源码验收PID44208仍执行已有274项完整回归,不重复启动;完成后封存输入、升级原Provider并验证工作台实际页面任务,继续下一项核心能力。
@@ -288,3 +297,22 @@
本轮恢复错误:父研究目录不是Git仓库,已切换独立产品目录。批量源码/文档输出触发截断后改为短段和结构化摘要;Windows rg通配文件名失败改为目录加-g,未把截断内容作为完整核对。所有验收使用自有工件、独立端口和数据目录。
恢复时的只读搜索一次错误使用Windows通配路径和不存在的types文件,改为实际目录加glob;先前大输出截断不作为完整读取证据。session-catchup未发现额外记录。
## 当前1.11独立工作区实现与验收
2026-10-30接续:正式4318实际为1.10.1/PID23080;主分支b3d2d78与独立工作区6bc3ce4之间只有已封存的1.10.1交付文档。原20项专项19通过,唯一失败为验收器调用host.stop而实际helper提供host.close,已按原宿主契约修正。下一步完成最终专项、真实界面、完整独立源码及本地发行,保留旧失败原TAP与原Provider。
本轮恢复记录:过量批量读取曾被截断,后续分段限定预算;两个猜测的只读路径verify-task-ui.mjs/QA-1.10.1.md不存在,实际为verify-execution-ui.mjs/QA-1.10.md。未将截断或读取失败计为验证。
最终专项20/20通过。首次新UI验收在折叠的依赖证据区域查找可见按钮失败,0页面/请求异常;保留.qa/task-plan-ui-95c4471e-9d1b-4d86-9cbc-3304459f4c3e原DOM/截图/结果,验证器先展开实际区域再核对原禁用状态。界面离开任务面板后丢弃迟到响应的保护已补齐。
第二轮新UI6组通过,组件卸载故障场景试图点击保存弹窗背后的页签而被实际遮罩正确阻止,原结果保留.qa/task-plan-ui-c817c9f1-0f54-4711-bc8c-a6a15f1cf690。该场景改为明确标注的受控DOM事件调度,检验组件卸载后的迟到成功处理,不宣称用户能穿透弹窗。
接续21/21专项和9组Git复验通过:证据ID及页面重复提示按双层JSON预留,最新反馈保留原调用/证明/计划和DOM唯一定位。原完整UI首五类44组后因夹具依赖可见历史数量而失败,原失败封存后按实际反馈修正;完整源码原测试根PID16684/子树核对后主动结束,原输入/部分TAP及stopped.json保持,不计为完成。准备本地独立实现提交,最终完整源码/界面与发行另行验收。
1. [in_progress] 持久任务依赖计划、不可变修订和原证据核验;Runtime/活动控制/HTTP身份/Git预览与发布/JSON及Markdown已接入。
2. [in_progress] 执行计划界面和结构化编辑器已构建,继续相关行为、HTTP、实际恢复与1280/390px验证。
3. [pending] 补实际DOM唯一CSS定位证据和页面读取进展,保留严格多元素拒绝及原模型失败。
4. [pending] 完整源码和界面、实际工程样本、本地Git提交、独立发行与原Provider升级。
本轮错误:恢复时猜测不存在的server/http和check-runner测试路径,已按rg真实清单定位app.mjs与checks.test.mjs;一次过量输出改为限定短段。新增界面首轮可选execution字段TypeScript错误已修正并构建通过;首次TAP重定向因.qa不存在,测试尚未启动,创建目录后执行。
+54
View File
@@ -0,0 +1,54 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fixture, call, assertToolPairs } from './helpers.mjs';
import { createBrowserProject } from './fixtures/browser-project.mjs';
import { BrowserManager } from '../src/core/browser/browser-manager.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { recordBrowserRead } from '../src/core/context/read-budget.mjs';
test('actual DOM controls include validated unique CSS selectors across repeated parent buttons and escaped labels', async t => {
const f = createBrowserProject(fixture(t)), manager = new BrowserManager(f.store); f.onCleanup(() => manager.stopAll());
const html = path.join(f.projectRoot, 'dist/index.html');
fs.appendFileSync(html, '<section><button>同类按钮一</button></section><section><button>同类按钮二</button></section><input aria-label="特殊&amp;标签&quot;一" id="field:special">');
const observation = await manager.plan(f.session, { steps: [] }), observed = await manager.start(f.session, observation.id).promise;
assert.equal(observed.status, 'observed');
const original = JSON.parse(f.store.artifactStore.read(f.store.core.artifact.get(observed.resultArtifactId))), controls = original.pages.at(-1).controls;
assert.ok(controls.length >= 6); assert.ok(controls.every(control => control.selectorEvidence === 'observed-dom-query' && control.selectorMatches === 1 && control.selector.length <= 300));
assert.equal(new Set(controls.map(control => control.selector)).size, controls.length);
const exact = await manager.plan(f.session, { steps: controls.map(control => ({ action: 'assert_count', selector: control.selector, count: 1 })) });
assert.equal((await manager.start(f.session, exact.id).promise).status, 'passed');
const ambiguous = await manager.plan(f.session, { steps: [{ action: 'assert_visible', selector: 'button:nth-of-type(1)' }] });
const rejected = await manager.start(f.session, ambiguous.id).promise;
assert.equal(rejected.status, 'failed'); assert.match(rejected.summary, /strict mode violation/);
});
test('browser field coverage distinguishes sections and Run windows while retaining original source identity', () => {
const task = { activeRunId: 'run-one' }, page = { source_artifact_id: 'original-source', source_sha256: 'a'.repeat(64), view_sha256: 'b'.repeat(64), section: 'page', content: '原字段正文', offset: 0, next_offset: 5 };
for (let count = 0; count < 4; count++) recordBrowserRead(task, { ...page }, 'inv-' + count, 'run-one');
assert.equal(task.readProgress.repeated, 3); assert.equal(task.readProgress.pause, true);
recordBrowserRead(task, { ...page, section: 'steps' }, 'other-section', 'run-one'); assert.equal(task.readProgress.repeated, 0);
recordBrowserRead(task, { ...page }, 'new-run', 'run-two'); assert.equal(task.readProgress.repeated, 0);
assert.equal(task.readProgress.last.artifactId, 'original-source'); assert.equal(task.readProgress.last.sourceSha256, 'a'.repeat(64));
assert.equal(task.readProgress.reads.length, 2);
});
test('repeated original browser pages pause a live Task without re-opening the browser or breaking tool pairing', async t => {
const f = createBrowserProject(fixture(t)), browser = new BrowserManager(f.store); f.onCleanup(() => browser.stopAll());
const plan = await browser.plan(f.session, { steps: [{ action: 'assert_count', selector: 'button', count: 1 }] }), original = await browser.start(f.session, plan.id).promise;
assert.equal(original.status, 'passed');
const provider = new Provider(), runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
const execute = runtime.executeTool.bind(runtime);
runtime.executeTool = (session, invocation, run) => { run.readMessageBytes = 4096; return execute(session, invocation, run); };
let requests = 0;
provider.complete = async () => ({ message: { role: 'assistant', content: '', tool_calls: [call('browser-repeat-' + requests++, 'read_browser_result', { browser_job_id: original.id, section: 'page', limit: 1000 })] }, usage: { prompt_tokens: 100, completion_tokens: 20 } });
runtime.start(f.session.id, '读取本任务原页面字段'); await runtime.active.get(f.session.id).promise;
assert.equal(f.session.status, 'paused'); assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'no_progress'); assert.equal(requests, 4);
assert.equal(f.store.core.browser_job.size, 1); assert.equal(f.store.core.browser_job.get(original.id).status, 'passed');
for (const message of f.session.providerMessages.filter(value => value.role === 'tool')) {
assert.ok(Buffer.byteLength(JSON.stringify(message), 'utf8') <= 4096, 'Original browser result plus repeat metadata must fit the actual next tool message.');
}
assertToolPairs(f.session.providerMessages);
});
+18
View File
@@ -0,0 +1,18 @@
import fs from 'node:fs';
import { Store } from '../../src/server/store.mjs';
import { TaskPlanManager } from '../../src/core/tasks/task-plan-manager.mjs';
import { readingStep } from './task-plan-fixture.mjs';
const [inputFile] = process.argv.slice(2), input = JSON.parse(fs.readFileSync(inputFile, 'utf8'));
const store = new Store(input.data), session = store.session(input.sessionId), manager = new TaskPlanManager(store);
const put = store.putRecord.bind(store);
store.putRecord = (kind, ...args) => {
const selected = kind === (input.operation === 'plan' ? 'task_plan' : 'task_proof');
if (selected && input.point === 'before') process.exit(71);
const result = put(kind, ...args);
if (selected && input.point === 'after') process.exit(71);
return result;
};
if (input.operation === 'plan') await manager.plan(session, { expected_revision: 0, steps: [readingStep()] });
else await manager.verify(session, { plan_id: input.planId, expected_revision: 1, step_key: 'read', evidence_id: input.evidenceId });
throw new Error('The declared process exit point was not reached.');
+21
View File
@@ -0,0 +1,21 @@
import { randomUUID } from 'node:crypto';
import { call } from '../helpers.mjs';
import { readText } from '../../src/server/files.mjs';
export const readingStep = (key = 'read', depends_on = []) => ({ key, title: '读取实际工程', criterion: '实际读取本工程文件并保留原结果', kind: 'analysis', tools: ['read_file'], depends_on });
export const checksStep = (key = 'check', depends_on = []) => ({ key, title: '检查工程', criterion: '所选测试与构建实际通过', kind: 'checks', checks: ['test', 'build'], depends_on });
export function beginPlanTask(f, goal = '检查工程并按真实证据交付') {
const run = f.store.beginRun(f.session, goal, false, f.store.config);
f.session.status = 'paused'; f.store.finishRun(f.session, run, 'plan_ready'); return run;
}
export function completeRead(f, relative = 'README.md') {
const run = f.store.core.run.get(f.session.runId), invocation = call('plan-read-' + randomUUID(), 'read_file', { path: relative });
f.session.providerMessages.push({ role: 'assistant', content: '', tool_calls: [invocation] });
const event = f.store.event(f.session, { kind: 'tool', toolCallId: invocation.id, tool: 'read_file', phase: 'queued', label: '实际文件读取' });
const record = f.store.beginInvocation(f.session, invocation, run, event);
f.store.invocationState(f.session, event, 'running');
const result = { ...readText(f.project, relative), tool_invocation_id: record.id };
event.phase = 'completed'; f.store.finishInvocation(f.session, event, result);
f.session.providerMessages.push({ role: 'tool', tool_call_id: invocation.id, content: JSON.stringify(result) }); f.store.save(f.session);
return record;
}
+39
View File
@@ -0,0 +1,39 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { fixture, launchWorkbench, assertToolPairs } from './helpers.mjs';
import { beginPlanTask, completeRead, readingStep } from './fixtures/task-plan-fixture.mjs';
test('task-plan HTTP mutations bind current Task/Run and retain original evidence through real host restart', async t => {
const f = fixture(t); beginPlanTask(f); const record = completeRead(f), taskId = f.session.taskId, runId = f.session.runId; f.store.close();
let host = await launchWorkbench(t, f.data), route = '/sessions/' + f.session.id;
const input = { taskId, runId, expected_revision: 0, steps: [readingStep()] };
assert.equal((await host.api(route + '/task-plan')).configured, false);
await assert.rejects(host.api(route + '/task-plans', { ...input, taskId: '00000000-0000-0000-0000-000000000000' }), /任务或运行已变化/);
const saved = await host.api(route + '/task-plans', input), planId = saved.plan.plan_id;
assert.equal(saved.plan.revision, 1); assert.equal(saved.session.execution.taskPlans[0].id, planId);
const other = await host.api('/sessions', { projectId: f.project.id });
await assert.rejects(host.api('/sessions/' + other.id + '/task-plans', input), /任务或运行已变化/);
await assert.rejects(host.api(route + '/task-plan?taskId=wrong'), /所选任务已变化/);
const verified = await host.api(route + '/task-proofs', { taskId, runId, plan_id: planId, expected_revision: 1, step_key: 'read', evidence_id: record.id });
assert.equal(verified.verification.status, 'completed'); assert.equal(verified.plan.all_verified, true);
assert.equal(verified.session.execution.taskProofs.length, 1);
const before = await host.api(route + '/export'); await host.close();
host = await launchWorkbench(t, f.data);
const restored = await host.api(route + '/task-plan?taskId=' + taskId);
assert.equal(restored.all_verified, true); assert.equal(restored.plan_id, planId);
const after = await host.api(route + '/export'); assert.deepEqual(after.session.providerMessages, before.session.providerMessages);
assert.equal(after.execution.progress.totalTools, 1); assertToolPairs(after.session.providerMessages);
});
test('concurrent stale HTTP plan revisions cannot replace conditions or attach proofs to a different plan', async t => {
const f = fixture(t); beginPlanTask(f); const read = completeRead(f), taskId = f.session.taskId, runId = f.session.runId; f.store.close();
const host = await launchWorkbench(t, f.data), route = '/sessions/' + f.session.id;
const saved = await host.api(route + '/task-plans', { taskId, runId, expected_revision: 0, steps: [readingStep()] });
const requests = await Promise.allSettled(['later_a', 'later_b'].map(key => host.api(route + '/task-plans', { taskId, runId, expected_revision: 1, steps: [readingStep(), readingStep(key)] })));
assert.equal(requests.filter(value => value.status === 'fulfilled').length, 1);
assert.equal(requests.filter(value => value.status === 'rejected').length, 1);
const current = await host.api(route + '/task-plan'); assert.equal(current.revision, 2);
await assert.rejects(host.api(route + '/task-plans', { taskId, runId, expected_revision: 2, steps: [{ ...readingStep(), criterion: '弱化条件' }] }), /不能删改/);
await assert.rejects(host.api(route + '/task-proofs', { taskId, runId, plan_id: saved.plan.plan_id, expected_revision: 1, step_key: 'read', evidence_id: read.id }), /原计划视图/);
const exported = await host.api(route + '/export'); assert.equal(exported.execution.taskPlans.length, 2); assert.equal(exported.execution.taskProofs.length, 0);
});
+223
View File
@@ -0,0 +1,223 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fixture, call, assertToolPairs } from './helpers.mjs';
import { readingStep, checksStep, beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
import { createDeliveryProject, applyDeliveryFix, deliveryGit } from './fixtures/delivery-project.mjs';
import { createBrowserProject, browserSteps } from './fixtures/browser-project.mjs';
import { taskPlanInput } from '../src/shared/contracts/task-plans.mjs';
import { TaskPlanManager } from '../src/core/tasks/task-plan-manager.mjs';
import { Store } from '../src/server/store.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { compactToolFeedback } from '../src/core/context/tool-feedback.mjs';
test('a real escaped long-file tool message keeps its proof identity within a tight request budget', async t => {
const f = fixture(t); beginPlanTask(f); await new TaskPlanManager(f.store).plan(f.session, { expected_revision: 0, steps: [readingStep()] });
fs.writeFileSync(path.join(f.projectRoot, 'long.mjs'), '"中文😀\\\\\n'.repeat(600));
const provider = new Provider(), runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
const invocation = call('bounded-proof-read', 'read_file', { path: 'long.mjs' });
f.session.providerMessages.push({ role: 'assistant', content: '', tool_calls: [invocation] });
const record = f.store.core.run.get(f.session.runId);
const result = await runtime.executeTool(f.session, invocation, { id: record.id, taskId: record.taskId, record, project: f.project, config: f.store.config, readMessageBytes: 1024 });
assert.ok(result.tool_invocation_id); assert.ok(result.budget_limited); assert.ok(result.returned_characters > 0);
assert.ok(Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: invocation.id, content: JSON.stringify(result) }), 'utf8') <= 1024);
assert.equal(compactToolFeedback(JSON.stringify(result)).tool_invocation_id, result.tool_invocation_id);
const proof = await new TaskPlanManager(f.store).verify(f.session, { plan_id: f.store.core.task.get(f.session.taskId).currentTaskPlanId,
expected_revision: 1, step_key: 'read', evidence_id: result.tool_invocation_id });
assert.equal(proof.status, 'completed');
});
import { CheckRunner } from '../src/core/check-runner.mjs';
import { BrowserManager } from '../src/core/browser/browser-manager.mjs';
import { ChangeSetManager } from '../src/core/workspaces/change-sets.mjs';
import { proposeFile } from '../src/server/files.mjs';
import { GitDelivery } from '../src/core/git-delivery.mjs';
import { DeliveryReporter } from '../src/core/delivery-report.mjs';
const save = (manager, session, steps, expected_revision = 0) => manager.plan(session, { steps, expected_revision });
const verify = (manager, session, plan, step_key, evidence_id) => manager.verify(session, { plan_id: plan.id, expected_revision: plan.revision, step_key, evidence_id });
const corrupt = (store, id) => fs.appendFileSync(path.join(store.artifactStore.root, store.core.artifact.get(id).relative), 'corruption');
const pause = f => { f.session.status = 'paused'; f.store.save(f.session); };
test('task plans reject fabricated completion, invalid scopes and cyclic or missing dependencies', () => {
assert.throws(() => taskPlanInput({ expected_revision: 0, steps: [{ ...readingStep(), status: 'verified' }] }), /有效证据类别/);
assert.throws(() => taskPlanInput({ expected_revision: 0, steps: [readingStep('a', ['b']), readingStep('b', ['a'])] }), /循环/);
assert.throws(() => taskPlanInput({ expected_revision: 0, steps: [readingStep('a', ['unknown'])] }), /必须存在/);
assert.throws(() => taskPlanInput({ expected_revision: 0, steps: [{ ...readingStep(), tools: ['run_command'] }] }), /只读/);
assert.throws(() => taskPlanInput({ expected_revision: 0, steps: [{ key: 'write', title: '修改', criterion: '修改已审查', kind: 'changes', paths: ['../other.mjs'] }] }), /相对文件/);
});
test('sealed plans retain goal, contract hash and original steps through SQLite reopen without executing tools', async t => {
const f = fixture(t); beginPlanTask(f); const manager = new TaskPlanManager(f.store), steps = [readingStep()];
const plan = await save(manager, f.session, steps), artifact = f.store.core.artifact.get(plan.contractArtifactId);
assert.equal(artifact.sha256, plan.contractSha256); assert.equal(f.store.core.tool.size, 0);
assert.equal((await save(manager, f.session, steps)).id, plan.id);
await assert.rejects(save(manager, f.session, [{ ...steps[0], criterion: '弱化条件' }], 1), /不能删改/);
await assert.rejects(save(manager, f.session, [...steps, readingStep('later')], 0), /视图已过期/);
f.store.close(); const restored = new Store(f.data); f.onCleanup(() => restored.close());
const view = await new TaskPlanManager(restored).inspect(restored.session(f.session.id));
assert.equal(view.plan_id, plan.id); assert.equal(view.revision, 1); assert.equal(view.steps[0].status, 'ready');
assert.equal(restored.core.tool.size, 0); assert.equal(restored.core.task.get(f.session.taskId).goal, '检查工程并按真实证据交付');
});
test('proofs require original owned reads, honor dependencies and reject altered invocation arguments and bytes', async t => {
const f = fixture(t); beginPlanTask(f); const manager = new TaskPlanManager(f.store), record = completeRead(f);
const plan = await save(manager, f.session, [readingStep('first'), readingStep('next', ['first'])]);
assert.equal((await verify(manager, f.session, plan, 'next', record.id)).status, 'error');
assert.equal((await manager.inspect(f.session)).steps[1].status, 'blocked');
assert.equal((await verify(manager, f.session, plan, 'first', record.id)).status, 'completed');
const again = await verify(manager, f.session, plan, 'first', record.id); assert.equal(again.reused, true);
assert.equal((await verify(manager, f.session, plan, 'next', record.id)).status, 'completed');
assert.equal((await manager.inspect(f.session)).all_verified, true); assert.equal(f.store.core.tool.size, 1);
const argumentsBefore = f.session.providerMessages[0].tool_calls[0].function.arguments;
f.session.providerMessages[0].tool_calls[0].function.arguments = '{"path":"different-file"}';
assert.equal((await manager.inspect(f.session)).all_verified, false);
f.session.providerMessages[0].tool_calls[0].function.arguments = argumentsBefore;
corrupt(f.store, record.resultArtifactId);
assert.equal((await manager.inspect(f.session)).steps[0].status, 'unverified');
assert.equal((await verify(manager, f.session, plan, 'first', record.id)).status, 'error');
assert.equal(f.store.core.tool.size, 1);
});
test('new user requirements invalidate current proofs and reseal the same original operations in a new revision', async t => {
const f = fixture(t); beginPlanTask(f); const manager = new TaskPlanManager(f.store), record = completeRead(f), original = await save(manager, f.session, [readingStep()]);
await verify(manager, f.session, original, 'read', record.id);
const run = f.store.beginRun(f.session, '追加约束:保留原文件格式', true, f.store.config, { instructionSource: 'user' }); pause(f);
assert.equal((await manager.inspect(f.session)).status, 'needs_update');
await assert.rejects(verify(manager, f.session, original, 'read', record.id), /目标已变化/);
const next = await save(manager, f.session, [readingStep()], 1); assert.equal(next.parentPlanId, original.id); assert.equal(next.runId, run.id);
assert.equal((await manager.inspect(f.session)).all_verified, false);
await verify(manager, f.session, next, 'read', record.id);
assert.equal((await manager.inspect(f.session)).all_verified, true); assert.equal(f.store.core.tool.size, 1);
assert.equal(f.store.core.task_plan.size, 2); assert.equal(f.store.core.task_proof.size, 2);
});
test('applied change-set evidence binds reviewed current files and invalidates dependent steps after outside edits', async t => {
const f = fixture(t); beginPlanTask(f); const manager = new TaskPlanManager(f.store), batches = new ChangeSetManager(f.store);
f.onCleanup(() => batches.stopAll());
const proposed = proposeFile(f.store, f.session, { path: 'src/result.mjs', content: 'export const result = 42;\n', reason: 'Reviewed plan fixture' });
const set = await batches.prepare(f.session, [proposed.change_id]);
const plan = await save(manager, f.session, [{ key: 'change', title: '完成源文件', criterion: '审查后应用实际源码', kind: 'changes', paths: ['src/result.mjs'], depends_on: [] }, readingStep('read', ['change'])]);
assert.equal((await verify(manager, f.session, plan, 'change', set.id)).status, 'error');
await (await batches.start(f.session, set.id, set.fingerprint)).promise; assert.equal(set.status, 'completed');
assert.equal((await verify(manager, f.session, plan, 'change', set.id)).status, 'completed');
await verify(manager, f.session, plan, 'read', completeRead(f).id); assert.equal((await manager.inspect(f.session)).all_verified, true);
fs.appendFileSync(path.join(f.projectRoot, 'src/result.mjs'), '// user edit\n');
const changed = await manager.inspect(f.session); assert.equal(changed.steps[0].status, 'stale'); assert.equal(changed.steps[1].status, 'blocked');
assert.equal(set.status, 'completed', 'Read-only plan inspection must not rewrite the original applied result.');
});
test('actual npm checks are verified by original counted logs and current source, with failure history retained', async t => {
const f = fixture(t); createDeliveryProject(f); pause(f);
const manager = new TaskPlanManager(f.store), runner = new CheckRunner(f.store); f.onCleanup(() => runner.stopAll());
const plan = await save(manager, f.session, [checksStep()]);
const failedPlan = await runner.plan(f.session), failed = await (await runner.start(f.session, failedPlan.id)).promise;
assert.equal(failed.status, 'failed'); assert.equal((await verify(manager, f.session, plan, 'check', failed.id)).status, 'error');
applyDeliveryFix(f);
const passedPlan = await runner.plan(f.session), passed = await (await runner.start(f.session, passedPlan.id)).promise;
assert.equal(passed.status, 'passed'); assert.equal((await verify(manager, f.session, plan, 'check', passed.id)).status, 'completed');
assert.equal((await manager.inspect(f.session)).all_verified, true); assert.equal(passed.results[0].tests.total, 3);
passed.results[0].tests.total++; assert.equal((await manager.inspect(f.session)).all_verified, false); passed.results[0].tests.total--;
corrupt(f.store, passed.results[0].logArtifactId); assert.equal((await manager.inspect(f.session)).all_verified, false);
assert.equal(failed.status, 'failed'); assert.equal(f.store.core.task_proof.size, 2);
});
test('real desktop and mobile browser proofs bind required actions and PNGs, rejecting a later failed plan and changed builds', async t => {
const f = createBrowserProject(fixture(t)), manager = new TaskPlanManager(f.store), browser = new BrowserManager(f.store);
f.onCleanup(() => browser.stopAll());
const plan = await save(manager, f.session, [1280, 390].map((width, index) => ({ key: 'page' + index, title: width + 'px页面', criterion: '实际交互与可见断言通过', kind: 'browser', viewport_width: width, actions: ['fill', 'select', 'click'], depends_on: [] })));
for (const [index, width] of [1280, 390].entries()) {
const page = await browser.plan(f.session, { steps: browserSteps, viewport: { width, height: 844 } }), job = await browser.start(f.session, page.id).promise;
assert.equal(job.status, 'passed', job.summary); assert.equal((await verify(manager, f.session, plan, 'page' + index, job.id)).status, 'completed');
}
assert.equal((await manager.inspect(f.session)).all_verified, true);
const failingPlan = await browser.plan(f.session, { steps: [{ action: 'assert_count', selector: 'button', count: 9 }], viewport: { width: 390, height: 844 } });
assert.equal((await browser.start(f.session, failingPlan.id).promise).status, 'failed');
assert.equal((await manager.inspect(f.session)).steps[1].status, 'stale');
fs.appendFileSync(path.join(f.projectRoot, 'dist/app.js'), '// changed output\n');
assert.equal((await manager.inspect(f.session)).steps[0].status, 'stale');
});
test('Git delivery blocks incomplete plans and changed preview bindings, preserving HEAD and owner index before a fresh verified commit', async t => {
const f = fixture(t); createDeliveryProject(f); applyDeliveryFix(f); pause(f);
const manager = new TaskPlanManager(f.store), runner = new CheckRunner(f.store), delivery = new GitDelivery(f.store);
f.onCleanup(() => runner.stopAll()); f.onCleanup(() => delivery.stopAll());
const checkPlan = await runner.plan(f.session), check = await (await runner.start(f.session, checkPlan.id)).promise; assert.equal(check.status, 'passed');
const plan = await save(manager, f.session, [checksStep()]);
await assert.rejects(delivery.plan(f.session), /任务计划/);
const pending = await new DeliveryReporter(f.store).create(f.session); assert.equal(pending.report.status, 'needs_plan_verification');
await verify(manager, f.session, plan, 'check', check.id); const preview = await delivery.plan(f.session);
const head = deliveryGit(f, ['rev-parse', 'HEAD']).trim(), indexPath = path.join(deliveryGit(f, ['rev-parse', '--absolute-git-dir']).trim(), 'index'), originalIndex = fs.readFileSync(indexPath);
const next = await save(manager, f.session, [checksStep(), readingStep('read', ['check'])], 1);
const rejected = await (await delivery.start(f.session, preview.id)).promise;
assert.equal(rejected.status, 'stale'); assert.equal(deliveryGit(f, ['rev-parse', 'HEAD']).trim(), head); assert.deepEqual(fs.readFileSync(indexPath), originalIndex);
await verify(manager, f.session, next, 'check', check.id); await verify(manager, f.session, next, 'read', completeRead(f).id);
const fresh = await delivery.plan(f.session); assert.notEqual(fresh.taskPlanBindingSha256, preview.taskPlanBindingSha256);
const delivered = await (await delivery.start(f.session, fresh.id)).promise; assert.equal(delivered.status, 'completed', delivered.summary);
const report = await new DeliveryReporter(f.store).create(f.session); assert.equal(report.report.taskPlan.all_verified, true); assert.equal(report.report.status, 'verified_committed');
assert.equal(report.report.taskPlanHistory.length, 2); assert.equal(report.report.taskProofs.length, 3);
assert.match(f.store.artifactStore.read(f.store.core.artifact.get(report.markdownArtifactId)), /执行计划与实际核验/);
});
test('the runtime supplies owned read IDs and completes a plan only after original step evidence verification', async t => {
const f = fixture(t), provider = new Provider(), runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
let phase = 0, planId, readId;
provider.complete = async (_config, messages, _project, _signal, _progress, _requestPlan, tools) => {
assert.ok(tools.some(tool => tool.function.name === 'verify_task_step'));
const last = messages.filter(message => message.role === 'tool').at(-1), result = last ? JSON.parse(last.content) : null;
let calls;
if (phase === 0) calls = [call('runtime-plan', 'plan_task', { expected_revision: 0, steps: [readingStep()] })];
if (phase === 1) { planId = result.plan_id; calls = [call('runtime-read', 'read_file', { path: 'README.md' })]; }
if (phase === 2) { readId = result.tool_invocation_id; assert.ok(readId); calls = [call('runtime-proof', 'verify_task_step', { plan_id: planId, expected_revision: 1, step_key: 'read', evidence_id: readId })]; }
phase++; return { message: { role: 'assistant', content: calls ? '' : '原步骤核验完成。', ...(calls ? { tool_calls: calls } : {}) }, usage: { prompt_tokens: 120, completion_tokens: 20 } };
};
runtime.start(f.session.id, '按实际读取核验一项步骤'); await runtime.active.get(f.session.id).promise;
assert.equal(f.session.status, 'completed'); assert.equal((await runtime.taskPlanner().inspect(f.session)).all_verified, true);
assert.equal(f.store.core.tool.get(readId).tool, 'read_file'); assert.equal(phase, 4); assertToolPairs(f.session.providerMessages);
});
test('premature model completion pauses the original Task and resume preserves the existing plan without replay', async t => {
const f = fixture(t), provider = new Provider(), runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
let phase = 0, planId;
provider.complete = async (_config, messages) => {
const result = JSON.parse(messages.filter(message => message.role === 'tool').at(-1)?.content ?? '{}'); let calls;
if (phase === 0) calls = [call('early-plan', 'plan_task', { expected_revision: 0, steps: [readingStep()] })];
if (phase === 1) planId = result.plan_id;
if (phase === 2) calls = [call('resumed-read', 'read_file', { path: 'README.md' })];
if (phase === 3) calls = [call('resumed-proof', 'verify_task_step', { plan_id: planId, expected_revision: 1, step_key: 'read', evidence_id: result.tool_invocation_id })];
phase++; return { message: { role: 'assistant', content: calls ? '' : '模型自述结束。', ...(calls ? { tool_calls: calls } : {}) }, usage: { prompt_tokens: 120, completion_tokens: 20 } };
};
runtime.start(f.session.id, '核验读取后再完成任务'); await runtime.active.get(f.session.id).promise;
assert.equal(f.session.status, 'paused'); assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'task_plan_incomplete');
const taskId = f.session.taskId, prefix = structuredClone(f.session.providerMessages);
runtime.start(f.session.id, '', true); await runtime.active.get(f.session.id).promise;
assert.equal(f.session.taskId, taskId); assert.equal(f.session.status, 'completed'); assert.equal(f.store.core.task_plan.size, 1);
assert.deepEqual(f.session.providerMessages.slice(0, prefix.length), prefix); assertToolPairs(f.session.providerMessages);
});
test('plan operations participate in project activity and orderly shutdown', async t => {
const f = fixture(t); beginPlanTask(f); const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
let release; const gate = new Promise(resolve => { release = resolve; });
const pending = runtime.taskPlanner().mutate(f.session, 'user', () => gate);
assert.equal(runtime.isActive(f.session.id), true); assert.equal(runtime.projectHasActivity(f.project.id), true); assert.equal(runtime.hasActivity(), true);
assert.throws(() => runtime.start(f.session.id, '不能在核验时覆盖任务'), /已有任务/);
const stopped = runtime.stopAll(); release(); await pending; await stopped; assert.equal(runtime.hasActivity(), false);
});
for (const operation of ['plan', 'proof']) for (const point of ['before', 'after']) test(`actual process exit ${point} ${operation} save restores only committed plan evidence without replay`, async t => {
const f = fixture(t); beginPlanTask(f); const evidence = completeRead(f), manager = new TaskPlanManager(f.store);
const plan = operation === 'proof' ? await save(manager, f.session, [readingStep()]) : null;
const inputFile = path.join(f.root, 'crash-' + randomUUID() + '.json');
fs.writeFileSync(inputFile, JSON.stringify({ data: f.data, sessionId: f.session.id, operation, point, planId: plan?.id, evidenceId: evidence.id })); f.store.close();
const exited = spawnSync(process.execPath, ['tests/fixtures/task-plan-crash-worker.mjs', inputFile], { windowsHide: true, timeout: 10000, encoding: 'utf8' });
assert.equal(exited.status, 71, exited.stderr + exited.stdout);
const restored = new Store(f.data); f.onCleanup(() => restored.close());
const current = restored.session(f.session.id), view = await new TaskPlanManager(restored).inspect(current);
assert.equal(restored.core.tool.size, 1); assert.equal(restored.core.tool.get(evidence.id).state, 'completed');
assert.equal(view.configured, operation === 'proof' || point === 'after');
assert.equal(view.all_verified, operation === 'proof' && point === 'after');
assertToolPairs(current.providerMessages);
});