feat: add owned dependency preparation and reproducible environment evidence
This commit is contained in:
@@ -1,5 +1,12 @@
|
||||
# Agent Workbench 更新记录
|
||||
|
||||
## 1.21.0 · 工程环境与可复现依赖(发行验收中)
|
||||
|
||||
- 任务记录增加Node/npm及Python/pytest只读环境诊断,显示锁文件、缺失依赖和实际运行器身份。
|
||||
- 所属独立工作区支持固定npm ci计划、下载源与安装脚本审查、明确审批、停止和原日志;中断结果需核对,计划只执行一次。
|
||||
- 工程检查与交付绑定实际依赖字节和原安装凭据;固定评测核对原版与候选环境差异。
|
||||
- 真实发行与正式部署结果以本阶段验收收据为准,原用户项目、连接和历史保持。
|
||||
|
||||
## 1.20.3 · 模型原生参数与错误保留
|
||||
|
||||
- 错误详情与模型请求账本保留上游原文、code/type、请求ID和原Retry-After,并标明本地超时/协议核验与上游失败的来源。
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# 本地 Agent 工作台
|
||||
|
||||
1.21.0工程环境与固定依赖准备已进入发行验收:任务记录增加只读环境诊断、独立工作区npm ci审批/停止/原日志、中断核对,以及检查和评测的实际依赖身份。正式服务暂时仍为1.20.3,验收完成后保留状态升级。见[使用说明](docs/ENVIRONMENT-PREPARATION.md)、[阶段验收](docs/QA-1.21.md)与[回顾](docs/RETROSPECTIVE-1.21.md)。
|
||||
|
||||
1.20.3已本地上线:上游错误详情/原文下载、原生参数配置和按原因处理429。见[工作台](http://127.0.0.1:4318/?release=1.20.3)、[验收](docs/QA-1.20.3.md)、[回顾](docs/RETROSPECTIVE-1.20.3.md)和[发行身份](docs/model-fidelity-release-identity.json)。内置浏览器已明确为[1.22阶段](docs/PLAN-1.22.md),当前已有静态工程页面验收。
|
||||
|
||||
上一维护版1.20.2修复固定60秒生成截止,新增模型中心「等待时限」;其部署历史及原连接/记录保持。见[工作台](http://127.0.0.1:4318/?release=1.20.2)、[验收](docs/QA-1.20.2.md)、[回顾](docs/RETROSPECTIVE-1.20.2.md)和[发行身份](docs/model-wait-release-identity.json)。历史失败仍按原记录显示,手动续接的新请求使用新时限,任务总预算仍优先。
|
||||
|
||||
@@ -211,3 +211,6 @@ C01/C02/C07/C09/C11/C13/C15/C24:每批1–3固定样本、原测试保护、
|
||||
| Purge/路由/worker收益 | 与同题基线比较;增加错误修改或隐性人工工作不能算收益 |
|
||||
|
||||
每项能力记录:`能力ID → 研究来源 → 实现commit → 契约结果 → 工程任务/Run → 剩余限制`。阶段验收和发布时间以这些记录为依据。
|
||||
# 1.21 当前进度
|
||||
|
||||
工程环境诊断、管理工作区的固定npm依赖计划/审批/执行/停止/unknown核对、执行后诊断和实际依赖绑定已实现,正在完成发行验收;尚未正式切换1.20.3服务。已有依赖与本系统准备的依赖分别记录来源,安装完成不等于检查通过;真实React原版失败/候选9测试/类型检查/构建及Python2测试已通过,范围见[说明](ENVIRONMENT-PREPARATION.md)与[验收](QA-1.21.md)。通用内置浏览器仍为1.22计划。
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# 工程环境与依赖准备
|
||||
|
||||
在任务记录中打开「工程环境与依赖」,先诊断,再创建并核对准备计划。诊断不会安装软件、运行项目脚本或导入pytest。Node/npm来自工作台实际宿主;Python沿用已有解释器识别和审批后检查机制。实际二进制、声明、锁文件和依赖文件的SHA-256保存在原工件中。
|
||||
|
||||
## npm准备流程
|
||||
|
||||
1. 在任务记录创建并打开工作台管理的独立Git工作区。来源只取已提交版本,原项目已有修改保留。
|
||||
2. 诊断声明与现有依赖。首版准备器支持npm package-lock v2/v3、固定HTTP包下载及sha512校验;生产只接受无凭据的HTTPS注册源。pnpm/yarn/bun、workspace/file/git依赖、shrinkwrap、项目或父目录.npmrc、没有完整锁文件的工程需要先人工处理。
|
||||
3. 核对实际Node/npm、固定npm ci参数、工作区、下载注册源与300秒时限。默认跳过生命周期脚本;允许脚本需要明确选择并审批。根工程脚本会显示;锁文件标记的依赖脚本仅能在下载后取得正文,允许脚本代表允许这些安装脚本以本机账户执行。
|
||||
4. 审批后执行一次。配置和下载缓存位于工作台数据目录,使用独立空user/global配置;不继承未知宿主环境变量,不切换下载源或自动重放失败。离线模式只使用该工作区的缓存,缓存缺失保留真实错误。
|
||||
5. 查看退出码、原日志和实际依赖身份,再识别、确认并执行工程检查。安装成功不表示测试、类型检查或构建通过。
|
||||
|
||||
锁文件、声明、运行时、工作区、源码或原依赖变化后,旧准备计划失效。停止保留部分依赖和日志;再次尝试需要新计划。宿主中断记为unknown,原结果保持,先通过「核对中断现场」只读核对原进程和当前环境;仍有所属进程或无法核对时继续阻塞,不按历史PID杀进程。
|
||||
|
||||
## 检查和评测证据
|
||||
|
||||
新npm检查封存实际依赖文件快照,执行前后核对环境,交付前再次验证。空的构建缓存目录不影响文件身份;所有目录仍检查链接、替换、层数和条目上限,新增缓存文件或依赖内容变化会使旧结果失效。已准备环境引用原计划、审批、日志和结果工件;已有环境明确没有所属安装凭据。依赖字节变化不能继续复用原通过结果。
|
||||
|
||||
固定评测可分别打开原版和候选任务准备环境。两侧声明与Node/npm输入一致,开始候选前对照原版检查的实际依赖字节;报告缺少相同输入或原工件时保留不可比较原因和全部失败,不把模型回答算工程成功。历史记录不补造新环境证据。
|
||||
|
||||
Python本阶段提供解释器/pytest元数据与声明诊断,继续使用已有unittest/pytest结构化检查,不自动pip安装。未执行项目解释器时不声称已核对其版本。Node依赖快照上限为40,000项、512MiB、100层;超过上限或含外部链接明确显示无法完整核验。直接依赖存在和版本诊断不替代实际模块加载及项目检查。npm缓存是派生下载材料,所有安装仍需锁文件完整性核验。
|
||||
|
||||
这些操作以本机账户执行,不是操作系统沙箱。移动伴随端仍沿用原任务审批范围;通用内置浏览器属于1.22计划。
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# 后续执行计划
|
||||
|
||||
最新执行顺序:1.20.3模型错误保留与现有协议原生参数已本地上线 → [1.21工程依赖与可复现环境](PLAN-1.21.md) → [1.22工作台内置浏览器](PLAN-1.22.md)。1.10已有静态构建的真实Edge页面验收,1.22才是项目开发预览、桌面内嵌标签页与可观察/停止的通用网站操作;Codex右侧浏览器不算本产品内置能力。
|
||||
最新执行顺序:1.20.3模型错误保留与现有协议原生参数已本地上线 → [1.21工程依赖与可复现环境](PLAN-1.21.md)正在发行验收 → [1.22工作台内置浏览器](PLAN-1.22.md)。本轮A–E实现及真实工程/新UI已验证,继续完整回归、独立发行和保留状态升级,见[QA-1.21](QA-1.21.md)。1.10已有静态构建的真实Edge页面验收,1.22才是项目开发预览、桌面内嵌标签页与可观察/停止的通用网站操作;Codex右侧浏览器不算本产品内置能力。以下旧版段落保留其当时状态,不覆盖本行最新进度。
|
||||
|
||||
新增接入要求按[模型能力与错误信息保留方案](MODEL-FIDELITY-PLAN.md)执行:1.20.3已本地交付有界HTTP/SSE原错误、上游request ID、原code/type与Retry-After及现有Chat/Responses原生参数;实际验证/部署以[QA-1.20.3](QA-1.20.3.md)为准。更多供应商参数与模态仍逐项验证,不能称为全能力透传。原失败不回写,本机ID与上游ID分开,不把中文解释当原文。
|
||||
|
||||
|
||||
+5
-3
@@ -1,10 +1,10 @@
|
||||
# 1.21 后续方案:工程依赖与可复现环境
|
||||
|
||||
本文件是1.20之后的方案,不表示已经实现。1.20先收齐完整回归、独立发行、保留状态升级和回顾,再开始此阶段。真实模型工程与Purge收益继续按原选择单独验收。
|
||||
本阶段已进入实现及发行验收,当前状态见[1.21验收](QA-1.21.md)。A–E已接入;F在核对真实工程、历史回归和独立发行。正式服务在通过发行门槛前保持1.20.3。真实模型工程与Purge收益继续按原选择单独验收。
|
||||
|
||||
当前顺序调整:react-source真实案例已按[1.20.1验收](QA-1.20.1.md)完成系统修复及保留状态本地升级,原案例事实和失败历史保持。本方案、安装性能与界面可读性待办保留,尚未开始新实现;恢复后每切片独立验收、及时回顾和本地Git。真实模型工程复验单列,不续跑原无需测试任务或改写其历史消费。
|
||||
前置修复已完成:react-source真实案例按[1.20.1验收](QA-1.20.1.md)完成系统修复及保留状态本地升级,原案例事实和失败历史保持;1.20.2/1.20.3也已交付。安装性能与界面可读性作为独立待办;每切片独立验收、回顾和本地Git。真实模型工程复验单列,不续跑原无需测试任务或改写其历史消费。
|
||||
|
||||
审查已形成[完整报告](CASE-REACT-SOURCE-2026-11-01.md)和[证据摘要](CASE-REACT-SOURCE-EVIDENCE.json)。下一实施顺序以报告A–F为前置:原目标与诊断续接、审查动作、空参数兼容/失败用量、语义无进展、完成状态/实际路由及场景回归。修复验收与回顾后再进入本方案A;本文件的依赖准备功能尚未实现。
|
||||
历史审查见[完整报告](CASE-REACT-SOURCE-2026-11-01.md)和[证据摘要](CASE-REACT-SOURCE-EVIDENCE.json)。报告A–F修复已作为本阶段前置完成;本轮继续保留这些行为,并增加工程环境诊断和所属依赖准备。
|
||||
|
||||
## 要解决的具体缺口
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
|
||||
## 实施切片与验收
|
||||
|
||||
2026-11-01开始实施(分支`feat/reproducible-env-1.21`)。具体契约:沿用现有managed-worktree,不在父工程自动安装;首版支持npm package-lock v2/v3,固定Node/npm、独立配置/缓存和显式注册源,默认跳过生命周期脚本,可单独确认允许。Python先提供不执行项目代码的解释器/pytest与声明诊断,继续沿用已有Python检查器,不自动pip安装。准备计划、用户审批、所属进程、原日志与依赖字节身份独立持久化;中断置unknown并要求核对,原计划不重放。工程检查绑定实际依赖快照,原版/候选对照绑定相同声明和运行时输入,准备成功不能代替工程通过。
|
||||
|
||||
| 切片 | 实现 | 完成门槛 |
|
||||
| --- | --- | --- |
|
||||
| A 只读环境诊断 | 识别实际Node/npm或Python/pytest、声明/lockfile、依赖缺失与现有环境来源 | 缺失/不支持明确分类,诊断不安装或改配置;路径与真实二进制SHA绑定 |
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# 1.21 工程环境与依赖准备验收
|
||||
|
||||
当前为发行验收记录,正式服务尚未升级。基线e259ddc,分支`feat/reproducible-env-1.21`。原1.20.3/PID36552、Provider和用户任务保持;研发仅使用独立工程、数据、端口和自有HTTP响应。
|
||||
|
||||
## 实际能力
|
||||
|
||||
任务记录内可只读诊断Node/npm、Python/pytest元数据、声明、锁文件和实际依赖。管理的独立Git工作区支持一次性的npm ci计划,核对下载源、生命周期脚本策略、原输入后审批执行;可停止并保留所属进程、原日志和真实退出结果。中断结果保留unknown,需只读核对,原命令不自动重放。安装结束保存新诊断,后续检查和交付绑定依赖字节及原准备工件。使用方式见[说明](ENVIRONMENT-PREPARATION.md)。
|
||||
|
||||
## 已执行
|
||||
|
||||
| 层次 | 实际结果 | 原记录 |
|
||||
| --- | --- | --- |
|
||||
| 环境及评测关联回归 | 31/31通过,包含空目录与新增代码文件的不同处理;该轮早于最后的诊断刷新改动,最终源码另验 | `.qa/environment-review-regression.tap` |
|
||||
| 真实React/Python工程 | 两个工作区实际npm ci,原版失败保留,候选9项测试/类型检查/构建通过,Python2项通过;父工程未安装依赖 | `.qa/environment-projects-third.log`及其result/reports原件 |
|
||||
| 新环境UI | 桌面/390px、安装失败、停止、锁文件变化拒绝、unknown核对和迟到响应7组通过;已观察执行后新诊断ready | `.qa/environment-ui-57251e52-d965-4ed0-addf-b4abd6b9c628/result.json` |
|
||||
| 升级专项 | 1.21登记后原进程两次升级及0.1旧版升级2组通过 | `.qa/environment-upgrade-fixed.tap` |
|
||||
| 最终发行 | 历史UI、冻结源码全套、归档、便携、同载荷安装及保留状态正式升级在执行,未完成项不计通过 | 后续按原收据追加 |
|
||||
|
||||
## 回顾与修复
|
||||
|
||||
真实React第二轮发现Vite留下空`.vite-temp`目录被误判为依赖变化,原失败保留。修正后仅实际文件/链接决定环境身份,所有目录仍检查替换、链接和遍历上限;新增代码文件或修改依赖仍失效。界面回看发现准备成功后仍展示旧诊断,已改为保存执行后诊断,核心流程再验通过。
|
||||
|
||||
当前shell的默认Node来自其它工具的16版;npm会通过PATH启动子Node。一次研发构建因此在Vite入口失败,固定本次命令的Node24目录后通过;没有改系统PATH或正式宿主,原失败日志保留。
|
||||
|
||||
## 交付边界
|
||||
|
||||
首版准备npm package-lock v2/v3,生产仅接受无凭据HTTPS根注册源、固定下载与sha512;不静默改源或自动重试。Python暂不自动pip安装。现有权限为本机账户权限,独立工作区不代表操作系统沙箱。完整协议、多包管理器和通用内置浏览器另排,下一阶段见[1.22方案](PLAN-1.22.md)。本轮真实模型请求为0,固定HTTP与实际工程检查不代表模型自主完成率或Purge收益。
|
||||
@@ -0,0 +1,9 @@
|
||||
# 1.21 阶段回顾
|
||||
|
||||
本阶段围绕实际交付缺口推进:新工程不能只靠QA手动准备依赖,也不能把环境缺失报成代码失败。现有任务内核、Git工作区、审批、所属进程和工件继续复用;准备结果与工程检查分别判定。
|
||||
|
||||
真实工程验收发现两处不能仅靠接口测试确认的问题:Vite构建留下空目录引起错误失效,安装完成后界面仍展示准备前诊断。两处均已修复并保留原失败及新结果;新增实际依赖文件、外部链接和不完整扫描仍会阻止复用。
|
||||
|
||||
升级门槛补入1.21支持,固定9229调试端口的测试与其余全套分组串行,避免验收自己争用端口。一般测试仍使用独立目录和端口、并发上限2;全部原分母与日志保留,不通过改写旧失败来制造通过。
|
||||
|
||||
最终发行和正式数据核对仍在执行,完成事实以[验收记录](QA-1.21.md)与原收据为准。后续优先1.22项目开发服务预览和桌面浏览区;安装载荷体积/校验进度独立推进,不借本阶段改动扩大功能宣称。
|
||||
@@ -805,3 +805,11 @@ Responses已采用typed Items、call_id原配对和同线路加密reasoning续
|
||||
1.20.0完整本地交付:固定工程评测、同源原版/候选、全部尝试与原日志对照、显式采纳及父审查/检查/Git。独立源码604/604、28类210组界面、四类工程14节点、随包与同载荷安装7组、正式26页及原生回看通过。原PID36552/Provider、17项目/30全部会话/3144记录/5986事件、全部表每行/导出/模型中心及1824工件记录/1721去重文件原字节保持,9229关闭。本轮真实模型请求0;固定HTTP不代表自主推理收益或全仓自升级。
|
||||
|
||||
同源原检查、失败分母与人工介入是候选质量判断的依据。原函数的状态汇总问题已用来源绑定模块证明并修复;未将固定响应或自身模块试点推广为模型推理提升。发行服务版本必须与包身份同时断言,环境缺失需先诊断而非误算代码失败。
|
||||
# 1.21 接续发现
|
||||
|
||||
基线e259ddc,正式1.20.3/PID36552,工作区干净。已有Task/Run、隔离worktree、npm/Python真实检查、审批和停止;尚无产品化工程依赖准备。1.21优先固定npm lockfile,诊断与执行分开,准备操作绑定所属工作区及运行器/锁文件/来源,检查不将缺依赖误判为源码错误。广泛回归必须显式使用既有独立Python/pytest8.4.2,固定9229资源的升级测试串行;原1.20.3失败证据不重写。
|
||||
# 1.21接续回顾:实际工程失败与运行时
|
||||
|
||||
2026-11-01恢复核对:1.21迁移登记已补,`.qa/environment-upgrade-fixed.tap`两组真实原进程升级通过。`.qa/environment-projects-second.log`仍记录真实React流程失败:Vite只新增空`node_modules/.vite-temp`目录,原全目录身份误判为依赖变化。改为实际文件/链接身份,空目录不进入摘要或文件数,但全部目录继续检查链接/替换/遍历预算;新增缓存代码或修改依赖仍失效。新增行为回归并重跑原React/真实Python流程,不覆盖旧失败。
|
||||
|
||||
当前shell默认`node`仍为微信工具内Node16,研发与QA必须显式使用`tools/node-v24.22.1-win-x64/node.exe`;正式服务沿用PID36552,不因此改其宿主。恢复读取中出现输出过量及Windows rg通配路径错误,已改为精确路径和短段;截断输出不计作完整审阅。
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.20.3",
|
||||
"version": "1.21.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.20.3",
|
||||
"version": "1.21.0",
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
"@peculiar/x509": "3.1.0",
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "local-agent-workbench",
|
||||
"version": "1.20.3",
|
||||
"version": "1.21.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
|
||||
@@ -46,7 +46,8 @@
|
||||
"verify:model-protocols": "node scripts/verify-model-protocols-ui.mjs",
|
||||
"verify:evaluations": "node scripts/verify-evaluations-ui.mjs",
|
||||
"verify:evaluations-projects": "node scripts/verify-evaluations-projects.mjs",
|
||||
"verify:evaluations-release": "node scripts/verify-evaluations-release.mjs"
|
||||
"verify:evaluations-release": "node scripts/verify-evaluations-release.mjs",
|
||||
"verify:environment": "node scripts/verify-environment-ui.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
|
||||
+13
@@ -1,5 +1,9 @@
|
||||
# 统一执行进度
|
||||
|
||||
## 1.21 工程依赖与可复现环境(进行中)
|
||||
|
||||
用户授权继续全量开发并强调回顾、验证、修复。恢复核对e259ddc/Git干净,正式健康1.20.3/PID36552。沿用planning-with-files、product-ui-ux与既有UI风格;新分支按PLAN-1.21 A–F实施。1.20.3的已完成验收与原失败保持,1.22浏览器继续作为后续阶段。初次批量读取输出较长截断,后续按真实模块和短段读取,不将截断内容计为完整审阅。
|
||||
|
||||
## 1.20.3 模型错误和原生参数上线(已完成)
|
||||
|
||||
证据提交后逐个Git blob与工作区原字节核对通过,108份证据、当前32会话/3239记录/6229事件/1780工件和原连接稳定。初次暂存diff检查因原TAP失败堆栈的空白行报告尾随空格;保留原日志字节,补TAP binary属性后重新核对完整提交范围,不清洗原证据。前一ACCEPTANCE与最终Git字节收据分别保留,正式发行不变。
|
||||
@@ -1043,6 +1047,15 @@ D第四轮7组通过,桌面/390px原对照与实际候选证据已回看;前
|
||||
|
||||
## 1.20完整本地交付
|
||||
|
||||
## 1.21实施接续
|
||||
|
||||
恢复核对分支feat/reproducible-env-1.21,基线e259ddc,当前仅计划文件改动。读取Store、Runtime、工作区、检查与评测契约;确定复用managed-worktree,增加独立环境诊断/计划/执行记录和所属进程执行器。只读路径猜测command-runner/server-tools与test目录不存在、几次过量输出被截断,已按实际文件短段核对,均未改变产品或正式数据。没有读取凭据或发起真实模型请求。
|
||||
|
||||
A–C首实现已写入:只读Node/npm/Python/pytest诊断、锁定npm ci、隔离配置/缓存、显式脚本策略、单次计划审批、所属进程/停止/原日志、重启unknown和显式只读核对。D检查绑定实际依赖字节与原准备工件、评测同源环境正在验证;E任务记录界面和390px流程已构建。原相关35/35通过;新环境首轮9/11,两个验收器错误(局部变量遮蔽、HTTP使用未重建的旧dist-server)修正后三项恢复/API/Python复验通过。原失败TAP保留。一次集成脚本换行匹配失败只改了两份契约;核对后调整匹配完成,未触碰正式服务。一次本地npm CLI路径猜错导致构建未启动,改用固定Node目录的npm后构建通过。一次types补丁匹配拒绝,原子无改动,已按实际接口追加。
|
||||
|
||||
1.20.0完整本地交付:固定工程评测、同源原版/候选、全部尝试与原日志对照、显式采纳及父审查/检查/Git。独立源码604/604、28类210组界面、四类工程14节点、随包与同载荷安装7组、正式26页及原生回看通过。原PID36552/Provider、17项目/30全部会话/3144记录/5986事件、全部表每行/导出/模型中心及1824工件记录/1721去重文件原字节保持,9229关闭。本轮真实模型请求0;固定HTTP不代表自主推理收益或全仓自升级。
|
||||
|
||||
完整F原件、字节清单和发行身份已封存;不重写旧失败或不可变安装包。下一1.21仅方案,优先工程依赖与可复现环境。
|
||||
# 1.21接续:回顾、修复与最终验证
|
||||
|
||||
2026-11-01核对未提交实现和原始验收。环境专项原13/13、UI实际7组通过,迁移补登记后升级2/2通过;真实工程原轮仍失败,不能认定D完成。定位Vite空临时目录误判后修正身份逻辑,保留目录预算和外部链接拒绝,新增空目录与实际代码变化的行为验证。当前串行环境/评测专项运行中,后续重跑原React/Python并完成冻结发行。正式1.20.3/PID36552、Provider与用户项目未修改,真实模型请求0。
|
||||
|
||||
@@ -14,6 +14,7 @@ const prefixes = Object.freeze({
|
||||
'1.19.0': 'project-cache',
|
||||
'1.20.0': 'engineering-evals',
|
||||
'1.20.1': 'task-control',
|
||||
'1.21.0': 'reproducible-env',
|
||||
});
|
||||
export function releaseEvidencePrefix(version) {
|
||||
const prefix = prefixes[version];
|
||||
|
||||
@@ -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', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3'].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', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.20.2', '1.20.3', '1.21.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 = [];
|
||||
|
||||
+20
-17
@@ -9,31 +9,32 @@ import { randomUUID } from 'node:crypto';
|
||||
if (process.argv.slice(2).some(value => value !== '--help')) throw new Error('Unsupported argument; use --help.');
|
||||
if (process.argv.includes('--help')) { console.log('node scripts/verify-all-ui.mjs - run serial desktop/390px checks in independent local hosts; use explicit QA Python/Harness/Purge source paths for 1.15.'); process.exit(0); }
|
||||
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', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version), 'Review evidence paths when introducing the next release.');
|
||||
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', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version), 'Review evidence paths when introducing the next release.');
|
||||
const prefix = releaseEvidencePrefix(version), resultFile = `.qa/${prefix}-all-ui-validation.json`, results = [];
|
||||
const qaEnvironment = Object.fromEntries(['AGENT_WORKBENCH_TEST_PYTHON', 'AGENT_WORKBENCH_DEEPSEEK_ROOT', 'AGENT_WORKBENCH_PURGE_178_ROOT', 'AGENT_WORKBENCH_PURGE_181_ROOT']
|
||||
.filter(name => process.env[name]).map(name => [name, process.env[name]]));
|
||||
for (const [name, value] of Object.entries(qaEnvironment)) assert.ok(path.isAbsolute(value) && fs.existsSync(value), 'Use an existing absolute QA runtime/source path: ' + name);
|
||||
const cases = [
|
||||
...(['1.20.0', '1.20.1'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
|
||||
...(['1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
|
||||
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-vision-ui.mjs', null]] : []),
|
||||
...(['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-model-protocols-ui.mjs', null]] : []),
|
||||
...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-companion-ui.mjs', null]] : []),
|
||||
...(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-controlled-ui.mjs', null], ['verify-purge-ui.mjs', null]] : []),
|
||||
...(['1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-workers-ui.mjs', null]] : []),
|
||||
...(['1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []),
|
||||
...(['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []),
|
||||
...(['1.21.0'].includes(version)?[['verify-environment-ui.mjs',null],['verify-model-fidelity-ui.mjs',null],['verify-model-wait-ui.mjs',null]]:[]),
|
||||
...(['1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
|
||||
...(['1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
|
||||
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-vision-ui.mjs', null]] : []),
|
||||
...(['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-model-protocols-ui.mjs', null]] : []),
|
||||
...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-companion-ui.mjs', null]] : []),
|
||||
...(['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-controlled-ui.mjs', null], ['verify-purge-ui.mjs', null]] : []),
|
||||
...(['1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-workers-ui.mjs', null]] : []),
|
||||
...(['1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []),
|
||||
...(['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.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', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].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', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].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', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []),
|
||||
...(['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []),
|
||||
...(['1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(version) ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []),
|
||||
...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.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', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.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', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.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', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []),
|
||||
...(['1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0'].includes(version) ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []),
|
||||
];
|
||||
fs.mkdirSync('.qa', { recursive: true });
|
||||
const externalHost = new Set(['verify-ui.mjs', 'verify-diagnostics-ui.mjs', 'verify-execution-ui.mjs', 'verify-index-ui.mjs']);
|
||||
@@ -79,7 +80,8 @@ for (const [script, fixedProof] of cases) {
|
||||
child.once('close', code => { clearTimeout(timer); code === 0 && !timedOut ? resolve(tail) : reject(new Error(script + (timedOut ? ' timed out' : ' failed (' + code + ')') + ': ' + tail)); });
|
||||
});
|
||||
stream.end();
|
||||
const directory = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1].trim();
|
||||
const summary = output.trim().split(/\r?\n/).findLast(line => line.startsWith('{"success":'));
|
||||
const directory = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1].trim() || (summary ? JSON.parse(summary).directory : null);
|
||||
const proof = fixedProof || (directory && path.join(directory, 'result.json'));
|
||||
assert.ok(proof, 'Verifier must identify its current evidence.');
|
||||
if (!fixedProof) {
|
||||
@@ -88,10 +90,11 @@ for (const [script, fixedProof] of cases) {
|
||||
}
|
||||
const evidence = JSON.parse(fs.readFileSync(proof, 'utf8'));
|
||||
assert.notEqual(evidence.success, false); assert.notEqual(evidence.passed, false); if (evidence.version) assert.equal(evidence.version, version);
|
||||
const passed = [evidence.passed, evidence.cases, evidence.assertions].find(Array.isArray);
|
||||
const passed = [evidence.passed, evidence.cases, evidence.assertions, evidence.checks].find(Array.isArray);
|
||||
assert.ok(Array.isArray(passed) && passed.length > 0);
|
||||
const errors = evidence.pageErrors ?? [], failures = evidence.requestFailures ?? [];
|
||||
assert.equal(errors.length, 0); assert.equal(failures.length, 0);
|
||||
assert.deepEqual(evidence.errors ?? [], []);
|
||||
const saved = ['verify-controlled-ui.mjs', 'verify-purge-ui.mjs'].includes(script) ? `docs/${prefix}-${script.replace('verify-', '').replace('-ui.mjs', '')}-final-ui-validation.json`
|
||||
: script === 'verify-ui.mjs' ? `docs/${prefix}-basic-ui-validation.json`
|
||||
: ['verify-workspaces-ui.mjs', 'verify-task-plans-ui.mjs'].includes(script) ? proof
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createRequire} from 'node:module';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {fixture} from '../tests/helpers.mjs';
|
||||
import {deliveryGit} from '../tests/fixtures/delivery-project.mjs';
|
||||
import {WorkspaceManager} from '../src/core/workspaces/git-workspaces.mjs';
|
||||
import {EnvironmentManager} from '../src/core/environment/environment-manager.mjs';
|
||||
import {CheckRunner} from '../src/core/check-runner.mjs';
|
||||
|
||||
const directory=path.resolve('.qa','environment-projects-'+randomUUID());fs.mkdirSync(directory,{recursive:true});
|
||||
const disposers=[],t={after:fn=>disposers.push(fn)},f=fixture(t),reports=[],requests=[];
|
||||
const hash=value=>createHash('sha256').update(value).digest('hex'),require=createRequire(import.meta.url);
|
||||
const cacache=require(path.join(path.dirname(process.execPath),'node_modules/npm/node_modules/cacache'));
|
||||
const cache=path.join(process.env.LOCALAPPDATA,'npm-cache','_cacache');
|
||||
const manifestRoot=path.resolve('benchmarks/react-delivery-v1/baseline');fs.cpSync(manifestRoot,f.projectRoot,{recursive:true,filter:file=>!file.split(path.sep).includes('node_modules')});
|
||||
const lockFile=path.join(f.projectRoot,'package-lock.json'),originalLock=fs.readFileSync(lockFile),lock=JSON.parse(originalLock),tarballs=new Map();
|
||||
const server=http.createServer(async(request,response)=>{
|
||||
const entry=tarballs.get(request.url);requests.push({path:request.url,integrity:entry?.integrity??null});
|
||||
if(!entry){response.writeHead(404);response.end('No owned tarball');return;}
|
||||
try{const bytes=await cacache.get.byDigest(cache,entry.integrity);response.writeHead(200,{'Content-Type':'application/octet-stream'});response.end(bytes);}
|
||||
catch{response.writeHead(503);response.end('Required integrity not in local QA download cache');}
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const registry='http://127.0.0.1:'+server.address().port+'/';
|
||||
disposers.push(()=>{server.closeAllConnections();return new Promise(resolve=>server.close(resolve));});
|
||||
for(const entry of Object.values(lock.packages))if(entry.resolved){const url=new URL(entry.resolved);assert.equal(url.origin,'https://registry.npmjs.org');assert.equal(url.username,'');
|
||||
const target='/tarballs/'+hash(entry.resolved)+'.tgz';tarballs.set(target,{integrity:entry.integrity});entry.resolved=registry+target.slice(1);}
|
||||
fs.writeFileSync(lockFile,JSON.stringify(lock,null,2));
|
||||
deliveryGit(f,['init','--initial-branch=main']);deliveryGit(f,['-c','core.autocrlf=false','add','.']);deliveryGit(f,['-c','user.name=Workbench QA','-c','user.email=qa@workbench.local','commit','-m','Own React source and integrity-bound local tarball feed']);
|
||||
const parent=f.store.beginRun(f.session,'验证真实React工程的依赖准备及原版/候选检查',false,f.store.config);f.session.status='paused';f.store.finishRun(f.session,parent);
|
||||
const workspaces=new WorkspaceManager(f.store),environment=new EnvironmentManager(f.store,{allowHttpLoopback:true}),checks=new CheckRunner(f.store);
|
||||
disposers.push(()=>workspaces.stopAll(),()=>environment.stopAll(),()=>checks.stopAll());
|
||||
async function child(label){const record=await workspaces.prepare(f.session,label);await(await workspaces.start(f.session,record.id,record.fingerprint)).promise;assert.equal(record.status,'ready',record.summary);
|
||||
const project=f.store.project(record.childProjectId),session=f.store.session(record.childSessionId),run=f.store.beginRun(session,label,false,f.store.config);session.status='paused';f.store.finishRun(session,run);return {project,session};}
|
||||
async function prepare(p){const plan=await environment.plan(p.session,{registry}),job=await(await environment.start(p.session,plan.id,plan.fingerprint,{approved:true})).promise;
|
||||
reports.push({stage:'prepare',projectId:p.project.id,plan,job});assert.equal(job.status,'prepared',job.summary+'\n'+job.logExcerpt);console.log('PASS actual React npm ci: '+job.id);return job;}
|
||||
function dependencyFiles(root,relative='node_modules'){const directory=path.join(root,relative);if(!fs.existsSync(directory))return [];
|
||||
return fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name)).flatMap(entry=>{const name=path.posix.join(relative,entry.name),target=path.join(root,name);
|
||||
return entry.isSymbolicLink()?[{path:name,link:fs.readlinkSync(target)}]:entry.isDirectory()?[{path:name,directory:true},...dependencyFiles(root,name)]:[{path:name,sha256:hash(fs.readFileSync(target))}];});}
|
||||
async function check(p,names){const before=dependencyFiles(p.project.root),plan=await checks.plan(p.session,names),job=await(await checks.start(p.session,plan.id)).promise,after=dependencyFiles(p.project.root);
|
||||
const left=new Map(before.map(row=>[row.path,JSON.stringify(row)])),right=new Map(after.map(row=>[row.path,JSON.stringify(row)]));
|
||||
const changed=[...new Set([...left.keys(),...right.keys()])].filter(name=>left.get(name)!==right.get(name));
|
||||
reports.push({stage:'checks',projectId:p.project.id,plan,job,dependencySnapshot:{before,after,changed}});if(changed.length)console.log('Observed dependency changes: '+JSON.stringify(changed));return job;}
|
||||
let result;
|
||||
try{
|
||||
const original=await child('React原版环境'),candidate=await child('React候选环境'),left=await prepare(original),right=await prepare(candidate);
|
||||
assert.equal(left.after.dependencyInputs,right.after.dependencyInputs);assert.equal(left.after.installed.sha256,right.after.installed.sha256);
|
||||
const baseline=await check(original,['test','typecheck','build']);assert.equal(baseline.status,'failed',baseline.summary);assert.ok(baseline.results.some(value=>value.tests?.failed>0));
|
||||
const app=fs.readFileSync(path.join(candidate.project.root,'src/App.tsx'),'utf8'),fixes={
|
||||
'src/query.ts':"import type { Task } from './types.ts';\nexport function selectTasks(tasks: Task[], filter: string, query: string): Task[] { const text=query.trim().toLocaleLowerCase(); return tasks.filter(task => (filter==='done'?task.done:filter==='pending'?!task.done:true)&&task.title.toLocaleLowerCase().includes(text)); }\n",
|
||||
'src/summary.ts':"import type { Task } from './types.ts';\nexport function summarizeTasks(tasks: Task[]) { return {total:tasks.length,completed:tasks.filter(task=>task.done).length,pendingHours:tasks.filter(task=>!task.done).reduce((sum,task)=>sum+task.hours,0)}; }\n",
|
||||
'src/transition.ts':"import type { Task } from './types.ts';\nexport function toggleTask(tasks: Task[], id: string): Task[] { return tasks.map(task=>task.id===id?{...task,done:!task.done}:task); }\n",
|
||||
'src/App.tsx':app.replace("toggleTask(current, 'missing')",'toggleTask(current, task.id)')};
|
||||
for(const[name,value]of Object.entries(fixes))fs.writeFileSync(path.join(candidate.project.root,name),value);
|
||||
const candidateJob=await check(candidate,['test','typecheck','build']);assert.equal(candidateJob.status,'passed',candidateJob.summary);assert.equal(candidateJob.results[0].tests.passed,9);
|
||||
assert.ok(candidateJob.environment.preparation.jobId);assert.equal(fs.existsSync(path.join(f.projectRoot,'node_modules')),false);assert.equal(hash(fs.readFileSync(lockFile)),hash(JSON.stringify(lock,null,2)));
|
||||
const pyRoot=path.join(f.root,'python-owned');fs.mkdirSync(pyRoot);fs.mkdirSync(path.join(pyRoot,'tests'));
|
||||
fs.writeFileSync(path.join(pyRoot,'pyproject.toml'),'[tool.pytest.ini_options]\ntestpaths=["tests"]\n');
|
||||
fs.writeFileSync(path.join(pyRoot,'calc.py'),'def add(a,b):\n return a+b\n');fs.writeFileSync(path.join(pyRoot,'tests/test_calc.py'),'from calc import add\ndef test_positive():\n assert add(2,3)==5\ndef test_negative():\n assert add(-2,3)==1\n');
|
||||
const project=f.store.addProject(pyRoot),session=f.store.createSession(project.id),run=f.store.beginRun(session,'实际Python环境及检查',false,f.store.config);session.status='paused';f.store.finishRun(session,run);
|
||||
const py=new EnvironmentManager(f.store,{pythonExecutable:process.env.AGENT_WORKBENCH_TEST_PYTHON}),diagnostic=await py.diagnose(session);assert.equal(diagnostic.python.pytest.version,'8.4.2');
|
||||
const runner=new CheckRunner(f.store,{pythonExecutable:process.env.AGENT_WORKBENCH_TEST_PYTHON}),plan=await runner.plan(session,['python:test','python:compile']),job=await(await runner.start(session,plan.id)).promise;
|
||||
reports.push({stage:'python',diagnostic,plan,job});assert.equal(job.status,'passed',job.summary);assert.equal(job.results[0].tests.passed,2);
|
||||
result={success:true,directory,reports:reports.length,reactOriginal:baseline.status,reactCandidate:candidateJob.status,reactTests:9,pythonTests:2,requests:requests.length,
|
||||
originalLockSha256:hash(originalLock),ownedLockSha256:hash(fs.readFileSync(lockFile)),downloadSource:'local HTTP feed of existing npm tarball bytes by locked SRI; no config/credentials or remote network',realModelRequests:0};
|
||||
}catch(error){result={success:false,error:error.stack,directory,reports:reports.length,requests:requests.length};process.exitCode=1;}
|
||||
finally{fs.writeFileSync(path.join(directory,'reports.json'),JSON.stringify({reports,requests},null,2));fs.writeFileSync(path.join(directory,'result.json'),JSON.stringify(result,null,2));console.log(JSON.stringify(result));for(const dispose of disposers.reverse())await dispose();}
|
||||
@@ -0,0 +1,71 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import {randomUUID,createHash} from 'node:crypto';
|
||||
import {chromium,expect} from 'playwright/test';
|
||||
import {fixture,launchWorkbench,until} from '../tests/helpers.mjs';
|
||||
import {environmentProject} from '../tests/fixtures/environment-project.mjs';
|
||||
import {EnvironmentManager} from '../src/core/environment/environment-manager.mjs';
|
||||
|
||||
const args=process.argv.slice(2);assert.ok(!args.length||args.length===2&&args[0]==='--app-root'&&path.isAbsolute(args[1]));
|
||||
const appRoot=args[1]??process.cwd(),directory=path.resolve('.qa','environment-ui-'+randomUUID());fs.mkdirSync(directory,{recursive:true});
|
||||
const disposers=[],t={after:fn=>disposers.push(fn)},f=fixture(t),cases={},checks=[],screenshots=[],pageErrors=[],failures=[],events=[];
|
||||
let browser,page,host,result;
|
||||
const mark=value=>{checks.push(value);console.log('PASS '+value);};
|
||||
for(const name of ['desktop','mobile','failure','stop','stale','recovery','late']) {
|
||||
let own=f;
|
||||
if(Object.keys(cases).length){const projectRoot=path.join(f.root,'project-'+name);fs.mkdirSync(projectRoot);const project=f.store.addProject(projectRoot);own={...f,projectRoot,project,session:f.store.createSession(project.id)};}
|
||||
const postinstall=name==='failure'?`node -e "console.error('OWNED_INSTALL_FAILURE');process.exit(23)"`:name==='stop'?`node -e "console.log('OWNED_WAITING');setTimeout(()=>{},60000)"`:undefined;
|
||||
const project=await environmentProject(own,{dependency:false,...(postinstall?{postinstall}:{})});project.session.title='环境验收 '+name;f.store.save(project.session);cases[name]=project;
|
||||
if(name==='recovery'){
|
||||
const manager=new EnvironmentManager(f.store),plan=await manager.plan(project.session,{offline:true});
|
||||
f.store.putRecord('environment_job',project.session,{id:randomUUID(),sessionId:project.session.id,projectId:project.project.id,taskId:project.session.taskId,runId:project.session.runId,
|
||||
planId:plan.id,planFingerprint:plan.fingerprint,status:'queued',process:null,requiresVerification:false},'environment.queued');
|
||||
}
|
||||
}
|
||||
f.store.close();
|
||||
const panel=()=>page.getByRole('region',{name:'工程环境与依赖',exact:true});
|
||||
async function choose(name){const p=cases[name];if(page.viewportSize().width<=620||!await page.locator('.project-sidebar').isVisible())await page.getByRole('button',{name:'展开项目栏',exact:true}).click();
|
||||
await page.getByLabel('当前项目',{exact:true}).selectOption(p.project.id);await expect(page.locator('.work-title h1')).toHaveText(p.session.title);
|
||||
if(page.viewportSize().width<=620&&await page.getByRole('button',{name:'收起项目栏',exact:true}).isVisible())await page.getByRole('button',{name:'收起项目栏',exact:true}).click();
|
||||
await page.getByRole('button',{name:'查看任务记录',exact:true}).click();await expect(panel()).toBeVisible();return p;}
|
||||
async function capture(name){await panel().scrollIntoViewIfNeeded();const bounds=await page.evaluate(()=>({width:innerWidth,scroll:document.documentElement.scrollWidth}));assert.ok(bounds.scroll<=bounds.width+1,'horizontal overflow '+name);
|
||||
const file=path.join(directory,name+'.png');await page.screenshot({path:file,scale:'css'});screenshots.push({path:file,sha256:createHash('sha256').update(fs.readFileSync(file)).digest('hex')});}
|
||||
async function plan({allow=false}={}){await panel().getByRole('button',{name:/诊断工程环境/}).click();await expect(panel().getByText('Node / npm',{exact:true})).toBeVisible();
|
||||
await panel().getByText('下载与脚本选项',{exact:true}).click();await panel().getByLabel('只使用本工作区的下载缓存(离线)').check();if(allow)await panel().getByLabel('允许依赖生命周期脚本').check();
|
||||
await panel().getByRole('button',{name:'创建依赖准备计划',exact:true}).click();await expect(panel().getByRole('button',{name:'核对并批准依赖准备',exact:true})).toBeVisible();}
|
||||
async function approve(){await panel().getByRole('button',{name:'核对并批准依赖准备',exact:true}).click();const dialog=page.getByRole('dialog',{name:'确认依赖准备',exact:true});await expect(dialog).toBeVisible();
|
||||
await expect(dialog.getByText('独立工作区',{exact:true})).toBeVisible();await expect(dialog.locator('pre').first()).toContainText('--offline=true');return dialog;}
|
||||
async function settled(p){let session;await until(async()=>{session=await host.api('/sessions/'+p.session.id);return session.execution.environmentJobs?.at(-1)?.finishedAt;},30000);return session;}
|
||||
try{
|
||||
host=await launchWorkbench(t,f.data,{}, {appRoot,nodePath:fs.existsSync(path.join(appRoot,'runtime','node.exe'))?path.join(appRoot,'runtime','node.exe'):process.execPath});
|
||||
assert.notEqual(new URL(host.url).port,'4318');assert.equal(host.bootstrap.config.hasKey,false);
|
||||
browser=await chromium.launch({executablePath:'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',headless:true});page=await browser.newPage({viewport:{width:1440,height:1000}});
|
||||
page.on('pageerror',error=>pageErrors.push(error.message));page.on('requestfailed',request=>{if(request.resourceType()!=='eventsource')failures.push(request.url()+': '+request.failure()?.errorText);});
|
||||
page.on('response',response=>{if(response.url().includes('/environment-'))events.push({url:response.url(),status:response.status()});});
|
||||
await page.goto(host.url);let p=await choose('desktop');await plan();let dialog=await approve();await capture('desktop-plan');
|
||||
await dialog.getByRole('button',{name:'确认执行依赖准备',exact:true}).click();let session=await settled(p);assert.equal(session.execution.environmentJobs.at(-1).status,'prepared');
|
||||
assert.equal(session.execution.environmentDiagnostics.at(-1).node.status,'ready');await expect(panel().getByText('依赖已就绪',{exact:true})).toBeVisible();
|
||||
await expect(panel().getByText('依赖准备完成',{exact:true})).toBeVisible();await capture('desktop-prepared');
|
||||
await panel().getByRole('button',{name:'查看依赖日志',exact:true}).click();await expect(page.getByRole('dialog').last()).toContainText('stdout');await page.getByRole('dialog').last().getByRole('button',{name:'关闭窗口',exact:true}).click();
|
||||
await page.reload();await page.getByRole('button',{name:'查看任务记录',exact:true}).click();await expect(panel().getByText('依赖准备完成',{exact:true})).toBeVisible();
|
||||
assert.equal(fs.existsSync(path.join(p.sourceRoot,'node_modules')),false);mark('desktop diagnosis, fixed plan, explicit approval, actual npm, original log and refresh');
|
||||
await page.setViewportSize({width:390,height:844});p=await choose('mobile');await plan();dialog=await approve();await capture('mobile-plan');await dialog.getByRole('button',{name:'确认执行依赖准备',exact:true}).click();session=await settled(p);
|
||||
assert.equal(session.execution.environmentJobs.at(-1).status,'prepared');await capture('mobile-prepared');mark('390px same real flow and bounded plan modal');
|
||||
await page.setViewportSize({width:1440,height:1000});p=await choose('failure');await plan({allow:true});dialog=await approve();await expect(dialog.getByText('允许执行根工程和依赖包安装脚本',{exact:true})).toBeVisible();
|
||||
await dialog.getByRole('button',{name:'确认执行依赖准备',exact:true}).click();session=await settled(p);assert.equal(session.execution.environmentJobs.at(-1).status,'failed');await expect(panel().getByText('准备失败',{exact:true})).toBeVisible();await capture('failure-original-log');
|
||||
assert.match(session.execution.environmentJobs.at(-1).logExcerpt,/OWNED_INSTALL_FAILURE/);mark('explicit script approval and original nonzero install failure');
|
||||
p=await choose('stop');await plan({allow:true});dialog=await approve();await dialog.getByRole('button',{name:'确认执行依赖准备',exact:true}).click();await expect(panel().locator('pre').filter({hasText:'OWNED_WAITING'})).toBeVisible();
|
||||
await panel().getByRole('button',{name:'停止依赖准备',exact:true}).click();session=await settled(p);assert.equal(session.execution.environmentJobs.at(-1).status,'cancelled',session.execution.environmentJobs.at(-1).summary);await capture('stopped-owned-process');mark('stop kills only owned npm tree and keeps cancelled logs');
|
||||
p=await choose('stale');await plan();dialog=await approve();fs.appendFileSync(path.join(p.root,'package-lock.json'),'\n');await dialog.getByRole('button',{name:'确认执行依赖准备',exact:true}).click();
|
||||
await expect(page.getByRole('alert')).toContainText('变化');assert.equal((await host.api('/sessions/'+p.session.id)).execution.environmentJobs?.length??0,0);await capture('stale-input-rejected');await dialog.getByRole('button',{name:'取消',exact:true}).click();mark('changed lock rejected before process dispatch');
|
||||
p=await choose('recovery');await expect(panel().getByText('结果待核对',{exact:true})).toBeVisible();await panel().getByRole('button',{name:'核对中断现场',exact:true}).click();await page.getByRole('dialog',{name:'核对中断的依赖准备',exact:true}).getByRole('button',{name:'确认只读核对',exact:true}).click();
|
||||
await expect(panel().getByText('已核对原进程结束并保留现场,原未知结果保持。再次执行需要新计划。',{exact:true})).toBeVisible();await capture('recovery-reconciled');mark('recovered unknown remains original unknown after explicit reconciliation');
|
||||
p=await choose('late');await panel().getByRole('button',{name:'诊断工程环境',exact:true}).click();await expect(panel().getByText('Node / npm',{exact:true})).toBeVisible();
|
||||
let release,observed,finish;const gate=new Promise(resolve=>{release=resolve;}),seen=new Promise(resolve=>{observed=resolve;}),finished=new Promise(resolve=>{finish=resolve;});
|
||||
await page.route('**/environment-plans',async route=>{const response=await route.fetch();observed();await gate;try{await route.fulfill({response});}finally{finish();}});
|
||||
await panel().getByRole('button',{name:'创建依赖准备计划',exact:true}).click();await seen;await choose('desktop');release();await finished;await page.unroute('**/environment-plans');await expect(page.locator('.work-title h1')).toHaveText(cases.desktop.session.title);mark('late plan response cannot replace another project or task');
|
||||
assert.deepEqual(pageErrors,[]);assert.deepEqual(failures,[]);const receipts={};for(const[name,p]of Object.entries(cases))receipts[name]=await host.api('/sessions/'+p.session.id);
|
||||
fs.writeFileSync(path.join(directory,'receipts.json'),JSON.stringify(receipts,null,2));result={success:true,appRoot,version:host.bootstrap.version,checks,screenshots,pageErrors,failures,events,directory,realModelRequests:0};
|
||||
}catch(error){if(page){fs.writeFileSync(path.join(directory,'failure-dom.html'),await page.content());await page.screenshot({path:path.join(directory,'failure.png')}).catch(()=>{});}result={success:false,error:error.stack,checks,screenshots,pageErrors,failures,events,directory};process.exitCode=1;}
|
||||
finally{fs.writeFileSync(path.join(directory,'result.json'),JSON.stringify(result,null,2));console.log(JSON.stringify(result));await browser?.close();for(const dispose of disposers.reverse())await dispose();}
|
||||
@@ -34,7 +34,7 @@ for (const name of Object.keys(env)) if (name.toLowerCase() === 'path') delete e
|
||||
const windowsRoot = process.env.SystemRoot || 'C:\\Windows';
|
||||
env.PATH = [windowsRoot, path.join(windowsRoot, 'System32'), path.join(windowsRoot, 'System32', 'WindowsPowerShell', 'v1.0')].join(path.delimiter);
|
||||
let externalGit = null;
|
||||
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(manifest.version)) {
|
||||
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(manifest.version)) {
|
||||
// The controlled project requires external Git. Preserve its observed binary
|
||||
// directory while keeping system Node/npm unavailable to the packaged host.
|
||||
const binary = fs.realpathSync.native(execFileSync('where.exe', ['git.exe'], { env: gitEnvironment(), encoding: 'utf8', windowsHide: true, timeout: 10000 }).trim().split(/\r?\n/)[0]);
|
||||
@@ -88,7 +88,7 @@ try {
|
||||
console.log((await launch()).trim());
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(data, 'service-info.json'), 'utf8')).pid, firstInfo.pid);
|
||||
const example = bootstrap.projects.find(project => project.id === bootstrap.exampleProjectId);
|
||||
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(manifest.version)) {
|
||||
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(manifest.version)) {
|
||||
assert.equal(path.resolve(example.root).toLowerCase(), path.join(data, 'projects', 'starter-project').toLowerCase());
|
||||
const compareTemplate = relative => { for (const entry of fs.readdirSync(path.join(appRoot, 'examples/starter-project', relative), { withFileTypes: true })) {
|
||||
const next = path.join(relative, entry.name); if (entry.isDirectory()) compareTemplate(next);
|
||||
@@ -114,7 +114,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', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(manifest.version)) {
|
||||
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.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')));
|
||||
@@ -146,7 +146,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', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(manifest.version) && process.argv.includes('--native-engines')) {
|
||||
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.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');
|
||||
@@ -166,8 +166,8 @@ 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', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
|
||||
const actualControlled = ['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(manifest.version) ? await verifyControlledApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
|
||||
const actualBrowser = ['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null;
|
||||
const actualControlled = ['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(manifest.version) ? await verifyControlledApi({ 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; } });
|
||||
for (const file of manifest.files) {
|
||||
@@ -176,7 +176,7 @@ try {
|
||||
}
|
||||
const result = { success: true, date: new Date().toISOString(), appRoot, version: manifest.version, nodeVersion: manifest.nodeVersion,
|
||||
verifiedFiles: manifest.files.length, url, reusedPid: firstInfo.pid, checks: { jobId, status: checked.status, tests: checked.results[0].tests }, actualRea, actualEngine, actualBrowser, actualControlled, externalGit,
|
||||
steps: ['manifest hashes', 'bundled Node launch', 'same-service reuse', 'packaged example and static page', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(manifest.version) ? ['starter project copied to owned user data; original template bytes matched'] : []), 'explicit command consent', 'actual bundled Node version', 'actual bundled npm check without system Node/npm', 'check log artifact', ...(actualRea.length ? ['contained REA installation and Node identity', 'actual ASAR/imports/resources', 'original Bundle and target hash binding', 'verified reuse without producer replay'] : []), 'report availability', 'graceful stop', 'every original packaged file remains unchanged'], realModel: false };
|
||||
steps: ['manifest hashes', 'bundled Node launch', 'same-service reuse', 'packaged example and static page', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(manifest.version) ? ['starter project copied to owned user data; original template bytes matched'] : []), 'explicit command consent', 'actual bundled Node version', 'actual bundled npm check without system Node/npm', 'check log artifact', ...(actualRea.length ? ['contained REA installation and Node identity', 'actual ASAR/imports/resources', 'original Bundle and target hash binding', 'verified reuse without producer replay'] : []), 'report availability', 'graceful stop', 'every original packaged file remains unchanged'], realModel: false };
|
||||
fs.writeFileSync('.qa/release-validation.json', JSON.stringify(result, null, 2));
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} finally { if (started) { try { await stop(); } catch {} } }
|
||||
|
||||
@@ -19,7 +19,7 @@ assert.ok(fs.existsSync(npmCli), 'Use Node with its bundled npm.');
|
||||
const files = (root, relative = '') => fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))
|
||||
.flatMap(entry => entry.isDirectory() ? files(root, path.join(relative, entry.name)) : [path.join(relative, entry.name)]);
|
||||
const digest = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
const buildFolders = ['dist-client', 'dist-server', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version) ? ['dist-desktop'] : [])];
|
||||
const buildFolders = ['dist-client', 'dist-server', ...(['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version) ? ['dist-desktop'] : [])];
|
||||
const expected = Object.fromEntries(buildFolders.flatMap(folder => files(path.join(workspace, folder)).map(relative => [path.join(folder, relative), digest(path.join(workspace, folder, relative))])));
|
||||
const allowedEnv = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all|AGENT_WORKBENCH_TEST_PYTHON|AGENT_WORKBENCH_DEEPSEEK_ROOT|AGENT_WORKBENCH_PURGE_ROOT)$/i;
|
||||
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => allowedEnv.test(key)));
|
||||
@@ -30,7 +30,7 @@ const directory = path.join(sourceRoot, '.qa', 'package-validation-' + randomUUI
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const inputFolders = ['src', 'tests', 'scripts', ...['benchmarks', 'public', 'examples', 'research'].filter(folder => fs.existsSync(path.join(sourceRoot, folder)))];
|
||||
const inputNames = [...inputFolders.flatMap(folder => files(path.join(sourceRoot, folder)).map(relative => path.join(folder, relative))),
|
||||
'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', ...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version) ? ['mobile.html'] : []), ...['.gitattributes', '.gitignore', 'Start-Desktop.cmd', 'Start-Workbench.cmd', 'Stop-Workbench.cmd'].filter(name => fs.existsSync(path.join(sourceRoot, name)))].sort();
|
||||
'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', ...(['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version) ? ['mobile.html'] : []), ...['.gitattributes', '.gitignore', 'Start-Desktop.cmd', 'Start-Workbench.cmd', 'Stop-Workbench.cmd'].filter(name => fs.existsSync(path.join(sourceRoot, name)))].sort();
|
||||
const snapshot = () => inputNames.map(relative => ({ path: relative.replaceAll('\\', '/'), bytes: fs.statSync(path.join(sourceRoot, relative)).size, sha256: digest(path.join(sourceRoot, relative)) }));
|
||||
const inputs = snapshot(); fs.writeFileSync(path.join(directory, 'inputs.json'), JSON.stringify(inputs, null, 2));
|
||||
let stage = 'environment preflight', python = null;
|
||||
@@ -83,7 +83,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', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.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));
|
||||
@@ -91,7 +91,7 @@ try {
|
||||
assert.ok(actualRea.results.every(item => item.rootExited === true));
|
||||
}
|
||||
let actualEngine = null;
|
||||
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version) && process.argv.includes('--native-engines')) {
|
||||
if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.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));
|
||||
@@ -99,7 +99,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', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.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));
|
||||
@@ -109,7 +109,7 @@ try {
|
||||
assert.equal(actualBrowser.modelRequests, 0);
|
||||
}
|
||||
let actualControlled = null;
|
||||
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.14.0', '1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'compiled controlled-engine delivery';
|
||||
const output = await run(['scripts/verify-controlled-release.mjs', '--app-root', sourceRoot], 'controlled-engine.log');
|
||||
actualControlled = JSON.parse(output.trim().split('\n').at(-1));
|
||||
@@ -117,7 +117,7 @@ try {
|
||||
assert.equal(actualControlled.realModelRequests, 0); assert.equal(actualControlled.cases, 4); assert.ok(actualControlled.fixtureModelRequests > 0);
|
||||
}
|
||||
let actualCompanion = null;
|
||||
if (['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'contained companion gateway and UI';
|
||||
const output = await run(['scripts/verify-companion-ui.mjs', '--app-root', sourceRoot], 'companion-ui.log');
|
||||
const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim();
|
||||
@@ -128,7 +128,7 @@ try {
|
||||
assert.equal(actualCompanion.passed.length, 7); assert.deepEqual(actualCompanion.errors, []); assert.equal(actualCompanion.realModelRequests, 0);
|
||||
}
|
||||
let actualProtocols = null;
|
||||
if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'contained model protocols and mobile streams';
|
||||
const output = await run(['scripts/verify-model-protocols-ui.mjs', '--app-root', sourceRoot], 'model-protocols-ui.log');
|
||||
const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim();
|
||||
@@ -139,7 +139,7 @@ try {
|
||||
assert.equal(actualProtocols.passed.length, 5); assert.deepEqual(actualProtocols.pageErrors, []); assert.deepEqual(actualProtocols.requestFailures, []);
|
||||
}
|
||||
let actualVision = null;
|
||||
if (['1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'contained screenshot inputs and exact Task budget resume';
|
||||
const output = await run(['scripts/verify-vision-ui.mjs', '--app-root', sourceRoot], 'vision-ui.log');
|
||||
const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim();
|
||||
@@ -150,7 +150,7 @@ try {
|
||||
assert.equal(actualVision.passed.length, 5); assert.deepEqual(actualVision.pageErrors, []); assert.equal(actualVision.realModelRequests, 0);
|
||||
}
|
||||
let actualProjectCache = null;
|
||||
if (['1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'contained source-verified parsing cache controls';
|
||||
const output = await run(['scripts/verify-project-cache-ui.mjs', '--app-root', sourceRoot], 'project-cache-ui.log');
|
||||
const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim();
|
||||
@@ -160,10 +160,38 @@ try {
|
||||
assert.equal(fs.realpathSync.native(actualProjectCache.appRoot), sourceRoot); assert.equal(actualProjectCache.passed.length, 7);
|
||||
assert.equal(actualProjectCache.realModelRequests, 0); assert.deepEqual(actualProjectCache.pageErrors, []);
|
||||
}
|
||||
stage = 'tests';
|
||||
const output = await run(['--test', '--test-concurrency=2', '--test-reporter=tap', ...files(path.join(sourceRoot, 'tests')).filter(file => !file.includes(path.sep) && file.endsWith('.test.mjs')).map(file => path.join('tests', file))], 'tests.tap');
|
||||
const stats = Object.fromEntries([...output.matchAll(/^# (tests|pass|fail|cancelled|skipped|todo) (\d+)\s*$/gm)].map(match => [match[1], Number(match[2])]));
|
||||
assert.ok(stats.tests > 0); assert.equal(stats.pass, stats.tests); for (const key of ['fail', 'cancelled', 'skipped', 'todo']) assert.equal(stats[key], 0);
|
||||
let actualEnvironment = null, actualEnvironmentEngineering = null;
|
||||
if (evidence.version === '1.21.0') {
|
||||
stage = 'contained environment approval, stop and recovery UI';
|
||||
const output = await run(['scripts/verify-environment-ui.mjs', '--app-root', sourceRoot], 'environment-ui.log');
|
||||
const summary = JSON.parse(output.trim().split(/\r?\n/).findLast(line => line.startsWith('{"success":')));
|
||||
const relative = path.relative(path.join(sourceRoot, '.qa'), summary.directory);
|
||||
assert.ok(relative && !relative.startsWith('..') && !path.isAbsolute(relative));
|
||||
actualEnvironment = JSON.parse(fs.readFileSync(path.join(summary.directory, 'result.json'), 'utf8'));
|
||||
assert.equal(actualEnvironment.success, true); assert.equal(actualEnvironment.appRoot, sourceRoot);
|
||||
assert.equal(actualEnvironment.version, evidence.version); assert.equal(actualEnvironment.checks.length, 7);
|
||||
assert.deepEqual(actualEnvironment.pageErrors, []); assert.deepEqual(actualEnvironment.failures, []); assert.equal(actualEnvironment.realModelRequests, 0);
|
||||
stage = 'real locked React dependency preparation and Python engineering';
|
||||
const engineeringOutput = await run(['scripts/verify-environment-projects.mjs'], 'environment-engineering.log');
|
||||
actualEnvironmentEngineering = JSON.parse(engineeringOutput.trim().split(/\r?\n/).findLast(line => line.startsWith('{"success":')));
|
||||
assert.equal(actualEnvironmentEngineering.success, true); assert.equal(actualEnvironmentEngineering.reactOriginal, 'failed');
|
||||
assert.equal(actualEnvironmentEngineering.reactCandidate, 'passed'); assert.equal(actualEnvironmentEngineering.reactTests, 9);
|
||||
assert.equal(actualEnvironmentEngineering.pythonTests, 2); assert.equal(actualEnvironmentEngineering.realModelRequests, 0);
|
||||
}
|
||||
// Only this file opens the fixed inspector port. Run it separately so another
|
||||
// test's child host can never compete for that port during the full suite.
|
||||
const testFiles = files(path.join(sourceRoot, 'tests')).filter(file => !file.includes(path.sep) && file.endsWith('.test.mjs'));
|
||||
const testGroups = [testFiles.filter(file => file !== 'upgrade.test.mjs'), ['upgrade.test.mjs']];
|
||||
const stats = Object.fromEntries(['tests', 'pass', 'fail', 'cancelled', 'skipped', 'todo'].map(key => [key, 0]));
|
||||
for (const [index, group] of testGroups.entries()) {
|
||||
assert.ok(group.length > 0);
|
||||
stage = index === 0 ? 'full tests without fixed inspector' : 'exclusive retained upgrade tests';
|
||||
const output = await run(['--test', '--test-concurrency=' + (index === 0 ? 2 : 1), '--test-reporter=tap', ...group.map(file => path.join('tests', file))], index === 0 ? 'tests.tap' : 'upgrade-tests.tap');
|
||||
const groupStats = Object.fromEntries([...output.matchAll(/^# (tests|pass|fail|cancelled|skipped|todo) (\d+)\s*$/gm)].map(match => [match[1], Number(match[2])]));
|
||||
assert.ok(groupStats.tests > 0); assert.equal(groupStats.pass, groupStats.tests);
|
||||
for (const key of Object.keys(stats)) { assert.ok(Number.isInteger(groupStats[key])); stats[key] += groupStats[key]; }
|
||||
for (const key of ['fail', 'cancelled', 'skipped', 'todo']) assert.equal(groupStats[key], 0);
|
||||
}
|
||||
let actualTaskControl = null;
|
||||
if (evidence.version === '1.20.1') {
|
||||
stage = 'task control desktop and 390px';
|
||||
@@ -172,7 +200,7 @@ try {
|
||||
assert.equal(actualTaskControl.success, true); assert.equal(actualTaskControl.passed.length, 5); assert.equal(actualTaskControl.realModelRequests, 0);
|
||||
}
|
||||
let actualDesktop = null;
|
||||
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.15.0', '1.16.0', '1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'actual contained Electron window'; await run(['scripts/verify-desktop-window.mjs'], 'desktop-window.log');
|
||||
const window = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/desktop-window-latest.json'), 'utf8'));
|
||||
assert.equal(window.success, true); assert.equal(path.resolve(window.appRoot), sourceRoot); assert.equal(window.results.length, 7);
|
||||
@@ -186,7 +214,7 @@ try {
|
||||
actualDesktop = { window, ui, projects, scope: 'Independently rebuilt source and its shipped Electron binary; original window/engine/engineering assertions. Own credentials/HTTP fixtures; Windows native picker and complete host crash/stop have separate actual evidence.' };
|
||||
}
|
||||
let actualProtocolEngineering = null;
|
||||
if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'Responses SSE actual Node React Python engineering';
|
||||
await run(['scripts/verify-controlled-projects.mjs', '--responses'], 'responses-engineering.log');
|
||||
const location = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/responses-engineering-location.json'), 'utf8'));
|
||||
@@ -196,7 +224,7 @@ try {
|
||||
assert.deepEqual(actualProtocolEngineering.results.map(value => value.parentCheck.results[0].tests.passed), [8, 9, 10]);
|
||||
}
|
||||
let actualVisionEngineering = null;
|
||||
if (['1.18.0', '1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'screenshot Task Node React Python engineering';
|
||||
await run(['scripts/verify-vision-projects.mjs'], 'vision-engineering.log');
|
||||
const location = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/vision-engineering-location.json'), 'utf8'));
|
||||
@@ -206,7 +234,7 @@ try {
|
||||
assert.deepEqual(actualVisionEngineering.results.map(value => value.check.results[0].tests.passed), [8, 9, 10]);
|
||||
}
|
||||
let actualCacheEngineering = null;
|
||||
if (['1.19.0', '1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.19.0', '1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'cached index original requests and Node React Python engineering';
|
||||
await run(['scripts/verify-project-cache-projects.mjs'], 'project-cache-engineering.log');
|
||||
const location = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/project-cache-engineering-location.json'), 'utf8'));
|
||||
@@ -216,7 +244,7 @@ try {
|
||||
assert.deepEqual(actualCacheEngineering.results.map(value => value.check.results[0].tests.passed), [8, 9, 10]);
|
||||
}
|
||||
let actualEvaluations = null, actualEvaluationEngineering = null;
|
||||
if (['1.20.0', '1.20.1'].includes(evidence.version)) {
|
||||
if (['1.20.0', '1.20.1','1.21.0'].includes(evidence.version)) {
|
||||
stage = 'compiled fixed engineering evaluations';
|
||||
const output = await run(['scripts/verify-evaluations-release.mjs', '--app-root', sourceRoot], 'evaluations-release.log');
|
||||
const location = [...output.matchAll(/^EVIDENCE (.+)\r?$/gm)].at(-1)?.[1]?.trim();
|
||||
@@ -235,7 +263,7 @@ try {
|
||||
}
|
||||
assert.deepEqual(snapshot(), inputs, 'Source package inputs changed during validation.');
|
||||
const result = { success: true, version: evidence.version, testedAt: new Date().toISOString(), sourceRoot, directory, nodeVersion: process.version, python, offlineInstall: true,
|
||||
inputs, inputFiles: inputs.length, logs, buildMatchedFiles: Object.keys(expected).length, buildFiles: Object.entries(expected).map(([path, sha256]) => ({ path: path.replaceAll('\\', '/'), sha256 })), tests: stats, actualTaskControl, actualRea, actualEngine, actualBrowser, actualControlled, actualDesktop, actualCompanion, actualProtocols, actualProtocolEngineering, actualVision, actualVisionEngineering, actualProjectCache, actualCacheEngineering, actualEvaluations, actualEvaluationEngineering, credentialsHandling: 'Only build/runtime environment paths are inherited; no configured model credentials are used. The controlled-engine stage supplies a declared owned local response fixture.' };
|
||||
inputs, inputFiles: inputs.length, logs, buildMatchedFiles: Object.keys(expected).length, buildFiles: Object.entries(expected).map(([path, sha256]) => ({ path: path.replaceAll('\\', '/'), sha256 })), tests: stats, actualEnvironment, actualEnvironmentEngineering, actualTaskControl, actualRea, actualEngine, actualBrowser, actualControlled, actualDesktop, actualCompanion, actualProtocols, actualProtocolEngineering, actualVision, actualVisionEngineering, actualProjectCache, actualCacheEngineering, actualEvaluations, actualEvaluationEngineering, credentialsHandling: 'Only build/runtime environment paths are inherited; no configured model credentials are used. The controlled-engine stage supplies a declared owned local response fixture.' };
|
||||
save(result); console.log(JSON.stringify({ success: true, version: result.version, sourceRoot, directory, tests: stats, nodeVersion: process.version, python, inputFiles: inputs.length, buildMatchedFiles: result.buildMatchedFiles, rea: !!actualRea?.success, engine: !!actualEngine?.success, browser: !!actualBrowser?.success, controlled: !!actualControlled?.success }));
|
||||
} catch (error) {
|
||||
save({ success: false, version: evidence.version, testedAt: new Date().toISOString(), stage, error: error.message, sourceRoot, directory, nodeVersion: process.version, python, inputs, logs });
|
||||
|
||||
+3
-1
@@ -107,6 +107,7 @@ export default function App() {
|
||||
const sessionCreation = useRef<Promise<Session | null> | null>(null);
|
||||
const selectedProject = projects.find(project => project.id === projectId);
|
||||
const isRunning = !!session && (activeStates.includes(session.status) || session.execution?.checks.some(job => ['queued', 'running'].includes(job.status)) === true
|
||||
|| session.execution?.environmentJobs?.some(job => ['queued','running','stopping'].includes(job.status)) === true
|
||||
|| session.execution?.deliveries?.some(job => ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(job.status)) === true
|
||||
|| session.execution?.changeSets?.some(set => ['applying', 'rolling_back'].includes(set.status)) === true
|
||||
|| session.execution?.workspaces?.some(value => ['creating', 'verifying', 'registering'].includes(value.status)) === true
|
||||
@@ -568,7 +569,8 @@ export default function App() {
|
||||
{isRunning && !approval && <div className="working-note"><LoaderCircle size={14} className="spin" /><span>{session?.executionMode === 'demo' ? '正在执行演示流程' : '正在处理任务'}</span></div>}
|
||||
</div>}
|
||||
{session&&<BudgetPausePanel key={session.id+session.execution?.run?.id} session={session} config={config} onSession={acceptSession}/>}
|
||||
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>{approval.browserPlanId ? '确认实际页面检查' : approval.checkPlanId ? '确认工程检查' : '确认这次终端执行'}</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre>
|
||||
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>{approval.environmentPlanId ? '确认依赖准备' : approval.browserPlanId ? '确认实际页面检查' : approval.checkPlanId ? '确认工程检查' : '确认这次终端执行'}</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre>
|
||||
{approval.environmentSummary&&<div className="approval-shell"><p>所属工作区:{approval.environmentSummary.root}</p><p>注册源:{approval.environmentSummary.registry} · {approval.environmentSummary.offline?'只使用缓存':'允许下载'} · {Math.round(approval.environmentSummary.timeoutMs/1000)} 秒</p><strong>{approval.environmentSummary.scripts==='skip'?'跳过全部安装脚本':'允许根工程及依赖安装脚本'}</strong><details><summary>安装脚本范围</summary>{approval.environmentSummary.lifecycle.map(row=><div key={row.name}><strong>{row.name}</strong><pre>{row.script}</pre></div>)}<p>锁文件标记 {approval.environmentSummary.installScriptPackages.length} 个包带安装脚本;下载前无法读取其正文。</p></details><p>准备完成后仍需实际工程检查。停止后保留部分依赖,原计划不会自动重放。</p></div>}
|
||||
{approval.checkScripts?.filter(check => check.python).map(check => <p className="approval-shell" key={check.name}>Python {check.python!.runtime.version || '执行时核对版本'} · {check.python!.runtime.logicalExecutable || check.python!.runtime.executable || '解释器缺失'}</p>)}
|
||||
<div className="approval-path"><Folder size={12} /><span>{approval.cwd}</span></div><p className="approval-shell">{approval.shell || '项目终端'} · UTF-8</p><p className="approval-scope">{approval.browserPlanId ? '按封存步骤操作当前构建,保存页面原结果。' : '确认后以你的系统权限执行。'}</p><div className="approval-actions"><button className="button secondary" onClick={() => decide(false)} disabled={deciding}>拒绝执行</button><button className="button primary" onClick={() => decide(true)} disabled={deciding}><Play size={14} />确认执行</button></div></div>}
|
||||
{pending.length > 0 && !isRunning && <button className="review-callout" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={17} /><span><strong>{pending.length} 项改动等待审查</strong><small>查看差异后,再应用到项目文件。</small></span><ArrowRight size={17} /></button>}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
.environment-panel { min-width:0; }
|
||||
.environment-error { padding:10px;border-left:3px solid #b63d3d;background:#fff0ef;color:#8b2828;overflow-wrap:anywhere;font-size:12px;line-height:1.7; }
|
||||
.environment-panel h4 { margin:0 0 10px;font-size:13px;color:var(--text-primary,#20344c); }
|
||||
.environment-diagnostic,.environment-plan,.environment-job,.environment-prepare { margin-top:14px;padding-top:14px;border-top:1px solid var(--border,#dce4ec);min-width:0; }
|
||||
.environment-result-heading { display:flex;align-items:center;flex-wrap:wrap;gap:8px;font-size:12px; }
|
||||
.environment-result-heading>code { margin-left:auto;color:var(--text-muted,#687c91);font-size:11px; }
|
||||
.environment-state { display:inline-flex;padding:3px 7px;background:#edf2f7;color:#40576d;border-radius:4px;font-size:11px; }
|
||||
.environment-state.ready { color:#176143;background:#e8f5ee; }
|
||||
.environment-state.needs_preparation { color:#855716;background:#fff4df; }
|
||||
.environment-fields { display:grid;grid-template-columns:96px minmax(0,1fr);gap:8px 12px;margin:12px 0;font-size:12px;line-height:1.6; }
|
||||
.environment-fields dt { color:var(--text-muted,#687c91); }
|
||||
.environment-fields dd { margin:0;min-width:0;overflow-wrap:anywhere; }
|
||||
.environment-fields dd code { display:block;font-size:11px;overflow-wrap:anywhere; }
|
||||
.environment-path { display:block;overflow-wrap:anywhere;font-size:11px;line-height:1.7; }
|
||||
.environment-panel p { font-size:12px;line-height:1.65;overflow-wrap:anywhere; }
|
||||
.environment-panel pre,.environment-confirm pre { max-height:260px;overflow:auto;padding:10px;background:var(--surface-subtle,#f3f6fa);border:1px solid var(--border,#dce4ec);border-radius:5px;font:11px/1.7 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere; }
|
||||
.environment-panel details,.environment-confirm details { margin:10px 0;font-size:12px; }
|
||||
.environment-panel summary { cursor:pointer;line-height:1.8;color:var(--text-secondary,#40576d); }
|
||||
.environment-prepare label { display:block;font-size:12px;line-height:1.65;margin:10px 0; }
|
||||
.environment-prepare label>input:not([type=checkbox]) { display:block;width:100%;margin-top:5px;padding:8px;border:1px solid var(--border,#dce4ec);border-radius:5px;background:var(--surface,#fff);font:12px/1.5 inherit;color:inherit; }
|
||||
.environment-prepare .environment-choice { display:flex;gap:8px;align-items:flex-start; }
|
||||
.environment-choice input { flex-shrink:0;margin-top:4px; }
|
||||
.environment-issues { padding-left:18px;color:#8a561b;font-size:12px;line-height:1.8;overflow-wrap:anywhere; }
|
||||
.environment-actions { display:flex;gap:12px;flex-wrap:wrap; }
|
||||
.environment-confirm { min-width:0;max-height:65vh;overflow:auto; }
|
||||
@media(max-width:600px) { .environment-fields { grid-template-columns:minmax(0,1fr);gap:3px; }.environment-fields dd { margin-bottom:8px; }.environment-panel .button { max-width:100%;white-space:normal;min-height:40px; }.environment-actions .text-button { min-height:40px; } }
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Check, FileText, LoaderCircle, PackageCheck, RefreshCw, Square } from 'lucide-react';
|
||||
import { api, downloadArtifact } from './api';
|
||||
import { Modal } from './components';
|
||||
import type { EnvironmentPlan, Project, Session } from './types';
|
||||
import './EnvironmentPanel.css';
|
||||
|
||||
const labels: Record<string,string> = {ready:'依赖已就绪',needs_preparation:'需要准备依赖',unsupported:'暂不支持自动准备',planned:'计划待确认',consumed:'计划已使用',queued:'排队中',running:'正在准备',stopping:'正在停止',prepared:'依赖准备完成',failed:'准备失败',cancelled:'已停止',unknown:'结果待核对',stale:'输入已变化',unverified:'未能完整核验',missing:'未找到',available:'已识别',deferred:'等待检查审批'};
|
||||
const activeStates=['queued','running','stopping'];
|
||||
export function EnvironmentPanel({project,session,busy,onSession,onError,openArtifact}:{project:Project;session:Session;busy:boolean;onSession:(value:Session)=>void;onError:(error:unknown)=>void;openArtifact:(id:string)=>void}) {
|
||||
const [working,setWorking]=useState(''),[registry,setRegistry]=useState('https://registry.npmjs.org/'),[allowScripts,setAllowScripts]=useState(false),[offline,setOffline]=useState(false);
|
||||
const [failure,setFailure]=useState('');
|
||||
const [confirm,setConfirm]=useState<EnvironmentPlan|null>(null),[reconcile,setReconcile]=useState<string|null>(null),scope=useRef(0);
|
||||
const execution=session.execution,diagnostic=execution?.environmentDiagnostics?.at(-1),node=diagnostic?.node,python=diagnostic?.python;
|
||||
const plans=execution?.environmentPlans??[],plan=plans.at(-1),jobs=execution?.environmentJobs??[],active=jobs.some(job=>activeStates.includes(job.status));
|
||||
const unresolved=jobs.some(job=>job.requiresVerification&&!job.reconciliation);
|
||||
useEffect(()=>{scope.current++;setWorking('');setFailure('');setConfirm(null);setReconcile(null);setRegistry('https://registry.npmjs.org/');setAllowScripts(false);setOffline(false);return()=>{scope.current++;};},[session.id,execution?.task?.id]);
|
||||
async function perform(action:string,input:unknown={},after?:()=>void) {
|
||||
const current=scope.current;setWorking(action);setFailure('');
|
||||
try{const value=await api<Session>('/sessions/'+session.id+'/'+action,input);if(current===scope.current){onSession(value);after?.();}}
|
||||
catch(error){if(current===scope.current){setFailure(error instanceof Error?error.message:String(error));onError(error);}}
|
||||
finally{if(current===scope.current)setWorking('');}
|
||||
}
|
||||
const disabled=busy||active||!!working;
|
||||
return <section className="task-record-section environment-panel" aria-label="工程环境与依赖">
|
||||
<div className="record-heading"><PackageCheck size={15}/><h3>工程环境与依赖</h3></div>
|
||||
<p className="record-footnote">先核对环境,再准备依赖、执行工程检查。诊断只读取声明与实际文件。</p>
|
||||
{failure&&!confirm&&!reconcile&&<p className="environment-error" role="alert">{failure}</p>}
|
||||
<button type="button" className="button secondary" disabled={disabled||!execution?.task} onClick={()=>perform('environment-diagnostics')}>
|
||||
{working==='environment-diagnostics'?<LoaderCircle size={14} className="spin"/>:<RefreshCw size={14}/>}{diagnostic?'重新诊断工程环境':'诊断工程环境'}</button>
|
||||
{diagnostic&&<div className="environment-diagnostic" role="status">
|
||||
{node&&<><div className="environment-result-heading"><strong>Node / npm</strong><span className={'environment-state '+node.status}>{labels[node.status]??node.status}</span></div>
|
||||
<dl className="environment-fields"><dt>实际运行时</dt><dd>Node {node.runtime.node.version} · npm {node.runtime.npm?.version??'未找到'}<code title={node.runtime.node.path}>{node.runtime.node.path}</code></dd>
|
||||
<dt>声明与锁文件</dt><dd>{node.declarations.map(file=><code key={file.path} title={file.sha256}>{file.path.split(/[\\/]/).at(-1)} · {file.sha256.slice(0,12)}</code>)}{node.lockVersion&&<span>package-lock v{node.lockVersion} · {node.packageCount} 个锁定包</span>}</dd>
|
||||
<dt>实际依赖文件</dt><dd>{node.installed.status==='verified'?`${node.installed.files} 项 · ${(node.installed.bytes/1024/1024).toFixed(1)} MB` : node.installed.status==='missing'?'没有 node_modules':node.installed.message}
|
||||
{node.installed.sha256&&<code title={node.installed.sha256}>SHA-256 {node.installed.sha256.slice(0,16)}</code>}</dd>
|
||||
{!!node.missing.length&&<><dt>缺少依赖</dt><dd>{node.missing.join('、')}</dd></>}{!!node.mismatched.length&&<><dt>版本需核对</dt><dd>{node.mismatched.join('、')}</dd></>}
|
||||
{!!node.sources.length&&<><dt>锁定下载来源</dt><dd>{node.sources.map(source=><code key={source}>{source}</code>)}</dd></>}
|
||||
</dl>{!!node.issues.length&&<ul className="environment-issues">{node.issues.map(issue=><li key={issue}>{issue}</li>)}</ul>}
|
||||
</>}
|
||||
{python&&<><div className="environment-result-heading"><strong>Python / {python.framework??'检查器'}</strong><span className="environment-state">{labels[python.status]??python.status}</span></div>
|
||||
<p>{python.runtime.version??'版本等待审批后核对'} · pytest {python.pytest.version??'未找到元数据'}</p><code className="environment-path">{python.runtime.logicalExecutable??'没有可用解释器'}</code><p className="record-footnote">{python.message}</p></>}
|
||||
{!node&&!python&&<p>尚未识别可支持的 Node 或 Python 工程声明。</p>}
|
||||
<button type="button" className="text-button" onClick={()=>openArtifact(diagnostic.artifactId)}><FileText size={13}/>查看原诊断</button>
|
||||
</div>}
|
||||
{node&&<div className="environment-prepare">
|
||||
<h4>准备所属工作区</h4>
|
||||
{!project.workspace&&<p className="record-footnote">先在上方创建并打开独立开发工作区;依赖准备在该工作区执行。</p>}
|
||||
<details><summary>下载与脚本选项</summary><label>注册源<input aria-label="依赖注册源" value={registry} disabled={disabled} onChange={event=>setRegistry(event.target.value)}/></label>
|
||||
<label className="environment-choice"><input type="checkbox" checked={offline} disabled={disabled} onChange={event=>setOffline(event.target.checked)}/>只使用本工作区的下载缓存(离线)</label>
|
||||
<label className="environment-choice"><input type="checkbox" checked={allowScripts} disabled={disabled} onChange={event=>setAllowScripts(event.target.checked)}/>允许依赖生命周期脚本</label>
|
||||
<p className="record-footnote">默认跳过脚本。部分原生依赖需要脚本才能使用;允许后,根工程和下载包的安装脚本会以本机账户执行。具体执行范围会在确认页显示。</p>
|
||||
</details>
|
||||
<button type="button" className="button secondary" disabled={disabled||unresolved||!project.workspace||!node.preparable} onClick={()=>perform('environment-plans',{registry,scripts:allowScripts?'allow':'skip',offline})}>{working==='environment-plans'?<LoaderCircle size={14} className="spin"/>:<PackageCheck size={14}/>}创建依赖准备计划</button>
|
||||
</div>}
|
||||
{plan&&<div className="environment-plan"><div className="environment-result-heading"><strong>npm ci</strong><span className="environment-state">{labels[plan.status]??plan.status}</span></div>
|
||||
<p>{plan.packageCount} 个锁定包 · {plan.offline?'离线缓存':'下载自 '+plan.registry} · {plan.scripts==='skip'?'跳过安装脚本':'允许安装脚本'}</p><code className="environment-path">{plan.root}</code>
|
||||
<details><summary>查看固定命令与计划身份</summary><pre>{plan.invocation.executable+'\n'+plan.invocation.args.map(arg=>JSON.stringify(arg)).join('\n')}</pre><code className="environment-path">SHA-256 {plan.fingerprint}</code></details>
|
||||
{plan.status==='planned'&&<button type="button" className="button primary" disabled={disabled||unresolved} onClick={()=>setConfirm(plan)}>核对并批准依赖准备</button>}
|
||||
</div>}
|
||||
{jobs.slice().reverse().map(job=><div className="environment-job" key={job.id}>
|
||||
<div className="environment-result-heading"><strong>{labels[job.status]??job.status}</strong><code title={job.id}>{job.id.slice(0,8)}</code>
|
||||
{activeStates.includes(job.status)&&<button type="button" className="text-button" disabled={!!working} onClick={()=>perform('environment-jobs/'+job.id+'/stop')}><Square size={12}/>停止依赖准备</button>}</div>
|
||||
<p>{job.summary??'按封存计划准备依赖,原进程与日志正在记录。'}</p>{job.result&&<p className="record-footnote">退出码 {job.result.exitCode??'未返回'} · {(job.result.durationMs/1000).toFixed(1)} 秒{job.result.truncated?' · 日志超出上限,保留首尾':''}</p>}
|
||||
{job.logExcerpt&&<details open={activeStates.includes(job.status)}><summary>原执行日志预览</summary><pre>{job.logExcerpt}</pre></details>}
|
||||
{job.logArtifactId&&<div className="environment-actions"><button type="button" className="text-button" onClick={()=>openArtifact(job.logArtifactId!)}><FileText size={13}/>查看依赖日志</button><button type="button" className="text-button" onClick={()=>{void downloadArtifact(session.id,job.logArtifactId!,'dependency-'+job.id+'.log').catch(onError);}}>下载原日志</button></div>}
|
||||
{job.after&&<details><summary>准备后的环境身份</summary><code className="environment-path">SHA-256 {job.after.identity}</code><p className="record-footnote">依赖准备完成后,还需要实际测试与构建。</p></details>}
|
||||
{job.requiresVerification&&!job.reconciliation&&<button type="button" className="button secondary" disabled={disabled} onClick={()=>setReconcile(job.id)}>核对中断现场</button>}
|
||||
{job.reconciliation&&<p className="record-footnote">已核对原进程结束并保留现场,原未知结果保持。再次执行需要新计划。</p>}
|
||||
</div>)}
|
||||
{confirm&&<Modal title="确认依赖准备" description="核对目标、实际命令、下载来源和脚本范围后执行。" onClose={()=>{if(!working)setConfirm(null);}}>
|
||||
<div className="environment-confirm"><dl className="environment-fields"><dt>独立工作区</dt><dd><code>{confirm.root}</code></dd><dt>注册源</dt><dd>{confirm.registry}{confirm.offline?'(只使用缓存)':''}</dd>
|
||||
<dt>执行时限</dt><dd>{Math.round(confirm.timeoutMs/1000)} 秒,可随时停止</dd><dt>生命周期脚本</dt><dd><strong>{confirm.scripts==='skip'?'全部跳过(--ignore-scripts=true)':'允许执行根工程和依赖包安装脚本'}</strong></dd></dl>
|
||||
<pre>{confirm.invocation.executable+'\n'+confirm.invocation.args.map(arg=>JSON.stringify(arg)).join('\n')}</pre>
|
||||
{!!confirm.lifecycle.length&&<details open><summary>根工程的安装脚本</summary>{confirm.lifecycle.map(script=><div key={script.name}><strong>{script.name}</strong><pre>{script.script}</pre></div>)}</details>}
|
||||
{!!confirm.installScriptPackages.length&&<p>锁文件标记了 {confirm.installScriptPackages.length} 个带安装脚本的包:{confirm.installScriptPackages.join('、')}。脚本正文需下载后才能读取。</p>}
|
||||
<p className="record-footnote">会更新该工作区的 node_modules。失败或停止后保留现场与日志;原计划只执行一次。安装完成后继续核对工程检查结果。</p>
|
||||
{failure&&<p className="environment-error" role="alert">{failure}</p>}
|
||||
</div><div className="modal-actions"><button type="button" className="button secondary" disabled={!!working} onClick={()=>setConfirm(null)}>取消</button><button type="button" className="button primary" disabled={disabled} onClick={()=>perform('environment-jobs',{planId:confirm.id,fingerprint:confirm.fingerprint,approved:true},()=>setConfirm(null))}><Check size={14}/>确认执行依赖准备</button></div>
|
||||
</Modal>}
|
||||
{reconcile&&<Modal title="核对中断的依赖准备" onClose={()=>setReconcile(null)}><p>将只读核对原所属进程和当前工程环境。原进程仍存在时保留阻塞状态;确认结束后保留原未知结果,并允许重新创建计划。</p><div className="modal-actions"><button type="button" className="button secondary" onClick={()=>setReconcile(null)}>取消</button><button type="button" className="button primary" disabled={!!working} onClick={()=>perform('environment-jobs/'+reconcile+'/reconcile',{fingerprint:jobs.find(job=>job.id===reconcile)?.planFingerprint},()=>setReconcile(null))}>确认只读核对</button></div></Modal>}
|
||||
</section>;
|
||||
}
|
||||
@@ -76,7 +76,7 @@ export function EvaluationPanel({session,config,busy,onSession,onNavigate,onRevi
|
||||
{sample.error&&<p className="evaluation-error">{sample.error}</p>}
|
||||
<details className="evaluation-commands" open={sample.status==='ready'}><summary>固定检查 · {sample.checks.join(' / ')}</summary>{sample.commands?.map(command=><div key={command.name}><strong>{command.command}</strong><pre>{command.script}</pre>{command.lifecycle?.map(step=><p key={step.name}>{step.name}:<code>{step.script}</code></p>)}</div>)??<p>工作区准备完成后显示实际命令,执行前需要核对。</p>}</details>
|
||||
{!!sample.workers?.length&&<div className="evaluation-lanes">{sample.workers.map(worker=><section key={worker.id} aria-label={worker.evaluation?.role==='original'?'原版工程':'候选工程'}><div className="evaluation-lane-title"><h4>{worker.evaluation?.role==='original'?'原版':'候选'}</h4><span>{worker.evaluation?.role==='original'?'只跑固定检查':label(worker.sessionStatus==='awaiting_approval'?'awaiting_approval':worker.status)}</span></div><p>{worker.summary}</p>{worker.status!=='unprepared'&&<button className="button secondary" onClick={()=>void onNavigate(worker.projectId,worker.sessionId,worker.sessionStatus==='awaiting_approval'?'approval':worker.sessionStatus==='needs_review'?'changes':'task')}>{worker.sessionStatus==='awaiting_approval'?'核对并审批检查':worker.sessionStatus==='needs_review'?'审查候选改动':'打开原任务'}<ArrowUpRight size={13}/></button>}</section>)}</div>}
|
||||
{sample.contractSha256&&<p className="evaluation-note">同源输入已封存 · SHA-256 <code>{sample.contractSha256.slice(0,16)}</code></p>}
|
||||
{!!sample.workers?.length&&<p className="evaluation-note">新检出的工程如缺依赖,可先打开两侧原任务,在「工程环境与依赖」分别核对并准备;两侧使用同一锁文件及运行时,再执行原版检查。</p>}{sample.contractSha256&&<p className="evaluation-note">同源输入已封存 · SHA-256 <code>{sample.contractSha256.slice(0,16)}</code></p>}
|
||||
<div className="evaluation-actions">
|
||||
{sample.status==='pending'&&<button className="button" disabled={!!action||running||busy||batch.samples.slice(0,batch.samples.indexOf(sample)).some(sample=>!sample.report)} onClick={()=>confirm('prepare')}>准备同源工作区</button>}
|
||||
{sample.status==='ready'&&<button className="button" disabled={!!action||running} onClick={()=>confirm('baseline')}>核对并运行原版</button>}
|
||||
@@ -93,6 +93,6 @@ export function EvaluationPanel({session,config,busy,onSession,onNavigate,onRevi
|
||||
</>}
|
||||
</>}
|
||||
{confirmation&&batch&&sample&&<Modal title="确认评测操作" onClose={()=>setConfirmation(null)}><div className="evaluation-confirm"><h3>{sample.label}</h3><p>{({prepare:'从封存 HEAD 创建两个独立 Git 工作区,保留来源原修改。',baseline:'请核对上方完整检查命令。将以本机账户执行原工程程序,不请求模型。',start:'将请求封存模型并使用剩余预算。候选提案仍需审查,工程检查仍需审批。',seal:'保存当前全部尝试、失败、停止与未知。封存后该样本不能再执行或修改。',adopt:'核对原通过报告及当前来源后,生成父工程待审查变更集。应用、父检查和 Git 交付仍需确认。',retain:'保留原任务、工作区和全部结果,结束本批;未执行样本仍计入原分母。'} as Record<string,string>)[confirmation.operation]}</p><button className="button" disabled={!!action} onClick={()=>{if(confirmation.batchId===batch.id&&confirmation.sampleId===sample.id)void execute(confirmation.operation);}}>确认{({prepare:'准备',baseline:'运行原版',start:'开始候选',seal:'封存结果',adopt:'准备采纳',retain:'保留现场结束'} as Record<string,string>)[confirmation.operation]}</button></div></Modal>}
|
||||
{report&&sample&&<Modal title="原版与候选对照" wide onClose={()=>setReport(null)}><div className="evaluation-report"><div className="evaluation-report-heading"><div><h3>{report.label}</h3>{report.evidenceMode==='local-fixture'&&<p className="evaluation-note">本地固定响应 · 执行链验收</p>}<p>{report.inputVerified?'原测试与非候选输入已核对':report.inputError??'原输入无法核对'}</p></div><button className="button secondary" onClick={()=>downloadBlob(new Blob([JSON.stringify(report,null,2)],{type:'application/json'}),'agent-workbench-evaluation-'+report.sampleId+'.json')}><Download size={14}/>导出原报告</button></div><div className="evaluation-lanes">{(['original','candidate'] as const).map(role=>{const result=report[role];return <section key={role}><div className="evaluation-lane-title"><h4>{role==='original'?'原版':'候选'}</h4><strong className={'evaluation-outcome '+result.outcome}>{label(result.outcome)}</strong></div><p>{result.reason??result.evidenceError}</p><dl><div><dt>用时</dt><dd>{elapsed(result)}</dd></div><div><dt>模型请求</dt><dd>{result.usage?.requests??'未知'}</dd></div><div><dt>上游用量</dt><dd>{result.usage?.reported?number(result.usage.totalTokens)+' tokens':'未知;保留预算估算'}</dd></div><div><dt>费用</dt><dd>未报告</dd></div><div><dt>实际人工操作</dt><dd>审批 {result.approvals?.filter(approval=>approval.status==='approved').length??0} 次 · 应用提案 {result.changes?.filter(change=>change.status==='applied').length??0} 项</dd></div></dl>{result.attempts.length?result.attempts.map((attempt,index)=><div className="evaluation-attempt" key={attempt.id}><strong>检查尝试 {index+1} · {label(attempt.status)}</strong>{attempt.results.map(check=><div key={check.logArtifactId}><span>{check.name} · {check.status?label(check.status):'证据缺失'}</span>{check.tests&&<span>测试 {check.tests.passed}/{check.tests.total} · 失败 {check.tests.failed}</span>}<code>{check.logSha256?.slice(0,16)??'原日志无法核对'}</code></div>)}</div>):<p>没有完整检查结果;保持未知。</p>}</section>;})}</div><p className="evaluation-note">{report.note}</p><details><summary>报告原字段与工件引用</summary><pre>{JSON.stringify(report,null,2)}</pre></details></div></Modal>}
|
||||
{report&&sample&&<Modal title="原版与候选对照" wide onClose={()=>setReport(null)}><div className="evaluation-report"><div className="evaluation-report-heading"><div><h3>{report.label}</h3>{report.evidenceMode==='local-fixture'&&<p className="evaluation-note">本地固定响应 · 执行链验收</p>}<p>{report.inputVerified?'原测试与非候选输入已核对':report.inputError??'原输入无法核对'}</p></div><button className="button secondary" onClick={()=>downloadBlob(new Blob([JSON.stringify(report,null,2)],{type:'application/json'}),'agent-workbench-evaluation-'+report.sampleId+'.json')}><Download size={14}/>导出原报告</button></div><div className="evaluation-lanes">{(['original','candidate'] as const).map(role=>{const result=report[role];return <section key={role}><div className="evaluation-lane-title"><h4>{role==='original'?'原版':'候选'}</h4><strong className={'evaluation-outcome '+result.outcome}>{label(result.outcome)}</strong></div><p>{result.reason??result.evidenceError}</p><dl><div><dt>用时</dt><dd>{elapsed(result)}</dd></div><div><dt>模型请求</dt><dd>{result.usage?.requests??'未知'}</dd></div><div><dt>上游用量</dt><dd>{result.usage?.reported?number(result.usage.totalTokens)+' tokens':'未知;保留预算估算'}</dd></div><div><dt>费用</dt><dd>未报告</dd></div><div><dt>实际人工操作</dt><dd>审批 {result.approvals?.filter(approval=>approval.status==='approved').length??0} 次 · 应用提案 {result.changes?.filter(change=>change.status==='applied').length??0} 项</dd></div></dl>{result.attempts.length?result.attempts.map((attempt,index)=><div className="evaluation-attempt" key={attempt.id}><strong>检查尝试 {index+1} · {label(attempt.status)}</strong>{attempt.results.map(check=><div key={check.logArtifactId}><span>{check.name} · {check.status?label(check.status):'证据缺失'}</span>{check.tests&&<span>测试 {check.tests.passed}/{check.tests.total} · 失败 {check.tests.failed}</span>}<code>{check.logSha256?.slice(0,16)??'原日志无法核对'}</code></div>)}</div>):<p>没有完整检查结果;保持未知。</p>}</section>;})}</div><p className="evaluation-note">{report.environmentComparison&&<span>依赖环境:{report.environmentComparison.matched?'原版与候选实际输入一致':'缺少相同环境的有效证据'}。 </span>}{report.note}</p><details><summary>报告原字段与工件引用</summary><pre>{JSON.stringify(report,null,2)}</pre></details></div></Modal>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { TaskPlanPanel } from './TaskPlanPanel';
|
||||
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
|
||||
import { McpJobHistory } from './McpJobHistory';
|
||||
import './TaskPanel.css';
|
||||
import { EnvironmentPanel } from './EnvironmentPanel';
|
||||
|
||||
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');
|
||||
@@ -110,6 +111,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
|
||||
</> : <p className="record-empty"><LoaderCircle size={14} className="spin" />正在读取运行记录</p>}
|
||||
</section>}
|
||||
{run && <RequestContextPanel session={session} runId={run.id} onError={onError} openArtifact={openArtifact} />}
|
||||
{task && <EnvironmentPanel project={project} session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
<section className="task-record-section project-checks">
|
||||
<div className="record-heading"><GitBranch size={15} /><h3>工程检查</h3><Status value={task?.verification.status || 'not_configured'} /></div>
|
||||
{task?.verification.status === 'failed' && <p className="record-footnote" role="status">原工程检查有失败记录;文件应用或答复完成不代表检查通过。</p>}
|
||||
@@ -117,6 +119,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
|
||||
<p className="record-footnote">检查对应当时的工程快照。先识别测试与执行环境,再确认检查;项目变化后重新检查。</p>
|
||||
<button type="button" className="button secondary" disabled={!task || busy || planning || checkRunning} onClick={() => planChecks()}>{planning ? <LoaderCircle size={14} className="spin" /> : <RefreshCw size={14} />}{latestPlan ? '重新识别检查计划' : '识别工程与检查'}</button>
|
||||
{latestPlan && <div className="check-plan"><p><strong>{latestPlan.project.name}</strong> · {latestPlan.project.languages.join(' / ') || '待识别'}</p><p className="check-baseline"><GitBranch size={12} />{latestPlan.project.git.available ? `${latestPlan.project.git.branch || 'detached'} · ${latestPlan.project.git.head?.slice(0, 8) || '尚无提交'}${latestPlan.project.git.dirty ? ' · 有未提交改动' : ' · 工作区干净'}` : '项目尚未启用 Git'}</p>
|
||||
{latestPlan.environment&&<p className="record-footnote">环境:Node {latestPlan.environment.runtime.node.version} · npm {latestPlan.environment.runtime.npm?.version??'未找到'} · {latestPlan.environment.status==='ready'?'依赖已就绪':'依赖需要核对,请先查看上方工程环境'}{latestPlan.environment.preparation&&' · 引用依赖准备 '+latestPlan.environment.preparation.jobId.slice(0,8)}</p>}
|
||||
{latestPlan.project.python?.status === 'invalid' && <p className="record-empty">{latestPlan.project.python.message}</p>}
|
||||
{checkChoices.length > 0 && <fieldset className="check-selection" disabled={busy || planning || starting || checkRunning}>
|
||||
<legend>选择检查范围</legend>
|
||||
|
||||
@@ -4,6 +4,23 @@ export interface Config {
|
||||
maxRunDurationMs: number; maxRunTokens: number; maxTaskTokens: number;
|
||||
modelResponseTimeoutMs?: number; modelStreamIdleTimeoutMs?: number;
|
||||
}
|
||||
export interface EnvironmentFile { path:string;sha256:string;bytes:number }
|
||||
export interface DependencyTree { status:string;files:number;bytes:number;sha256:string|null;message?:string }
|
||||
export interface NodeEnvironmentRuntime {status:string;node:EnvironmentFile&{version:string};npm:(EnvironmentFile&{version:string;manifest:EnvironmentFile})|null}
|
||||
export interface NodeEnvironmentBinding {kind:'node';identity:string;dependencyInputs:string;status:string;installed:DependencyTree;declarations:EnvironmentFile[];runtime:NodeEnvironmentRuntime}
|
||||
export interface EnvironmentDiagnostic {id:string;taskId:string;runId:string;artifactId:string;artifactSha256:string;inspectedAt:string;status:string;
|
||||
node:(NodeEnvironmentBinding&{manager:string;lockVersion:number|null;packageCount:number;missing:string[];mismatched:string[];sources:string[];issues:string[];preparable:boolean})|null;
|
||||
python:{status:string;framework?:string;runtime:{version:string|null;logicalExecutable:string|null};pytest:{version:string|null};message:string}|null}
|
||||
export interface EnvironmentPlan {id:string;taskId:string;runId:string;status:string;root:string;registry:string;scripts:'skip'|'allow';offline:boolean;packageCount:number;timeoutMs:number;fingerprint:string;
|
||||
invocation:{executable:string;args:string[]};lifecycle:{name:string;script:string}[];installScriptPackages:string[]}
|
||||
export interface EnvironmentJob {id:string;taskId:string;runId:string;planFingerprint:string;status:string;summary?:string;finishedAt?:string;requiresVerification:boolean;
|
||||
logExcerpt?:string;logArtifactId?:string;after?:NodeEnvironmentBinding;result?:{exitCode:number|null;durationMs:number;truncated?:boolean};reconciliation?:{artifactId:string;sha256:string}}
|
||||
export interface ExecutionSnapshot {environmentDiagnostics?:EnvironmentDiagnostic[];environmentPlans?:EnvironmentPlan[];environmentJobs?:EnvironmentJob[]}
|
||||
export interface CheckPlan {environment?:NodeEnvironmentBinding|null}
|
||||
export interface CheckJob {environment?:NodeEnvironmentBinding|null}
|
||||
export interface Approval {environmentPlanId?:string}
|
||||
export interface Approval {environmentSummary?:Pick<EnvironmentPlan,'root'|'registry'|'scripts'|'offline'|'timeoutMs'|'lifecycle'|'installScriptPackages'>}
|
||||
export interface NodeEnvironmentBinding {preparation?:{jobId:string;planId:string;sessionId:string;logArtifactId:string;logSha256:string}|null}
|
||||
export interface ModelSelection { type: 'legacy' | 'connection' | 'pool'; id: string; name: string }
|
||||
export interface WorkspaceOrigin { id: string; sourceProjectId: string; sourceSessionId: string; sourceRoot: string; sourceWorkspaceId: string | null; baseCommit: string; branch: string; commonGitDir: string; gitDir: string; fingerprint: string }
|
||||
export interface WorkspaceIdentity { kind: 'local-project' | 'managed-worktree'; projectId: string; root: string; workspaceId?: string; sourceProjectId?: string; sourceSessionId?: string; sourceRoot?: string; sourceWorkspaceId?: string | null; baseCommit?: string; branch?: string; commonGitDir?: string; gitDir?: string; fingerprint?: string }
|
||||
@@ -304,3 +321,5 @@ export interface ResearchPage { content: string; offset: number; next_offset: nu
|
||||
export interface BrowserStep { action: 'fill' | 'select' | 'click' | 'assert_text' | 'assert_count' | 'assert_visible'; selector: string; value?: string; text?: string; count?: number; visible?: boolean; contains?: boolean }
|
||||
export interface BrowserPlan { id: string; taskId: string; runId: string; status: string; fingerprint: string; sourceFingerprint: string; build: { directory: string; files: number; bytes: number; sha256: string }; path: string; viewport: { width: number; height: number }; steps: BrowserStep[] }
|
||||
export interface BrowserJob { id: string; taskId: string; runId: string; planId: string; planFingerprint: string; sourceFingerprint: string; buildSha256: string; status: string; startedAt: string; finishedAt: string | null; summary: string; resultArtifactId?: string; resultSha256?: string; assertions: { total: number; passed: number; failed: number }; requiresVerification: boolean; cleanup?: { exited: boolean; pid: number | null }; steps: (BrowserStep & { status: string; error?: string; actual?: unknown })[]; screenshots: { artifactId: string; sha256: string; bytes: number; width: number; height: number; label: string }[] }
|
||||
|
||||
export interface EvaluationReport {environmentComparison?:{dependencyInputs:string;matched:boolean}}
|
||||
|
||||
+33
-78
@@ -1,9 +1,9 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { runOwnedCommand } from './owned-command.mjs';
|
||||
import { nodeEnvironmentBinding, verifyNodeBinding } from './environment/environment-inspector.mjs';
|
||||
import { bindEnvironmentPreparation, verifyEnvironmentPreparation } from './environment/environment-evidence.mjs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { readOwnedProcessTree } from './owned-process-tree.mjs';
|
||||
import { inspectProject, createCheckList } from './project-inspector.mjs';
|
||||
import { safePath } from '../server/files.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
@@ -20,7 +20,7 @@ const conflict = message => Object.assign(new Error(message), { status: 409 });
|
||||
const removeAnsi = text => text.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '');
|
||||
const checkContract = plan => ({ schemaVersion: 1, kind: 'sealed-check-plan', id: plan.id, sessionId: plan.sessionId,
|
||||
projectId: plan.projectId, taskId: plan.taskId, runId: plan.runId, fingerprint: plan.fingerprint,
|
||||
sourceFingerprint: plan.sourceFingerprint, checks: plan.checks });
|
||||
sourceFingerprint: plan.sourceFingerprint, checks: plan.checks, ...(plan.environment ? { environment: plan.environment } : {}) });
|
||||
|
||||
export function parseTestEvidence(output, framework) {
|
||||
const text = removeAnsi(output), values = {};
|
||||
@@ -84,8 +84,11 @@ export class CheckRunner {
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
|
||||
status: 'planned', createdAt: at(), fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint, project: inspection, artifactId: artifact.id,
|
||||
checks: checks.map(check => ({ id: randomUUID(), ...check })) };
|
||||
checks: checks.map(check => ({ id: randomUUID(), ...check })),
|
||||
...(checks.some(check=>check.engine!=='python') ? {environment:bindEnvironmentPreparation(this.store,session.projectId,nodeEnvironmentBinding(this.store.project(session.projectId),{runtimeDirectory:this.runtimeDirectory}))}: {}) };
|
||||
const contract = this.store.artifactStore.write(session, run, checkContract(plan), { kind: 'check-plan' });
|
||||
const evaluation=await verifyEvaluationSources(this.store,session);
|
||||
if(evaluation?.sample.environmentInputs && plan.environment?.dependencyInputs!==evaluation.sample.environmentInputs.dependencyInputs)throw conflict('评测的依赖声明或Node/npm输入与原同源计划不同。');
|
||||
this.store.core.artifact.set(contract.id, contract); plan.contractArtifactId = contract.id; plan.contractSha256 = contract.sha256;
|
||||
const task = this.store.core.task.get(session.taskId);
|
||||
if (task.verification.status === 'passed') {
|
||||
@@ -117,7 +120,7 @@ export class CheckRunner {
|
||||
const npm = checks.some(check => check.engine !== 'python') ? npmInvocation('', this.runtimeDirectory) : null;
|
||||
// This detects repeated declared inputs. Reusing an old result never
|
||||
// creates a new verification or claims that arbitrary external state was checked.
|
||||
return createHash('sha256').update(JSON.stringify({ fingerprint: inspection.fingerprint, checks,
|
||||
return createHash('sha256').update(JSON.stringify({ fingerprint: inspection.fingerprint, checks, ...(plan.environment ? {environment:plan.environment.identity}:{}),
|
||||
node: { version: process.version, file: describe(process.execPath) }, npm: npm ? describe(npm.args[0]) : null,
|
||||
dependencies: ['node_modules', 'node_modules/.package-lock.json', '.pnp.cjs', '.venv/pyvenv.cfg'].map(relative => describe(path.join(project.root, relative))),
|
||||
environment: projectEnvironment() })).digest('hex');
|
||||
@@ -127,6 +130,7 @@ export class CheckRunner {
|
||||
const plan = this.planFor(session, planId), inspection = await inspectProject(this.store.project(session.projectId));
|
||||
if (inspection.fingerprint !== plan.fingerprint) throw conflict('检查计划创建后工程或Git基线已变化,请重新识别再执行。');
|
||||
if (!inspection.scope.complete) return null;
|
||||
verifyNodeBinding(this.store.project(session.projectId),plan.environment);
|
||||
const identity = this.inputIdentity(session, plan, inspection);
|
||||
const previous = [...this.store.core.check_job.values()].findLast(job => job.taskId === session.taskId && job.inputIdentity === identity
|
||||
&& ['passed', 'failed', 'unverified'].includes(job.status) && !job.stale && !job.requiresVerification && job.finishedAt);
|
||||
@@ -169,6 +173,9 @@ export class CheckRunner {
|
||||
try {
|
||||
await verifyEvaluationSources(this.store, session, plan.checks.map(check => check.name));
|
||||
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
|
||||
verifyNodeBinding(this.store.project(session.projectId),plan.environment);
|
||||
verifyEnvironmentPreparation(this.store,session.projectId,plan.environment);
|
||||
if(plan.environment)job.environment=structuredClone(plan.environment);
|
||||
const before = await inspectProject(this.store.project(session.projectId));
|
||||
signal.throwIfAborted();
|
||||
if (before.fingerprint !== plan.fingerprint) throw conflict('检查计划创建后工程或Git基线已变化,请重新识别再执行。');
|
||||
@@ -205,6 +212,7 @@ export class CheckRunner {
|
||||
const after = await inspectProject(this.store.project(session.projectId));
|
||||
if (after.sourceFingerprint !== job.sourceFingerprint) { job.stale = true; break; }
|
||||
}
|
||||
verifyNodeBinding(this.store.project(session.projectId),plan.environment);
|
||||
const final = await inspectProject(this.store.project(session.projectId));
|
||||
await verifyEvaluationSources(this.store, session, plan.checks.map(check => check.name));
|
||||
job.stale ||= final.sourceFingerprint !== job.sourceFingerprint;
|
||||
@@ -238,78 +246,25 @@ export class CheckRunner {
|
||||
const isPython = check.engine === 'python';
|
||||
try { invocation = isPython ? await preparePythonInvocation(check, project, { signal }) : npmInvocation(check.name, this.runtimeDirectory); }
|
||||
catch (error) { return { status: signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed', exitCode: null, durationMs: Date.now() - started, tests: null, stdout: '', stderr: error.message, reason: error.message }; }
|
||||
return new Promise(resolve => {
|
||||
const env = isPython ? pythonEnvironment() : projectEnvironment({ NO_COLOR: '1', CI: '1' });
|
||||
const child = spawn(invocation.executable, invocation.args, { cwd: safePath(project), env, windowsHide: true, detached: process.platform !== 'win32', stdio: [isPython ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
|
||||
const streams = { stdout: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') }, stderr: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') } };
|
||||
let settled = false, timedOut = false, terminating = false, killTimer, ownershipError = null, treeKill = null, closedResult = null, rootClosed = false, treeTimer = null, treePending = null;
|
||||
const processInfo = onSpawn ? { pid: child.pid ?? null, hostPid: process.pid, executable: invocation.executable, argsSha256: createHash('sha256').update(JSON.stringify(invocation.args)).digest('hex'), cwd: project.root, startedAt: at() } : null;
|
||||
const append = (name, text) => { const value = streams[name]; value.characters += text.length; value.head = (value.head + text).slice(0, 240000); value.tail = (value.tail + text).slice(-240000); };
|
||||
const captured = name => { const value = streams[name]; return value.characters <= 240000 ? value.head : value.characters <= 480000 ? value.head + value.tail.slice(value.head.length - value.characters) : value.head + '\n[中间日志超出保存上限,保留开头和结尾]\n' + value.tail; };
|
||||
const captureTree = async (publish = true) => {
|
||||
const snapshot = await readOwnedProcessTree(processInfo);
|
||||
if (!snapshot.supported) return snapshot;
|
||||
if (snapshot.root) processInfo.rootCreatedAt ??= snapshot.root.createdAt;
|
||||
const known = new Map((processInfo.descendants ?? []).map(value => [value.pid + ':' + value.createdAt, value]));
|
||||
for (const value of snapshot.processes) if (value.pid !== processInfo.pid) known.set(value.pid + ':' + value.createdAt, value);
|
||||
processInfo.descendants = [...known.values()].sort((a, b) => a.pid - b.pid);
|
||||
processInfo.treeObservedAt = at(); processInfo.treeRemainingPids = snapshot.processes.map(value => value.pid);
|
||||
if (publish && !settled) onSpawn(processInfo);
|
||||
return snapshot;
|
||||
};
|
||||
const monitorTree = () => {
|
||||
if (settled || treePending) return;
|
||||
treePending = captureTree().catch(error => { ownershipError = error; processInfo.treeObservationError = error.message; terminate(); }).finally(() => { treePending = null; });
|
||||
};
|
||||
const finish = async (code, error, unknown = false) => {
|
||||
if (onSpawn && terminating && treeKill && !treeKill.done && !unknown) { closedResult = { code, error }; return; }
|
||||
if (onSpawn && treeKill?.error) unknown = true;
|
||||
if (settled) return; settled = true; clearTimeout(timeout); clearTimeout(killTimer); clearInterval(treeTimer); signal.removeEventListener('abort', terminate);
|
||||
if (onSpawn && process.platform === 'win32' && processInfo.pid) {
|
||||
await treePending;
|
||||
try { const snapshot = await captureTree(false); if (snapshot.processes.length) unknown = true; }
|
||||
catch (failure) { ownershipError = failure; processInfo.treeObservationError = failure.message; unknown = true; }
|
||||
}
|
||||
const stdout = captured('stdout'), stderr = captured('stderr') + (error ? '\n' + error.message : '') + (ownershipError ? '\n' + ownershipError.message : '');
|
||||
let collectedEvidence = null, collectedResult = null, evidenceError = null, cleanupError = null;
|
||||
if (isPython && !unknown && code !== null && !error) {
|
||||
try { const saved = readPythonEvidence(invocation, code); collectedEvidence = saved.text; collectedResult = saved.result; } catch (failure) { evidenceError = failure.message; }
|
||||
}
|
||||
const tests = check.kind === 'test' ? isPython ? collectedResult?.tests ?? null : parseTestEvidence(streams.stdout.tail, check.framework) : null;
|
||||
const status = unknown ? 'unknown' : signal.aborted ? 'cancelled'
|
||||
: timedOut || error || ownershipError || code !== 0 || evidenceError || tests?.failed > 0 || collectedResult?.collectionErrors > 0 ? 'failed'
|
||||
: (check.kind === 'test' && (!tests || tests.total === 0 || tests.passed !== tests.total || tests.cancelled > 0 || collectedResult?.collectionSkipped > 0)
|
||||
|| isPython && collectedResult?.compilation?.total === 0) ? 'unverified' : 'passed';
|
||||
if (isPython && !unknown) { try { invocation.dispose(); } catch (failure) { cleanupError = failure.message; } }
|
||||
resolve({ status, exitCode: code, durationMs: Date.now() - started, tests, stdout, stderr, timedOut, truncated: streams.stdout.characters > 480000 || streams.stderr.characters > 480000,
|
||||
...(onSpawn ? { process: { ...processInfo, rootExited: rootClosed, treeTermination: terminating ? unknown ? 'unknown' : 'confirmed' : 'not_requested' } } : {}),
|
||||
...(isPython ? { engine: 'python', python: pythonResultBinding(invocation), collectedEvidence, checkInput: invocation.input.toString('utf8'),
|
||||
compilation: collectedResult?.compilation ?? null, collectionErrors: collectedResult?.collectionErrors ?? null,
|
||||
collectionSkipped: collectedResult?.collectionSkipped ?? null, evidenceValidated: !!collectedResult, evidenceError, cleanupError,
|
||||
...(unknown ? { hostEvidenceDirectory: invocation.directory } : {}) } : {}),
|
||||
reason: unknown ? '进程终止未得到确认,需要核对实际副作用。' : timedOut ? '检查超过时间上限,已请求终止进程树。'
|
||||
: evidenceError || collectedResult?.collectorError || (collectedResult?.collectionErrors > 0 ? 'Python测试收集或类初始化有错误。' : null)
|
||||
|| (status === 'unverified' ? '测试为空、有跳过项,或没有可验证的测试数量。' : undefined) });
|
||||
};
|
||||
const terminate = () => {
|
||||
if (settled || terminating) return; terminating = true;
|
||||
if (child.pid) { if (process.platform === 'win32') {
|
||||
if (onSpawn) treeKill = { done: false, error: null };
|
||||
execFile('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, error => {
|
||||
if (!treeKill) return; treeKill.done = true; treeKill.error = error;
|
||||
if (closedResult) finish(closedResult.code, closedResult.error);
|
||||
});
|
||||
} else { try { process.kill(-child.pid, 'SIGTERM'); } catch { child.kill('SIGTERM'); } } }
|
||||
killTimer = setTimeout(() => finish(null, null, true), 5000);
|
||||
};
|
||||
const timeout = setTimeout(() => { timedOut = true; terminate(); }, this.timeoutMs);
|
||||
signal.addEventListener('abort', terminate, { once: true });
|
||||
for (const name of ['stdout', 'stderr']) { child[name].on('data', bytes => append(name, streams[name].decoder.write(bytes))); child[name].on('end', () => append(name, streams[name].decoder.end())); }
|
||||
child.once('error', error => finish(null, error)); child.once('close', code => { rootClosed = true; finish(code); });
|
||||
if (onSpawn) child.once('spawn', () => { processInfo.pid = child.pid; try { onSpawn(processInfo); if (process.platform === 'win32') { monitorTree(); treeTimer = setInterval(monitorTree, 1200); } } catch (error) { ownershipError = error; terminate(); } });
|
||||
if (isPython) { child.stdin.on('error', () => {}); child.stdin.end(invocation.input); }
|
||||
if (signal.aborted) terminate();
|
||||
});
|
||||
const result = await runOwnedCommand(invocation,{cwd:safePath(project),signal,onSpawn,timeoutMs:this.timeoutMs,
|
||||
env:isPython ? pythonEnvironment() : projectEnvironment({NO_COLOR:'1',CI:'1'}),input:isPython?invocation.input:null});
|
||||
let collectedEvidence=null,collectedResult=null,evidenceError=null,cleanupError=null;
|
||||
const unknown=result.status==='unknown';
|
||||
if(isPython && !unknown && result.exitCode!==null) {
|
||||
try { const saved=readPythonEvidence(invocation,result.exitCode);collectedEvidence=saved.text;collectedResult=saved.result; }
|
||||
catch(error){evidenceError=error.message;}
|
||||
}
|
||||
const tests=check.kind==='test' ? isPython?collectedResult?.tests??null:parseTestEvidence(result.stdout.slice(-240000),check.framework) : null;
|
||||
const status=['unknown','cancelled','failed'].includes(result.status)?result.status
|
||||
: evidenceError||tests?.failed>0||collectedResult?.collectionErrors>0?'failed'
|
||||
: (check.kind==='test'&&(!tests||tests.total===0||tests.passed!==tests.total||tests.cancelled>0||collectedResult?.collectionSkipped>0)
|
||||
||isPython&&collectedResult?.compilation?.total===0)?'unverified':'passed';
|
||||
if(isPython&&!unknown){try{invocation.dispose();}catch(error){cleanupError=error.message;}}
|
||||
return {...result,status,tests,...(isPython?{engine:'python',python:pythonResultBinding(invocation),collectedEvidence,checkInput:invocation.input.toString('utf8'),
|
||||
compilation:collectedResult?.compilation??null,collectionErrors:collectedResult?.collectionErrors??null,collectionSkipped:collectedResult?.collectionSkipped??null,
|
||||
evidenceValidated:!!collectedResult,evidenceError,cleanupError,...(unknown?{hostEvidenceDirectory:invocation.directory}:{})}:{}),
|
||||
reason:result.reason||evidenceError||collectedResult?.collectorError||(collectedResult?.collectionErrors>0?'Python测试收集或类初始化有错误。':null)
|
||||
||(status==='unverified'?'测试为空、有跳过项,或没有可验证的测试数量。':undefined)};
|
||||
}
|
||||
|
||||
async stop(sessionId, jobId) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { verifyNodeBinding } from './environment/environment-inspector.mjs';
|
||||
import { verifyEnvironmentPreparation } from './environment/environment-evidence.mjs';
|
||||
import { inspectProject } from './project-inspector.mjs';
|
||||
import { ChangeSetManager } from './workspaces/change-sets.mjs';
|
||||
import { verifyPlanEvidence } from './context/request-plan.mjs';
|
||||
@@ -20,6 +22,7 @@ export function verifiedCheck(store, session, inspection) {
|
||||
const same = job.sourceFingerprint ? job.sourceFingerprint === inspection.sourceFingerprint : job.fingerprint === inspection.fingerprint;
|
||||
if (!same || !job.results.length || job.results.some(result => result.status !== 'passed' || result.exitCode !== 0)
|
||||
|| !job.results.some(result => result.kind === 'test' && result.tests?.passed > 0 && result.tests.passed === result.tests.total && !result.tests.failed && !result.tests.skipped && !result.tests.cancelled)) return null;
|
||||
try { verifyNodeBinding(store.project(session.projectId),job.environment); verifyEnvironmentPreparation(store,session.projectId,job.environment); } catch { return null; }
|
||||
for (const result of job.results) {
|
||||
if (!result.logArtifactId) return null;
|
||||
try {
|
||||
@@ -136,6 +139,7 @@ export class DeliveryReporter {
|
||||
browserVerification, browserChecks,
|
||||
taskPlan, taskPlanHistory, taskProofs,
|
||||
checks: checkJobs.map(value => ({ id: value.id, status: value.status, planId: value.planId,
|
||||
...(value.environment ? { environment:value.environment } : {}),
|
||||
contractArtifactId: this.store.core.check_plan.get(value.planId)?.contractArtifactId ?? null,
|
||||
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
|
||||
sourceFingerprint: value.sourceFingerprint ?? null, startedAt: value.startedAt, finishedAt: value.finishedAt,
|
||||
@@ -191,6 +195,12 @@ export function renderDeliveryMarkdown(report) {
|
||||
lines.push('', '## 实际检查', '', '| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |', '| --- | --- | --- | --- | --- |');
|
||||
for (const job of report.checks) for (const result of job.results) lines.push('| ' + [job.id.slice(0, 8) + ' / ' + result.command,
|
||||
job.stale ? '源码已变化 / ' + result.status : result.status, result.exitCode ?? '未知', result.tests ? result.tests.passed + '/' + result.tests.total : '不适用或未知', result.logSha256 ?? '未知'].map(escapeCell).join(' | ') + ' |');
|
||||
const environments=report.checks.filter(job=>job.environment);
|
||||
if(environments.length){
|
||||
lines.push('','### 实际依赖环境','','| 检查记录 | Node / npm | 声明与运行时输入 | 实际依赖字节 | 准备记录 |','| --- | --- | --- | --- | --- |');
|
||||
for(const job of environments)lines.push('| '+[job.id,job.environment.runtime.node.version+' / '+(job.environment.runtime.npm?.version??'未知'),job.environment.dependencyInputs,job.environment.installed.sha256??'没有依赖目录',job.environment.preparation?.jobId??'已有环境,无所属准备凭据'].map(escapeCell).join(' | ')+' |');
|
||||
lines.push('','环境准备只记录安装;以上工程检查结果另行判定。');
|
||||
}
|
||||
const pythonResults = report.checks.flatMap(job => job.results.filter(result => result.python));
|
||||
if (pythonResults.length) {
|
||||
lines.push('', '### Python实际执行', '', '| 检查 | 解释器 | 版本 | 结构化结果SHA256 |', '| --- | --- | --- | --- |');
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { environmentPlanSeal } from '../../shared/contracts/environment.mjs';
|
||||
import { environmentHash, environmentConflict } from './environment-inspector.mjs';
|
||||
|
||||
export function bindEnvironmentPreparation(store,projectId,binding) {
|
||||
if(!binding)return binding;
|
||||
const job=[...(store.core.environment_job?.values()??[])].findLast(job=>job.projectId===projectId&&job.status==='prepared'&&!job.stale&&!job.requiresVerification&&job.after?.identity===binding.identity);
|
||||
return {...binding,preparation:job?{jobId:job.id,planId:job.planId,sessionId:job.sessionId,taskId:job.taskId,runId:job.runId,
|
||||
logArtifactId:job.logArtifactId,logSha256:job.logSha256,environmentArtifactId:job.environmentArtifactId,environmentSha256:job.environmentSha256}:null};
|
||||
}
|
||||
export function verifyEnvironmentPreparation(store,projectId,binding) {
|
||||
if(!binding?.preparation)return;
|
||||
const reference=binding.preparation,job=store.owned('environment_job',reference.jobId,reference.sessionId),plan=store.owned('environment_plan',reference.planId,reference.sessionId);
|
||||
if(job.projectId!==projectId||job.taskId!==reference.taskId||job.runId!==reference.runId||job.status!=='prepared'||job.stale||job.requiresVerification
|
||||
||job.planId!==plan.id||job.after?.identity!==binding.identity||job.dependencyInputs!==binding.dependencyInputs
|
||||
||environmentHash(environmentPlanSeal(plan))!==job.planFingerprint)throw environmentConflict('检查引用的原依赖准备记录无法核对。');
|
||||
for(const [id,sha,kind]of [[plan.contractArtifactId,plan.contractSha256,'environment-plan'],[reference.logArtifactId,reference.logSha256,'environment-log'],[reference.environmentArtifactId,reference.environmentSha256,'environment-result']]) {
|
||||
const artifact=store.owned('artifact',id,reference.sessionId);
|
||||
if(artifact.taskId!==job.taskId||artifact.runId!==job.runId||artifact.sha256!==sha||artifact.kind!==kind)throw environmentConflict('依赖准备工件归属或SHA-256已变化。');
|
||||
store.artifactStore.read(artifact);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { safePath } from '../../server/files.mjs';
|
||||
import { projectWorkspaceIdentity } from '../../shared/contracts/workspaces.mjs';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
import { resolvePythonRuntime } from '../python-runtime.mjs';
|
||||
|
||||
export const environmentHash = value => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest('hex');
|
||||
export const environmentConflict = message => Object.assign(new Error(message), { status: 409 });
|
||||
const same = (a,b) => (process.platform === 'win32' ? path.resolve(a).toLowerCase() : path.resolve(a)) === (process.platform === 'win32' ? path.resolve(b).toLowerCase() : path.resolve(b));
|
||||
export function fileIdentity(file, maximum = 128 * 1024 * 1024) {
|
||||
const stat = fs.lstatSync(file), resolved = fs.realpathSync.native(file);
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw environmentConflict('环境输入需要大小受限的独立常规文件:' + path.basename(file));
|
||||
const bytes = fs.readFileSync(file), after = fs.lstatSync(file);
|
||||
if (stat.ino !== after.ino || stat.mtimeMs !== after.mtimeMs || stat.ctimeMs !== after.ctimeMs || bytes.length !== after.size) throw environmentConflict('读取期间环境输入已变化,请重新诊断。');
|
||||
return { path: resolved, sha256: environmentHash(bytes), bytes: bytes.length };
|
||||
}
|
||||
function declaration(project, name) {
|
||||
const target = safePath(project, name, true);
|
||||
try { fs.lstatSync(target); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
||||
const identity = fileIdentity(target, 8 * 1024 * 1024), text = fs.readFileSync(target, 'utf8');
|
||||
if (environmentHash(text) !== identity.sha256) throw environmentConflict('环境声明在读取期间变化。');
|
||||
return { ...identity, text };
|
||||
}
|
||||
export function npmRuntime(runtimeDirectory = null) {
|
||||
const cli = [runtimeDirectory, path.dirname(process.execPath)].filter(Boolean)
|
||||
.map(directory => path.join(directory, 'node_modules', 'npm', 'bin', 'npm-cli.js')).find(file => fs.existsSync(file));
|
||||
const node = { ...fileIdentity(process.execPath), version: process.version };
|
||||
if (!cli) return { status: 'missing', node, npm: null, message: '宿主没有固定npm CLI,请使用随包Node启动。' };
|
||||
const manifest = fileIdentity(path.join(path.dirname(cli), '..', 'package.json'), 1024 * 1024);
|
||||
const version = JSON.parse(fs.readFileSync(manifest.path, 'utf8')).version;
|
||||
return { status: 'available', node, npm: { ...fileIdentity(cli), version, manifest } };
|
||||
}
|
||||
|
||||
// Hash actual dependency bytes. A hidden lockfile alone cannot prove that the
|
||||
// installed packages are still the ones a previous command checked.
|
||||
export function dependencyTree(project, { maximumFiles = 40000, maximumBytes = 512 * 1024 * 1024 } = {}) {
|
||||
const root = path.join(safePath(project), 'node_modules'), hash = createHash('sha256');
|
||||
let files = 0, bytes = 0, entriesSeen = 0;
|
||||
try {fs.lstatSync(root);}catch(error){if(error.code==='ENOENT')return { status:'missing',files:0,bytes:0,sha256:null };throw error;}
|
||||
const visit = (directory, depth = 0) => {
|
||||
if (depth > 100) throw new Error('依赖目录过深');
|
||||
const stat = fs.lstatSync(directory);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || !same(fs.realpathSync.native(directory), directory)) throw new Error('依赖目录包含链接或路径替换');
|
||||
const entries=fs.readdirSync(directory).sort();
|
||||
for (const name of entries) {
|
||||
const target = path.join(directory,name), relative = path.relative(root,target).replaceAll('\\','/'), info = fs.lstatSync(target);
|
||||
if (++entriesSeen > maximumFiles) throw new Error('依赖文件超过诊断上限');
|
||||
if (info.isSymbolicLink()) {
|
||||
const real = fs.realpathSync.native(target), within = path.relative(root,real);
|
||||
if (path.isAbsolute(within) || within === '..' || within.startsWith('..' + path.sep)) throw new Error('依赖链接指向工程以外');
|
||||
files++; hash.update(JSON.stringify([relative,'link',fs.readlinkSync(target)]) + '\n'); continue;
|
||||
}
|
||||
// Build tools may leave empty temporary directories. Only file/link
|
||||
// content affects this identity; every directory is still traversed and
|
||||
// checked for replacement, links and the entry/depth budgets.
|
||||
if (info.isDirectory()) { visit(target,depth+1); continue; }
|
||||
files++;
|
||||
bytes += info.size;
|
||||
if (!info.isFile() || info.nlink !== 1 || bytes > maximumBytes) throw new Error('依赖类型或大小超出可核验范围');
|
||||
const input = fileIdentity(target,maximumBytes);
|
||||
hash.update(JSON.stringify([relative,input.sha256,input.bytes,info.mode & 0o777]) + '\n');
|
||||
}
|
||||
if(JSON.stringify(entries)!==JSON.stringify(fs.readdirSync(directory).sort()))throw new Error('读取期间依赖目录发生变化');
|
||||
};
|
||||
try { visit(root); return { status: 'verified', files, bytes, sha256: hash.digest('hex') }; }
|
||||
catch (error) { return { status: 'unverified', files, bytes, sha256: null, message: error.message }; }
|
||||
}
|
||||
function json(file, name) {
|
||||
try { const result = JSON.parse(file.text); if (!result || Array.isArray(result) || typeof result !== 'object') throw new Error(); return result; }
|
||||
catch { throw environmentConflict(name + '不是有效JSON对象。'); }
|
||||
}
|
||||
export function inspectNodeEnvironment(project, { runtimeDirectory = null, treeLimits } = {}) {
|
||||
const runtime = npmRuntime(runtimeDirectory), manifestFile = declaration(project,'package.json');
|
||||
if (!manifestFile) return null;
|
||||
const manifest = json(manifestFile,'package.json'), lockFile = declaration(project,'package-lock.json');
|
||||
const manager = manifest.packageManager?.split?.('@')[0] ?? (['pnpm-lock.yaml','yarn.lock','bun.lock','bun.lockb'].find(name=>fs.existsSync(safePath(project,name,true))) ? 'other' : 'npm');
|
||||
const issues = [], lock = lockFile ? json(lockFile,'package-lock.json') : null;
|
||||
const declarations = [manifestFile,lockFile].filter(Boolean).map(({text,...value})=>value);
|
||||
const dependencies = Object.fromEntries(Object.entries({ ...manifest.dependencies, ...manifest.devDependencies, ...manifest.optionalDependencies }).sort(([a],[b])=>a.localeCompare(b)));
|
||||
if (manager !== 'npm') issues.push('当前自动准备仅支持npm,已识别包管理器:' + manager);
|
||||
if (manifest.workspaces) issues.push('当前自动准备不支持npm workspaces。');
|
||||
if (fs.existsSync(safePath(project,'npm-shrinkwrap.json',true))) issues.push('检测到npm-shrinkwrap.json,当前准备器只接受package-lock.json。');
|
||||
if (!lock) issues.push('缺少package-lock.json;请先人工生成并审查锁文件。');
|
||||
else if (![2,3].includes(lock.lockfileVersion) || !lock.packages || !lock.packages['']) issues.push('准备器需要package-lock v2或v3和完整packages字段。');
|
||||
const rootLock = lock?.packages?.[''];
|
||||
if (rootLock) for (const name of ['dependencies','devDependencies','optionalDependencies']) {
|
||||
const normalized = value => Object.entries(value ?? {}).sort(([a],[b])=>a.localeCompare(b));
|
||||
if (JSON.stringify(normalized(manifest[name])) !== JSON.stringify(normalized(rootLock[name]))) issues.push('声明与锁文件的' + name + '不一致。');
|
||||
}
|
||||
const packages = [];
|
||||
for (const [relative,value] of Object.entries(lock?.packages ?? {})) {
|
||||
if (!relative) continue;
|
||||
if (packages.length >= 5000) { issues.push('锁文件包数超过5000的支持范围。'); break; }
|
||||
if (!/^node_modules\//.test(relative) || relative.includes('\\') || relative.split('/').some(part=>!part||part==='..'||part==='.'||part.includes(':')) || value?.link || !value || typeof value !== 'object') {
|
||||
issues.push('锁文件含本地链接、工作区或不支持的包路径。'); continue;
|
||||
}
|
||||
let source = null;
|
||||
try {
|
||||
const url = new URL(value.resolved);
|
||||
if (url.username || url.password || url.search || url.hash || !/^https?:$/.test(url.protocol)) throw new Error();
|
||||
source = { origin: url.origin, url: url.href };
|
||||
} catch { issues.push('锁文件存在未固定的包来源:' + relative); }
|
||||
if (!/^sha512-[A-Za-z0-9+/]{86}==$/.test(value.integrity ?? '')) issues.push('锁文件缺少sha512完整性:' + relative);
|
||||
packages.push({ path:relative, version:value.version ?? null, source, integrity:value.integrity ?? null, hasInstallScript:value.hasInstallScript === true, optional:value.optional === true });
|
||||
}
|
||||
for (const [name,version] of Object.entries(dependencies)) if (typeof version !== 'string' || /^(?:file:|link:|workspace:|git|https?:|ssh:|github:)|[\\]/i.test(version)) issues.push('不支持本地或未固定依赖声明:' + name);
|
||||
const installed = dependencyTree(project,treeLimits), missing = [], mismatched = [];
|
||||
for (const [name] of Object.entries(dependencies)) {
|
||||
if (!/^(?:@[a-z0-9_.-]+\/)?[a-z0-9_.-]+$/i.test(name)) { issues.push('依赖名称无效。'); continue; }
|
||||
const packagePath = 'node_modules/' + name + '/package.json';
|
||||
try { const current = declaration(project,packagePath), info = current && json(current,packagePath);
|
||||
if (!info) missing.push(name);
|
||||
else if (packages.find(value=>value.path==='node_modules/'+name)?.version !== info.version) mismatched.push(name);
|
||||
} catch { mismatched.push(name); }
|
||||
}
|
||||
const npmrc = []; for (let directory=safePath(project);;directory=path.dirname(directory)) {
|
||||
if (fs.existsSync(path.join(directory,'.npmrc'))) npmrc.push(path.join(directory,'.npmrc'));
|
||||
if (path.dirname(directory)===directory) break;
|
||||
}
|
||||
if (npmrc.length) issues.push('项目或父目录有.npmrc;准备器不读取或继承其中凭据,请在无此配置的隔离工作区准备。');
|
||||
const lifecycle = Object.entries(manifest.scripts ?? {}).filter(([name])=>['preinstall','install','postinstall','prepublish','preprepare','prepare','postprepare'].includes(name))
|
||||
.map(([name,script])=>({name,script:String(script).slice(0,6000)}));
|
||||
const inputs = { declarations:declarations.map(({path:file,...value})=>({name:path.basename(file),...value})),
|
||||
node:{sha256:runtime.node.sha256,version:runtime.node.version}, npm:runtime.npm?{sha256:runtime.npm.sha256,version:runtime.npm.version,manifestSha256:runtime.npm.manifest.sha256}:null };
|
||||
const ready = !missing.length && !mismatched.length && (!Object.keys(dependencies).length || installed.status==='verified');
|
||||
return { kind:'node', manager, runtime, declarations, lockVersion:lock?.lockfileVersion ?? null, packageCount:packages.length,
|
||||
packages, dependencies:Object.keys(dependencies), missing, mismatched, installed, lifecycle, installScriptPackages:packages.filter(value=>value.hasInstallScript).map(value=>value.path),
|
||||
sources:[...new Set(packages.flatMap(value=>value.source?[value.source.origin]:[]))].sort(),
|
||||
issues:[...new Set(issues)], preparable:runtime.status==='available' && !issues.length,
|
||||
status:manager!=='npm'?'unsupported':ready?'ready':'needs_preparation', dependencyInputs:environmentHash(inputs),
|
||||
identity:environmentHash({inputs,installed,root:safePath(project),runtime,manager,issues:[...new Set(issues)]}), inputs };
|
||||
}
|
||||
export function nodeEnvironmentBinding(project, options) {
|
||||
const node = inspectNodeEnvironment(project,options);
|
||||
return node ? { kind:'node',identity:node.identity,dependencyInputs:node.dependencyInputs,status:node.status,
|
||||
installed:node.installed, declarations:node.declarations, runtime:node.runtime } : null;
|
||||
}
|
||||
export function verifyNodeBinding(project, binding) {
|
||||
if (!binding) return;
|
||||
const current = nodeEnvironmentBinding(project,{runtimeDirectory:binding.runtime?.npm ? path.resolve(binding.runtime.npm.path,'../../../..') : null});
|
||||
if (!current || current.identity !== binding.identity) throw environmentConflict('检查绑定的运行时、声明或实际依赖已变化,请重新诊断和检查。');
|
||||
}
|
||||
async function inspectPythonEnvironment(project, inspection, options) {
|
||||
if (!inspection.python) return null;
|
||||
const runtime = await resolvePythonRuntime(project,{executable:options.pythonExecutable ?? process.env.AGENT_WORKBENCH_PYTHON_PATH ?? inspection.python.preferredExecutable});
|
||||
const declarations = ['pyproject.toml','requirements.txt','requirements-dev.txt','Pipfile.lock','poetry.lock','uv.lock','pytest.ini','setup.cfg']
|
||||
.map(name=>declaration(project,name)).filter(Boolean).map(({text,...value})=>value);
|
||||
let pytest = {status:'missing',version:null,metadata:null};
|
||||
if (runtime.executable) {
|
||||
const directory = path.dirname(runtime.logicalExecutable), bases = [path.resolve(directory,'..','Lib','site-packages'),path.resolve(directory,'Lib','site-packages')];
|
||||
if (runtime.version) bases.push(path.resolve(directory,'..','lib','python'+runtime.version.split('.').slice(0,2).join('.'),'site-packages'));
|
||||
for (const base of bases) {
|
||||
if (!fs.existsSync(base)) continue;
|
||||
const matches = fs.readdirSync(base).filter(name=>/^pytest-[\d.]+\.dist-info$/i.test(name));
|
||||
if (matches.length === 1) { const metadata=fileIdentity(path.join(base,matches[0],'METADATA'),1024*1024);
|
||||
pytest={status:'available',version:matches[0].slice(7,-10),metadata}; break; }
|
||||
}
|
||||
}
|
||||
return {kind:'python',status:runtime.status,framework:inspection.python.framework,runtime,pytest,declarations,
|
||||
preparation:'manual',message:'未执行项目代码或导入pytest;本阶段不自动安装Python依赖。项目内解释器的版本探测等待检查审批。'};
|
||||
}
|
||||
export async function diagnoseEnvironment(project, options = {}) {
|
||||
const inspection = await inspectProject(project), node = inspectNodeEnvironment(project,options), python = await inspectPythonEnvironment(project,inspection,options);
|
||||
return {schemaVersion:1,inspectedAt:new Date().toISOString(),projectId:project.id,root:safePath(project),workspace:projectWorkspaceIdentity(project),
|
||||
fingerprint:inspection.fingerprint,sourceFingerprint:inspection.sourceFingerprint,scope:inspection.scope,node,python,
|
||||
status:!node&&!python?'unsupported':node?.status==='needs_preparation'?'needs_preparation':node?.status??python.status};
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { diagnoseEnvironment, nodeEnvironmentBinding, environmentHash as hash, environmentConflict as conflict, fileIdentity } from './environment-inspector.mjs';
|
||||
import { assertEnvironmentsResolved, ENVIRONMENT_ACTIVE, environmentPlanSeal as planSeal } from '../../shared/contracts/environment.mjs';
|
||||
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../../shared/contracts/workspaces.mjs';
|
||||
import { workerForSession } from '../../shared/contracts/workers.mjs';
|
||||
import { assertMcpResolved } from '../tools/mcp-contract.mjs';
|
||||
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
|
||||
import { verifyEvaluationSources } from '../evaluation/provenance.mjs';
|
||||
import { projectEnvironment } from '../process-environment.mjs';
|
||||
import { runOwnedCommand } from '../owned-command.mjs';
|
||||
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
export const publicEnvironmentDiagnostic = record => ({ ...record, node:record.node ? (({packages,...node})=>node)(record.node) : null });
|
||||
|
||||
export class EnvironmentManager {
|
||||
constructor(store,{runtimeDirectory=null,pythonExecutable=null,redact=String,projectBusy=()=>false,timeoutMs=300000,allowHttpLoopback=false}={}) {
|
||||
Object.assign(this,{store,runtimeDirectory,pythonExecutable,redact,projectBusy,timeoutMs,allowHttpLoopback});
|
||||
this.active=new Map(); this.projects=new Map();
|
||||
}
|
||||
isActive(sessionId) { return [...this.active.values()].some(value=>value.sessionId===sessionId); }
|
||||
projectActive(projectId) { return this.projects.has(projectId); }
|
||||
options() { return {runtimeDirectory:this.runtimeDirectory,pythonExecutable:this.pythonExecutable}; }
|
||||
artifact(session,runId,value,kind) {
|
||||
const artifact=this.store.artifactStore.write(session,this.store.owned('run',runId,session.id),typeof value==='string'?this.redact(value):JSON.parse(this.redact(JSON.stringify(value))),{kind});
|
||||
this.store.core.artifact.set(artifact.id,artifact); return artifact;
|
||||
}
|
||||
async diagnose(session) {
|
||||
if (!session.taskId || !session.runId) throw conflict('先建立项目任务,再记录本任务的环境诊断。');
|
||||
const taskId=session.taskId,runId=session.runId;
|
||||
await verifyWorkspaceProject(this.store,this.store.project(session.projectId));
|
||||
const diagnostic=await diagnoseEnvironment(this.store.project(session.projectId),this.options());
|
||||
if(taskId!==session.taskId||runId!==session.runId) throw conflict('诊断期间任务已切换,请重新诊断。');
|
||||
const record={...diagnostic,id:randomUUID(),sessionId:session.id,taskId,runId,createdAt:at()};
|
||||
const artifact=this.artifact(session,runId,record,'environment-diagnostic');record.artifactId=artifact.id;record.artifactSha256=artifact.sha256;
|
||||
this.store.putRecord('environment_diagnostic',session,record,'environment.diagnosed');return record;
|
||||
}
|
||||
idle(session,{exceptSessionId=null}={}) {
|
||||
assertEnvironmentsResolved(this.store,session.projectId);
|
||||
assertChangeSetsResolved(this.store,session.projectId,{includePrepared:true});
|
||||
assertWorkspacesResolved(this.store,session.projectId,{includePrepared:true});
|
||||
assertMcpResolved(this.store,session.projectId);
|
||||
if(this.projectActive(session.projectId)||this.projectBusy(session.projectId,exceptSessionId)) throw conflict('工程已有执行,请等待结束后准备依赖。');
|
||||
if(session.changes.some(value=>['pending','conflict'].includes(value.status))) throw conflict('先处理待审查的工程改动,再准备依赖。');
|
||||
const worker=workerForSession(this.store,session);
|
||||
if(worker && !worker.evaluation) throw conflict('受限协作的依赖请在独立工程准备完成后再创建协作。');
|
||||
if(worker?.status==='completed') throw conflict('评测子成果已经封存,不能再次准备依赖。');
|
||||
}
|
||||
registry(value='https://registry.npmjs.org/') {
|
||||
let url;try{url=new URL(value);}catch{throw conflict('注册源需要有效的HTTPS地址。');}
|
||||
const local=this.allowHttpLoopback && url.protocol==='http:' && ['127.0.0.1','localhost','[::1]'].includes(url.hostname);
|
||||
if((url.protocol!=='https:'&&!local)||url.username||url.password||url.search||url.hash||url.pathname!=='/') throw conflict('注册源只接受不含凭据、查询参数的HTTPS根地址。');
|
||||
return url.href;
|
||||
}
|
||||
async plan(session,input={}, {source='user'}={}) {
|
||||
if(!input||Array.isArray(input)||Object.keys(input).some(key=>!['registry','scripts','offline'].includes(key))) throw conflict('依赖计划只接受注册源、生命周期脚本策略和离线选择。');
|
||||
if(input.scripts!==undefined&&!['skip','allow'].includes(input.scripts)||input.offline!==undefined&&typeof input.offline!=='boolean') throw conflict('脚本策略或离线选项无效。');
|
||||
this.idle(session,{exceptSessionId:source==='agent'?session.id:null});
|
||||
await verifyEvaluationSources(this.store,session);
|
||||
const project=this.store.project(session.projectId);
|
||||
if(!project.workspace) throw conflict('依赖准备需要工作台管理的独立工作区。请先创建并打开独立工作区。');
|
||||
const diagnostic=await this.diagnose(session), node=diagnostic.node;
|
||||
this.idle(session,{exceptSessionId:source==='agent'?session.id:null});
|
||||
if(!node?.preparable) throw conflict(node?.issues?.join('\n')||'当前工程不支持自动准备npm依赖。');
|
||||
if(node.installed.status==='unverified') throw conflict('当前依赖目录无法完整核验,请保留现场并处理链接或诊断范围问题。');
|
||||
const registry=this.registry(input.registry),origin=new URL(registry).origin;
|
||||
if(node.packages.some(value=>value.source?.origin!==origin)) throw conflict('锁文件下载来源与所选注册源不同。请人工审查锁文件,系统不会静默改源。');
|
||||
const scripts=input.scripts??'skip';
|
||||
const id=randomUUID(),directory=path.join(this.store.directory,'environments','plans',id);
|
||||
fs.mkdirSync(directory,{recursive:true});
|
||||
if(fs.realpathSync.native(directory)!==path.resolve(directory))throw conflict('环境配置目录经过链接,不能准备计划。');
|
||||
const configFiles=['user.npmrc','global.npmrc'].map(name=>{const target=path.join(directory,name);fs.writeFileSync(target,'',{flag:'wx'});return fileIdentity(target);});
|
||||
const cacheDirectory=path.join(this.store.directory,'environments','cache',project.id);
|
||||
const invocation={executable:node.runtime.node.path,args:[node.runtime.npm.path,'ci','--registry='+registry,'--ignore-scripts='+(scripts==='skip'),
|
||||
'--audit=false','--fund=false','--update-notifier=false','--include=dev','--include=optional','--strict-ssl=true',
|
||||
'--userconfig='+configFiles[0].path,'--globalconfig='+configFiles[1].path,'--cache='+cacheDirectory,
|
||||
'--fetch-retries=0','--fetch-timeout=60000','--offline='+(input.offline===true)]};
|
||||
const plan={schemaVersion:1,id,sessionId:session.id,projectId:project.id,taskId:session.taskId,runId:session.runId,diagnosticId:diagnostic.id,
|
||||
root:project.root,workspace:projectWorkspaceIdentity(project),sourceFingerprint:diagnostic.sourceFingerprint,nodeIdentity:node.identity,
|
||||
dependencyInputs:node.dependencyInputs,registry,scripts,offline:input.offline===true,timeoutMs:this.timeoutMs,invocation,configFiles,cacheDirectory,
|
||||
lifecycle:node.lifecycle,installScriptPackages:node.installScriptPackages,packageCount:node.packageCount,status:'planned',createdAt:at(),jobId:null};
|
||||
plan.fingerprint=hash(planSeal(plan));
|
||||
const artifact=this.artifact(session,plan.runId,planSeal(plan),'environment-plan');plan.contractArtifactId=artifact.id;plan.contractSha256=artifact.sha256;
|
||||
this.store.putRecord('environment_plan',session,plan,'environment.planned');return plan;
|
||||
}
|
||||
own(session,id,fingerprint) {
|
||||
const plan=this.store.owned('environment_plan',id,session.id);
|
||||
if(plan.taskId!==session.taskId||plan.runId!==session.runId||fingerprint!==plan.fingerprint||hash(planSeal(plan))!==plan.fingerprint)throw conflict('环境计划身份、任务或执行范围已变化,请重新准备计划。');
|
||||
const artifact=this.store.owned('artifact',plan.contractArtifactId,session.id);
|
||||
if(artifact.kind!=='environment-plan'||artifact.sha256!==plan.contractSha256||this.store.artifactStore.read(artifact)!==this.redact(JSON.stringify(planSeal(plan))))throw conflict('原环境计划工件无法核对。');
|
||||
return plan;
|
||||
}
|
||||
async verify(session,plan) {
|
||||
const project=this.store.project(session.projectId);await verifyWorkspaceProject(this.store,project);await verifyEvaluationSources(this.store,session);
|
||||
if(JSON.stringify(projectWorkspaceIdentity(project))!==JSON.stringify(plan.workspace))throw conflict('准备目标的工作区身份已变化。');
|
||||
const node=nodeEnvironmentBinding(project,this.options());
|
||||
if(!node||node.identity!==plan.nodeIdentity)throw conflict('声明、锁文件、运行时或当前依赖已变化,请重新准备计划。');
|
||||
const inspection=await inspectProject(project);
|
||||
if(!inspection.scope.complete||inspection.sourceFingerprint!==plan.sourceFingerprint)throw conflict('工程来源在计划创建后变化,请重新准备。');
|
||||
for(const original of plan.configFiles)if(JSON.stringify(fileIdentity(original.path))!==JSON.stringify(original))throw conflict('隔离npm配置已变化。');
|
||||
return node;
|
||||
}
|
||||
async start(session,id,fingerprint,{approved=false,signal,source='user',approvalId=null}={}) {
|
||||
if(approved!==true)throw conflict('请核对固定依赖命令、下载来源和脚本策略后明确批准。');
|
||||
this.idle(session,{exceptSessionId:source==='agent'?session.id:null});
|
||||
const plan=this.own(session,id,fingerprint);
|
||||
if(plan.status!=='planned'||plan.jobId)throw conflict('这个依赖计划已经使用;原结果保留,不自动重放。重新执行需要新计划和审批。');
|
||||
const controller=new AbortController(),job={id:randomUUID(),sessionId:session.id,projectId:session.projectId,taskId:plan.taskId,runId:plan.runId,
|
||||
planId:plan.id,planFingerprint:plan.fingerprint,dependencyInputs:plan.dependencyInputs,source,approvalId,status:'queued',createdAt:at(),startedAt:null,finishedAt:null,
|
||||
command:['node',...plan.invocation.args].join(' '),root:plan.root,process:null,requiresVerification:false,logExcerpt:'',result:null};
|
||||
const active={sessionId:session.id,projectId:session.projectId,controller,promise:null};
|
||||
this.active.set(job.id,active);this.projects.set(session.projectId,job.id);
|
||||
try {
|
||||
await this.verify(session,plan);
|
||||
this.own(session,id,fingerprint);
|
||||
if(signal?.aborted||controller.signal.aborted)throw conflict('环境准备在执行前已停止。');
|
||||
if(!approvalId){const approval={id:randomUUID(),environmentPlanId:plan.id,taskId:plan.taskId,runId:plan.runId,projectId:plan.projectId,
|
||||
command:job.command,cwd:plan.root,reason:'核对不可变依赖计划后准备所属工作区',shell:'npm · 直接进程',status:'approved',createdAt:at(),decidedAt:at()};session.approvals.push(approval);job.approvalId=approval.id;}
|
||||
plan.status='consumed';plan.jobId=job.id;
|
||||
this.store.putRecord('environment_job',session,job,'environment.queued');
|
||||
const combined=signal?AbortSignal.any([signal,controller.signal]):controller.signal;
|
||||
active.promise=this.execute(session,plan,job,combined).finally(()=>{this.active.delete(job.id);this.projects.delete(session.projectId);});
|
||||
active.promise.catch(()=>{});return {job,promise:active.promise};
|
||||
}catch(error){this.active.delete(job.id);this.projects.delete(session.projectId);throw error;}
|
||||
}
|
||||
async execute(session,plan,job,signal) {
|
||||
let dispatched=false,recorded=false;
|
||||
try {
|
||||
await this.verify(session,plan);signal.throwIfAborted();
|
||||
fs.mkdirSync(plan.cacheDirectory,{recursive:true});
|
||||
if(fs.realpathSync.native(plan.cacheDirectory)!==path.resolve(plan.cacheDirectory))throw conflict('npm缓存目录经过链接,准备已拒绝。');
|
||||
job.status='running';job.startedAt=at();this.store.save(session,{type:'environment.running',detail:{jobId:job.id}});
|
||||
let lastUpdate=0;
|
||||
const result=await runOwnedCommand(plan.invocation,{cwd:plan.root,signal,timeoutMs:plan.timeoutMs,
|
||||
env:projectEnvironment({CI:'1',NO_COLOR:'1',NPM_CONFIG_USERCONFIG:plan.configFiles[0].path,NPM_CONFIG_GLOBALCONFIG:plan.configFiles[1].path,
|
||||
NPM_CONFIG_CACHE:plan.cacheDirectory,NPM_CONFIG_REGISTRY:plan.registry,NPM_CONFIG_IGNORE_SCRIPTS:String(plan.scripts==='skip')}),
|
||||
onSpawn:info=>{dispatched=true;job.process={...info};this.store.save(session,{type:'environment.process',detail:{jobId:job.id}});},
|
||||
onOutput:(stream,text)=>{job.logExcerpt=this.redact((job.logExcerpt+text).slice(-8000));if(Date.now()-lastUpdate>750){lastUpdate=Date.now();this.store.save(session,{type:'environment.output',detail:{jobId:job.id,stream}});}}});
|
||||
const {stdout,stderr,...saved}=result;
|
||||
const log=this.artifact(session,job.runId,`$ ${job.command}\n\n[stdout]\n${stdout}\n\n[stderr]\n${stderr}`,'environment-log');
|
||||
job.logArtifactId=log.id;job.logSha256=log.sha256;job.logExcerpt=this.redact((stdout+'\n'+stderr).slice(-8000));job.result=saved;job.process=result.process??job.process;
|
||||
recorded=true;job.status=result.status==='passed'?'prepared':result.status;job.requiresVerification=result.status==='unknown';
|
||||
const after=await this.diagnose(session);
|
||||
const artifact=this.artifact(session,job.runId,after,'environment-result');job.environmentArtifactId=artifact.id;job.environmentSha256=artifact.sha256;
|
||||
job.after=nodeEnvironmentBinding(this.store.project(session.projectId),this.options());
|
||||
if(after.sourceFingerprint!==plan.sourceFingerprint||job.after?.dependencyInputs!==plan.dependencyInputs){job.stale=true;if(job.status==='prepared')job.status='stale';}
|
||||
if(job.status==='prepared'&&job.after?.status!=='ready')job.status='unverified';
|
||||
this.store.invalidateChecks(session.projectId,'工作区依赖准备已执行,旧检查环境需要重新核验。');
|
||||
job.summary=job.status==='prepared'?'依赖命令完成,实际依赖字节已记录。请继续执行工程检查。':job.status==='cancelled'?'准备已停止,部分依赖和原日志保留。':job.status==='unknown'?'所属进程或执行结果未知,请核对原记录。':job.status==='stale'?'准备期间源码或锁文件已变化,原结果保留,请重新诊断。':'依赖准备未满足条件,请查看实际退出码和原日志。';
|
||||
} catch(error) {
|
||||
job.status=dispatched&&!recorded?'unknown':signal.aborted?'cancelled':error.status===409?'stale':'failed';
|
||||
job.requiresVerification=job.status==='unknown';job.summary=this.redact(error.message??String(error));
|
||||
} finally {job.finishedAt=at();this.store.save(session,{type:'environment.finished',detail:{jobId:job.id,status:job.status}});}
|
||||
return job;
|
||||
}
|
||||
async reconcile(session,id,fingerprint) {
|
||||
const job=this.store.owned('environment_job',id,session.id);
|
||||
if(this.active.has(job.id)||ENVIRONMENT_ACTIVE.has(job.status)||!job.requiresVerification||job.reconciliation||fingerprint!==job.planFingerprint)throw conflict('只有原中断的未知准备记录可以核对。');
|
||||
const observation=job.process?.pid?await readOwnedProcessTree(job.process):{supported:true,processes:[],note:'原记录未登记已启动进程'};
|
||||
if(!observation.supported||observation.processes.length)throw conflict('原所属进程仍存在或无法核对;不会按历史PID杀进程。');
|
||||
const diagnostic=await this.diagnose(session);
|
||||
const reconciliation={observedAt:at(),observation,diagnosticId:diagnostic.id,note:'已核对原进程结束并保留当前依赖现场;不补造原安装成功或重放命令。'};
|
||||
const artifact=this.artifact(session,job.runId,reconciliation,'environment-reconciliation');
|
||||
job.reconciliation={...reconciliation,artifactId:artifact.id,sha256:artifact.sha256};job.requiresVerification=false;
|
||||
this.store.save(session,{type:'environment.reconciled',detail:{jobId:job.id}});return job;
|
||||
}
|
||||
async stop(sessionId,id=null) {
|
||||
if(id)this.store.owned('environment_job',id,sessionId);
|
||||
const entries=[...this.active.entries()].filter(([key,value])=>value.sessionId===sessionId&&(!id||key===id));
|
||||
for(const [key,value]of entries){value.controller.abort(new Error('用户停止依赖准备'));const job=this.store.core.environment_job.get(key);if(job){job.status='stopping';this.store.save(this.store.session(sessionId),{type:'environment.stopping',detail:{jobId:key}});}}
|
||||
await Promise.all(entries.map(([,value])=>value.promise));
|
||||
}
|
||||
async stopAll(){await Promise.all([...new Set([...this.active.values()].map(value=>value.sessionId))].map(id=>this.stop(id)));}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import { workerUsage, COLLABORATION_CLOSED } from '../../shared/contracts/worker
|
||||
import { evaluationInput, evaluationSeal, evaluationSampleSeal, evaluationHash, evaluationSummary, evaluationConflict } from '../../shared/contracts/evaluations.mjs';
|
||||
import { evaluationRecord, preparedSample, verifyEvaluationSources } from './provenance.mjs';
|
||||
import { createCheckList } from '../project-inspector.mjs';
|
||||
import { nodeEnvironmentBinding } from '../environment/environment-inspector.mjs';
|
||||
import { verifyNodeBinding } from '../environment/environment-inspector.mjs';
|
||||
import { verifyEnvironmentPreparation } from '../environment/environment-evidence.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const identity = source => Object.fromEntries(['root','head','reference','branch','gitDir','commonDir','indexSha256','statusSha256','sourceFingerprint','treeSha256','configuration','filterDrivers'].map(key => [key, source[key]]));
|
||||
@@ -98,6 +101,11 @@ export class EvaluationManager {
|
||||
const commands = inventories.map(value=>commandView(createCheckList(value.inspection,sample.checks)));
|
||||
if (!commands[0].some(check=>check.kind==='test') || JSON.stringify(commands[0])!==JSON.stringify(commands[1])) throw evaluationConflict('样本必须包含同源的真实测试检查。');
|
||||
sample.files = inventories[0].files; sample.commands = commands[0]; sample.children = group.children.map(child=>({id:child.id,role:child.evaluation.role,projectId:child.projectId,sessionId:child.sessionId,taskId:child.taskId}));
|
||||
const environments=group.children.map(child=>nodeEnvironmentBinding(this.store.project(child.projectId),{runtimeDirectory:this.runtime.checkRunner().runtimeDirectory}));
|
||||
if(environments.some(Boolean)) {
|
||||
if(!environments[0]||!environments[1]||environments[0].dependencyInputs!==environments[1].dependencyInputs)throw evaluationConflict('原版与候选的依赖声明或Node/npm运行时不同。');
|
||||
sample.environmentInputs={kind:'node',dependencyInputs:environments[0].dependencyInputs};
|
||||
}
|
||||
const artifact = this.artifact(session,batch,evaluationSampleSeal(batch,sample),'evaluation-sample');
|
||||
sample.contractArtifactId = artifact.id; sample.contractSha256 = artifact.sha256;
|
||||
preparedSample(this.store,batch,sample); signal.throwIfAborted();
|
||||
@@ -130,6 +138,10 @@ export class EvaluationManager {
|
||||
return this.launch(session,batch,sample,'candidate_running',async signal=>{
|
||||
const remaining=this.remaining(batch),group=this.group(session,batch,sample),child=group.children.find(child=>child.evaluation.role==='candidate');
|
||||
this.selectParent(session,group);await verifyEvaluationSources(this.store,this.store.session(child.sessionId));signal.throwIfAborted();
|
||||
if(sample.environmentInputs){
|
||||
const baseline=this.store.core.check_job.get(sample.baselineJobId),candidate=nodeEnvironmentBinding(this.store.project(child.projectId),{runtimeDirectory:this.runtime.checkRunner().runtimeDirectory});
|
||||
if(!baseline?.environment||!candidate||baseline.environment.dependencyInputs!==candidate.dependencyInputs||baseline.environment.installed.sha256!==candidate.installed.sha256)throw evaluationConflict('候选与原版检查的实际依赖环境不同。请保留原结果,先核对两侧环境;已尝试原版不重放。');
|
||||
}
|
||||
group.startedAt ??= at();group.deadline ??= Date.now()+remaining; group.deadline=Math.min(group.deadline,batch.deadline);
|
||||
const started=this.runtime.workerManager().start(session,group.id,group.fingerprint,child.id);
|
||||
const stop=()=>{void this.runtime.workerManager().stopParent(session.id);};signal.addEventListener('abort',stop,{once:true});
|
||||
@@ -151,7 +163,7 @@ export class EvaluationManager {
|
||||
const extra={};for(const key of ['metricsArtifactId','inputArtifactId'])if(result[key]){const file=this.store.owned('artifact',result[key],owner.id);this.store.artifactStore.read(file);extra[key]={id:file.id,sha256:file.sha256};}
|
||||
return {name:result.name,command:result.command,status:result.status,exitCode:result.exitCode,durationMs:result.durationMs,tests:result.tests??null,logArtifactId:artifact.id,logSha256:artifact.sha256,...extra};
|
||||
});
|
||||
return {id:job.id,planId:plan.id,status:job.status,stale:!!job.stale,requiresVerification:!!job.requiresVerification,startedAt:job.startedAt,finishedAt:job.finishedAt,sourceFingerprint:job.sourceFingerprint,summary:job.summary,results};
|
||||
return {id:job.id,planId:plan.id,status:job.status,stale:!!job.stale,requiresVerification:!!job.requiresVerification,startedAt:job.startedAt,finishedAt:job.finishedAt,sourceFingerprint:job.sourceFingerprint,summary:job.summary,results,...(job.environment?{environment:job.environment}:{})};
|
||||
});
|
||||
const latest=attempts.at(-1), raw=role==='original'?latest?.status:worker?.status,lastRun=this.store.core.run.get(worker?.currentRunId);
|
||||
const outcome=worker?.requiresVerification||latest?.requiresVerification||latest?.stale?'unknown':role==='candidate'&&raw==='completed'?'passed':role==='original'&&raw==='passed'?'passed':raw==='failed'?'failed':['stopped','cancelled'].includes(raw)||role==='candidate'&&lastRun?.stopReason==='cancelled'?'stopped':'unknown';
|
||||
@@ -172,10 +184,23 @@ export class EvaluationManager {
|
||||
try{preparedSample(this.store,batch,sample);for(const child of sample.children)await verifyEvaluationSources(this.store,this.store.session(child.sessionId));inputVerified=true;}catch(error){inputError=this.runtime.provider.redact(error.message);}
|
||||
const evidence=role=>{try{return this.roleEvidence(batch,sample,role);}catch(error){const child=sample.children?.find(child=>child.role===role);return {outcome:'unknown',evidenceError:this.runtime.provider.redact(error.message),attempts:[...this.store.core.check_job.values()].filter(job=>job.taskId===child?.taskId).map(job=>({id:job.id,status:job.status,results:job.results.map(result=>({name:result.name,logArtifactId:result.logArtifactId}))})),usage:null};}};
|
||||
const original=evidence('original'),candidate=evidence('candidate');
|
||||
if(!inputVerified){original.outcome='unknown';candidate.outcome='unknown';}
|
||||
let environmentComparison=null;
|
||||
if(sample.environmentInputs){
|
||||
const left=original.attempts.at(-1)?.environment,right=candidate.attempts.at(-1)?.environment;
|
||||
const matched=!!left&&!!right&&left.dependencyInputs===sample.environmentInputs.dependencyInputs&&left.dependencyInputs===right.dependencyInputs&&left.installed.sha256===right.installed.sha256;
|
||||
environmentComparison={dependencyInputs:sample.environmentInputs.dependencyInputs,matched,original:left??null,candidate:right??null};
|
||||
if(!matched){inputVerified=false;inputError='原版与候选缺少相同实际依赖输入的检查证据。';}
|
||||
for(const child of sample.children){const owner=this.store.session(child.sessionId),job=[...this.store.core.check_job.values()].findLast(job=>job.taskId===child.taskId);
|
||||
try{if(job?.environment){verifyNodeBinding(this.store.project(child.projectId),job.environment);verifyEnvironmentPreparation(this.store,child.projectId,job.environment);}}
|
||||
catch(error){inputVerified=false;inputError=this.runtime.provider.redact(error.message);}
|
||||
}
|
||||
}
|
||||
// Missing comparable check inputs cannot erase an observed cancellation.
|
||||
// A stopped candidate remains in the denominator and cannot be adopted.
|
||||
if(!inputVerified){original.outcome='unknown';if(candidate.outcome!=='stopped')candidate.outcome='unknown';}
|
||||
const report={schemaVersion:1,batchId:batch.id,batchFingerprint:batch.fingerprint,sampleId:sample.id,sampleSha256:sample.contractSha256??null,
|
||||
label:sample.label,goal:sample.goal,criteria:sample.criteria,source:batch.source,model:batch.model,evidenceMode:batch.evidenceMode,budget:batch.budget,
|
||||
inputVerified,inputError,commands:sample.commands??[],original,candidate,summary:{original:original.outcome,candidate:candidate.outcome},
|
||||
inputVerified,inputError,commands:sample.commands??[],original,candidate,...(environmentComparison?{environmentComparison}:{}),summary:{original:original.outcome,candidate:candidate.outcome},
|
||||
inferenceValidated:false,note:batch.evidenceMode==='local-fixture'?'本地固定响应仅证明执行链与真实工程检查,不证明模型自主完成率。':'当前样本结果仅适用于封存需求和工程;不外推整体模型能力。',sealedAt:at()};
|
||||
const artifact=this.artifact(session,batch,report,'evaluation-report');sample.report={artifactId:artifact.id,sha256:artifact.sha256,summary:report.summary};sample.status='sealed';
|
||||
const group=sample.groupId&&this.store.core.collaboration.get(sample.groupId);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { readOwnedProcessTree } from './owned-process-tree.mjs';
|
||||
|
||||
// Both checks and dependency preparation use this direct, shell-free process
|
||||
// owner. Callers choose fixed invocations and interpret their own evidence.
|
||||
export async function runOwnedCommand(invocation, { cwd, env, signal, onSpawn = null, input = null, timeoutMs = 180000, onOutput = null } = {}) {
|
||||
const started = Date.now(), at = () => new Date().toISOString();
|
||||
if (signal.aborted) return { status: 'cancelled', exitCode: null, durationMs: 0, stdout: '', stderr: '', process: null };
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(invocation.executable, invocation.args, { cwd, env, windowsHide: true,
|
||||
detached: process.platform !== 'win32', stdio: [input === null ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
|
||||
const streams = Object.fromEntries(['stdout', 'stderr'].map(name => [name, { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') }]));
|
||||
let settled = false, timedOut = false, terminating = false, killTimer, ownershipError = null, treeKill = null, closedResult = null, rootClosed = false, treeTimer = null, treePending = null;
|
||||
const processInfo = { pid: child.pid ?? null, hostPid: process.pid, executable: invocation.executable,
|
||||
argsSha256: createHash('sha256').update(JSON.stringify(invocation.args)).digest('hex'), cwd, startedAt: at() };
|
||||
const append = (name, text) => { const value = streams[name]; value.characters += text.length;
|
||||
value.head = (value.head + text).slice(0, 240000); value.tail = (value.tail + text).slice(-240000);
|
||||
if (onOutput && !settled) { try { onOutput(name, text); } catch (error) { ownershipError = error; terminate(); } }
|
||||
};
|
||||
const captured = name => { const value = streams[name]; return value.characters <= 240000 ? value.head
|
||||
: value.characters <= 480000 ? value.head + value.tail.slice(value.head.length - value.characters)
|
||||
: value.head + '\n[中间日志超出保存上限,保留开头和结尾]\n' + value.tail; };
|
||||
const captureTree = async (publish = true) => {
|
||||
const snapshot = await readOwnedProcessTree(processInfo);
|
||||
if (!snapshot.supported) return snapshot;
|
||||
if (snapshot.root) processInfo.rootCreatedAt ??= snapshot.root.createdAt;
|
||||
const known = new Map((processInfo.descendants ?? []).map(value => [value.pid + ':' + value.createdAt, value]));
|
||||
for (const value of snapshot.processes) if (value.pid !== processInfo.pid) known.set(value.pid + ':' + value.createdAt, value);
|
||||
processInfo.descendants = [...known.values()].sort((a, b) => a.pid - b.pid);
|
||||
processInfo.treeObservedAt = at(); processInfo.treeRemainingPids = snapshot.processes.map(value => value.pid);
|
||||
if (publish && !settled) onSpawn?.(processInfo);
|
||||
return snapshot;
|
||||
};
|
||||
const monitorTree = () => { if (settled || treePending) return;
|
||||
treePending = captureTree().catch(error => { ownershipError = error; processInfo.treeObservationError = error.message; terminate(); }).finally(() => { treePending = null; }); };
|
||||
const finish = async (code, error, unknown = false) => {
|
||||
if (onSpawn && terminating && treeKill && !treeKill.done && !unknown) { closedResult = { code, error }; return; }
|
||||
if (onSpawn && treeKill?.error) unknown = true;
|
||||
if (settled) return; settled = true; clearTimeout(timeout); clearTimeout(killTimer); clearInterval(treeTimer); signal.removeEventListener('abort', terminate);
|
||||
if (onSpawn && process.platform === 'win32' && processInfo.pid) {
|
||||
await treePending;
|
||||
try { const snapshot = await captureTree(false); if (snapshot.processes.length) unknown = true; }
|
||||
catch (failure) { ownershipError = failure; processInfo.treeObservationError = failure.message; unknown = true; }
|
||||
}
|
||||
resolve({ status: unknown ? 'unknown' : signal.aborted ? 'cancelled' : timedOut || error || ownershipError || code !== 0 ? 'failed' : 'passed',
|
||||
exitCode: code, durationMs: Date.now() - started, stdout: captured('stdout'),
|
||||
stderr: captured('stderr') + (error ? '\n' + error.message : '') + (ownershipError ? '\n' + ownershipError.message : ''),
|
||||
timedOut, truncated: streams.stdout.characters > 480000 || streams.stderr.characters > 480000,
|
||||
...(onSpawn ? { process: { ...processInfo, rootExited: rootClosed, treeTermination: terminating ? unknown ? 'unknown' : 'confirmed' : 'not_requested' } } : {}),
|
||||
reason: unknown ? '进程结束未得到确认,需要核对实际副作用。' : timedOut ? '命令超过时间上限,已请求终止所属进程树。' : error?.message ?? ownershipError?.message ?? null });
|
||||
};
|
||||
const terminate = () => {
|
||||
if (settled || terminating) return; terminating = true;
|
||||
if (child.pid) {
|
||||
if (process.platform === 'win32') {
|
||||
if (onSpawn) treeKill = { done: false, error: null };
|
||||
execFile('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, error => {
|
||||
if (!treeKill) return; treeKill.done = true; treeKill.error = error;
|
||||
if (closedResult) void finish(closedResult.code, closedResult.error);
|
||||
});
|
||||
} else { try { process.kill(-child.pid, 'SIGTERM'); } catch { child.kill('SIGTERM'); } }
|
||||
}
|
||||
killTimer = setTimeout(() => { void finish(null, null, true); }, 5000);
|
||||
};
|
||||
const timeout = setTimeout(() => { timedOut = true; terminate(); }, timeoutMs);
|
||||
signal.addEventListener('abort', terminate, { once: true });
|
||||
for (const name of ['stdout', 'stderr']) {
|
||||
child[name].on('data', bytes => append(name, streams[name].decoder.write(bytes)));
|
||||
child[name].on('end', () => append(name, streams[name].decoder.end()));
|
||||
}
|
||||
child.once('error', error => { void finish(null, error); }); child.once('close', code => { rootClosed = true; void finish(code); });
|
||||
if (onSpawn) child.once('spawn', () => { processInfo.pid = child.pid;
|
||||
try { onSpawn(processInfo); if (process.platform === 'win32') { monitorTree(); treeTimer = setInterval(monitorTree, 1200); } }
|
||||
catch (error) { ownershipError = error; terminate(); }
|
||||
});
|
||||
if (input !== null) { child.stdin.on('error', () => {}); child.stdin.end(input); }
|
||||
if (signal.aborted) terminate();
|
||||
});
|
||||
}
|
||||
+22
-1
@@ -200,7 +200,7 @@ return async (request, response) => {
|
||||
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
|
||||
environment: executionEnvironment(),
|
||||
projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null,
|
||||
capabilities: { workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', latestToolFeedback: 'sealed-original-result-fields', changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-and-python-counted-jobs', pythonChecks: 'bound-interpreter-and-structured-results', browserChecks: 'sealed-static-build-and-real-edge-assertions', projectInspection: 'bounded-source-and-git', projectMemory: 'project-scoped-source-fingerprint-and-expiry', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
|
||||
capabilities: { environmentPreparation:'sealed-npm-ci-in-owned-worktree',environmentDiagnostics:'node-python-runtime-and-dependency-bytes',workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', latestToolFeedback: 'sealed-original-result-fields', changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-and-python-counted-jobs', pythonChecks: 'bound-interpreter-and-structured-results', browserChecks: 'sealed-static-build-and-real-edge-assertions', projectInspection: 'bounded-source-and-git', projectMemory: 'project-scoped-source-fingerprint-and-expiry', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
|
||||
});
|
||||
}
|
||||
if (method === 'GET' && route === '/api/diagnostics') {
|
||||
@@ -616,6 +616,27 @@ return async (request, response) => {
|
||||
await body(request); await runtime.gitDelivery().report(session);
|
||||
return json(response, store.publicSession(session), 201);
|
||||
}
|
||||
if (method === 'POST' && action === 'environment-diagnostics') {
|
||||
await body(request); await runtime.environmentManager().diagnose(session);
|
||||
return json(response,store.publicSession(session),201);
|
||||
}
|
||||
if (method === 'POST' && action === 'environment-plans') {
|
||||
await runtime.environmentManager().plan(session,await body(request));
|
||||
return json(response,store.publicSession(session),201);
|
||||
}
|
||||
if (method === 'POST' && action === 'environment-jobs') {
|
||||
const input=await body(request);
|
||||
if(!input || Array.isArray(input) || Object.keys(input).some(key=>!['planId','fingerprint','approved'].includes(key))) throw Object.assign(new Error('依赖执行只接受原计划身份与明确审批。'),{status:400});
|
||||
await runtime.environmentManager().start(session,input.planId,input.fingerprint,{approved:input.approved});
|
||||
return json(response,store.publicSession(session),202);
|
||||
}
|
||||
const environmentJob=action.match(/^environment-jobs\/([a-f0-9-]+)\/(stop|reconcile)$/);
|
||||
if(method==='POST' && environmentJob) {
|
||||
const input=await body(request),manager=runtime.environmentManager();
|
||||
if(environmentJob[2]==='stop')await manager.stop(session.id,environmentJob[1]);
|
||||
else await manager.reconcile(session,environmentJob[1],input.fingerprint);
|
||||
return json(response,store.publicSession(session));
|
||||
}
|
||||
if (method === 'POST' && action === 'check-plans') {
|
||||
const input = await body(request);
|
||||
if (runtime.isActive(id)) throw Object.assign(new Error('任务或检查正在执行,请等待结束后再准备检查。'), { status: 409 });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
|
||||
export const APP_VERSION = '1.20.3';
|
||||
export const APP_VERSION = '1.21.0';
|
||||
|
||||
export function executionEnvironment() {
|
||||
const windows = process.platform === 'win32';
|
||||
|
||||
@@ -19,7 +19,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
if (server.workbenchHostAuthority?.stopping) throw new Error('Wait for the original host stop operation before upgrading.');
|
||||
if (server.workbenchCompanion?.server || server.workbenchCompanion?.busy) throw new Error('Close the mobile companion gateway before upgrading; original tasks remain on the host.');
|
||||
if (server.workbenchHostAuthority?.desktopWindows?.().count) throw new Error('Close the registered desktop windows before upgrading; the execution host remains running.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.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, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
|
||||
if (runtime.evaluations?.active.size || runtime.environments?.active.size || runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.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 evaluations, environments, tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
|
||||
if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes 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.');
|
||||
@@ -32,7 +32,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null,
|
||||
vault: provider.hub?.credentialVault ? Object.getPrototypeOf(provider.hub.credentialVault) : null };
|
||||
const oldStoreProperties = { ...store };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, 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, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
|
||||
const oldRuntimeProperties = { evaluations:runtime.evaluations, environments: runtime.environments, appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, 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, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
|
||||
const oldUpdates = store.listeners('update');
|
||||
const oldInputs = runtime.inputs;
|
||||
const oldResumes = runtime.resumes;
|
||||
@@ -49,7 +49,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
if (provider.hub.importer) Object.setPrototypeOf(provider.hub.importer, ConfigImporter.prototype);
|
||||
if (provider.hub.credentialVault) Object.setPrototypeOf(provider.hub.credentialVault, CredentialVault.prototype);
|
||||
}
|
||||
runtime.appDirectory = root; runtime.workers = null; runtime.controlledEngines = null; 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; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
|
||||
runtime.appDirectory = root; runtime.evaluations = null; runtime.environments = null; runtime.workers = null; runtime.controlledEngines = null; 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; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
|
||||
delete server.workbenchCompanion;
|
||||
runtime.inputs = null;
|
||||
runtime.resumes = null;
|
||||
|
||||
@@ -32,6 +32,9 @@ export const toolDefinitions = [
|
||||
{ type: 'function', function: { name: 'delivery_report', description: '从当前Task的源码指纹、实际检查、提交和Run用量生成JSON/Markdown证据报告工件,不执行项目命令。报告注明未检查/待审核/结果未知和业务需求未验收;运行中的报告为阶段快照。', parameters: { type: 'object', properties: {} } } },
|
||||
{ type: 'function', function: { name: 'read_artifact', description: '读取当前会话保存的实际执行工件或检查日志,校验归属和SHA256。offset/limit分页,默认2000字符,实际页按当前完整请求预算缩小;用返回的next_offset读取下一页,已读区间不要重复。完整原工件保留。优先读取实际结果/日志,不反复扫描更新的历史索引;不重新执行检查。', parameters: { type: 'object', properties: { artifact_id: { type: 'string' }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['artifact_id'] } } },
|
||||
{ type: 'function', function: { name: 'inspect_project', description: '静态识别工程语言、入口、规则、npm脚本、Python测试声明和只读Git基线;返回有界源码指纹,不执行项目代码。', parameters: { type: 'object', properties: {} } } },
|
||||
{ type:'function',function:{name:'diagnose_environment',description:'只读诊断当前Task工程的Node/npm或Python/pytest、声明/锁文件和实际依赖,不安装、不执行项目代码。缺依赖属于环境问题,应先处理;返回所属原诊断工件。',parameters:{type:'object',properties:{},additionalProperties:false}}},
|
||||
{ type:'function',function:{name:'plan_environment',description:'为工作台管理的独立工作区封存npm ci准备计划;固定Node/npm、锁文件、目标、注册源、脚本策略、缓存与时限。只准备计划,不执行。默认跳过生命周期脚本。原项目请先让用户在任务记录创建并打开独立工作区。',parameters:{type:'object',properties:{registry:{type:'string'},scripts:{type:'string',enum:['skip','allow']},offline:{type:'boolean'}},additionalProperties:false}}},
|
||||
{ type:'function',function:{name:'prepare_environment',description:'请求用户明确确认后,只执行一次原依赖准备计划。输入变化或原计划已用则拒绝,不自动重试;保留真实日志/退出码/环境身份。安装成功不代表检查通过。',parameters:{type:'object',properties:{plan_id:{type:'string'},fingerprint:{type:'string'}},required:['plan_id','fingerprint'],additionalProperties:false}}},
|
||||
{ type: 'function', function: { name: 'plan_checks', description: '为当前Task封存已识别的npm或Python检查范围。返回plan id、检查目标、实际解释器身份和源码指纹;不执行项目检查,项目解释器探测等待确认。', parameters: { type: 'object', properties: { names: { type: 'array', items: { type: 'string' }, maxItems: 6, description: '可选:已识别test/typecheck/check/lint/build或python:test、python:compile;混合项目缺省保留npm范围。' } } } } },
|
||||
{ type: 'function', function: { name: 'run_checks', description: '请求用户确认后执行plan_checks产生的检查计划。保存独立job、实际退出码、测试数量和日志工件;过期计划不执行,未报告测试数量不能记通过。', parameters: { type: 'object', properties: { plan_id: { type: 'string' } }, required: ['plan_id'] } } },
|
||||
{ type: 'function', function: { name: 'inspect_session', description: '读取当前工作台会话的错误来源、模型请求、终端环境、近期工具结果和最新提案状态。解释工作台报错或执行状态时优先使用;只读取本地记录,不搜索项目,不联网,不返回密钥。',
|
||||
@@ -61,6 +64,7 @@ export function projectContext(project) {
|
||||
'你是这个本地编程工作台的编程助手。用用户的语言沟通,以实际读取和工具结果为依据。',
|
||||
'当前项目:' + project.name + '。所有文件路径相对于这个项目。',
|
||||
'可以读取、搜索、提出完整文件改动和请求终端命令。不要声称提案已经写入;只有用户应用后才改变文件。',
|
||||
'工程缺依赖时用diagnose_environment核对原因;只在所属独立工作区用plan_environment封存依赖计划,prepare_environment请求审批后执行一次,不自动重放失败。Python依赖目前人工准备。环境准备成功后继续plan_checks/run_checks,不能将安装成功当测试通过。',
|
||||
'工程任务先用inspect_project识别语言、脚本、规则与Git基线。plan_checks准备已识别npm或Python检查计划,run_checks请求用户确认后执行。Python支持python:test和python:compile,绑定unittest/pytest、实际解释器和源码;混合项目默认保留npm范围,明确选择Python名称才能执行。只凭回答不能声称检查通过。',
|
||||
'修改较大的工程时,先用index_project/query_code定位符号、导入和文件,再用read_file按实际行读取必要内容。索引是静态证据,部分或无结果不代表完整工程;Python声明候选需读取核对。',
|
||||
'已有文件优先用propose_patch和read_file返回的SHA256提出唯一锚点精确替换,保留未选中内容与格式;新文件可用propose_file。补丁锚点重叠/重复或文件变化时重新读取,不猜测写入位置。',
|
||||
|
||||
+32
-14
@@ -1,3 +1,5 @@
|
||||
import { publicEnvironmentDiagnostic } from '../core/environment/environment-manager.mjs';
|
||||
import { EnvironmentManager } from '../core/environment/environment-manager.mjs';
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
@@ -43,7 +45,7 @@ import { WORKER_TOOLS, COLLABORATION_CLOSED, workerForSession, assertWorkerTool,
|
||||
|
||||
const workerAuthority = Symbol('internal-worker-start');
|
||||
|
||||
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: '运行终端命令' };
|
||||
const labels = { diagnose_environment:'诊断工程环境',plan_environment:'准备依赖计划',prepare_environment:'执行依赖准备',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: '运行终端命令' };
|
||||
|
||||
labels.prepare_change_set = '准备多文件变更集';
|
||||
labels.list_research_targets = '查看本任务登记工件';
|
||||
@@ -93,7 +95,7 @@ export function validateToolArgs(tool, args) {
|
||||
|| new Set(args.change_ids).size !== args.change_ids.length) throw new Error('变更集需要1到32个不同的提案ID。');
|
||||
return;
|
||||
}
|
||||
const required = ['inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
|
||||
const required = ['diagnose_environment','plan_environment','inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'prepare_environment' ? ['plan_id','fingerprint'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
|
||||
: tool === 'propose_patch' ? ['path', 'base_sha256', 'reason'] : tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
|
||||
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
|
||||
for (const field of ['depth', 'start_line', 'end_line', 'offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < 0)) throw new Error('工具参数 ' + field + ' 必须是非负整数。');
|
||||
@@ -111,8 +113,8 @@ export class Runtime {
|
||||
this.appDirectory = appDirectory;
|
||||
this.active = new Map(); this.waiters = new Map();
|
||||
}
|
||||
isActive(id) { return !!this.evaluations?.isActive(id) || this.active.has(id) || !!this.workers?.isActive(id) || !!this.controlledEngines?.isActive(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.evaluations?.active.size ?? 0) > 0 || (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.workers?.active.size ?? 0) > 0 || (this.controlledEngines?.drivers.size ?? 0) > 0 || (this.mcp?.active.size ?? 0) > 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; }
|
||||
isActive(id) { return !!this.environments?.isActive(id) || !!this.evaluations?.isActive(id) || this.active.has(id) || !!this.workers?.isActive(id) || !!this.controlledEngines?.isActive(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.environments?.active.size ?? 0) > 0 || (this.evaluations?.active.size ?? 0) > 0 || (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.workers?.active.size ?? 0) > 0 || (this.controlledEngines?.drivers.size ?? 0) > 0 || (this.mcp?.active.size ?? 0) > 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; }
|
||||
evaluationManager() { return this.evaluations ??= new EvaluationManager(this.store, this); }
|
||||
workerManager() { return this.workers ??= new WorkerManager(this.store, this); }
|
||||
projectIndexer() { return this.codeIndex ??= new ProjectIndex({ cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') }); }
|
||||
@@ -141,27 +143,31 @@ export class Runtime {
|
||||
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) });
|
||||
}
|
||||
projectHasActivity(projectId, exceptSessionId = null, { excludeGroupId = null, excludeEvaluationId = null } = {}) {
|
||||
return !!this.evaluations?.projectActive(projectId, excludeEvaluationId) || !!this.workers?.projectActive(projectId, excludeGroupId) || !!this.controlledEngines?.projectActive(projectId, exceptSessionId) || [...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);
|
||||
return !!this.environments?.projectActive(projectId) || !!this.evaluations?.projectActive(projectId, excludeEvaluationId) || !!this.workers?.projectActive(projectId, excludeGroupId) || !!this.controlledEngines?.projectActive(projectId, exceptSessionId) || [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.environments?.projectActive(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.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId) || [...this.active.values()].some(run => run.project.id === projectId) || !!this.checks?.projectActive(projectId)
|
||||
!!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId) || [...this.active.values()].some(run => run.project.id === projectId) || !!this.environments?.projectActive(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.taskPlans?.projectActive(projectId) });
|
||||
}
|
||||
changeSetManager() {
|
||||
return this.changeSets ??= new ChangeSetManager(this.store, { beforeApply: (session, set) => this.workerManager().verifyMerge(session, set), projectBusy: (projectId, exceptId) =>
|
||||
!!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(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.taskPlans?.projectActive(projectId) });
|
||||
|| !!this.environments?.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) });
|
||||
}
|
||||
environmentManager() {
|
||||
return this.environments ??= new EnvironmentManager(this.store, { runtimeDirectory: this.appDirectory ? path.join(this.appDirectory,'runtime') : null,
|
||||
redact: value => this.provider.redact(value), projectBusy: (projectId,exceptId) => this.projectHasActivity(projectId,exceptId) });
|
||||
}
|
||||
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.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(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) });
|
||||
projectBusy: (projectId, exceptId) => !!this.environments?.projectActive(projectId) || !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(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.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(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) });
|
||||
projectBusy: (projectId, exceptId) => !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId, exceptId) || [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.environments?.projectActive(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) });
|
||||
}
|
||||
startWorker(session, worker, config) {
|
||||
if (workerForSession(this.store, session) !== worker || !this.workers?.active.has(worker.collaborationId)
|
||||
@@ -515,7 +521,7 @@ export class Runtime {
|
||||
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');
|
||||
if (!['prepare_environment','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 === 'read_registered_skill') {
|
||||
@@ -593,6 +599,18 @@ export class Runtime {
|
||||
files: set.files.map(file => ({ path: file.path, change_id: file.changeId, base_sha256: file.baseSha256, sha256: file.sha256 })),
|
||||
note: '只封存了整批审查范围,未写入项目。请用户在改动面板审核整个批次并确认应用。' };
|
||||
}
|
||||
else if(tool==='diagnose_environment') result=publicEnvironmentDiagnostic(await this.environmentManager().diagnose(session));
|
||||
else if(tool==='plan_environment') result=await this.environmentManager().plan(session,args,{source:'agent'});
|
||||
else if(tool==='prepare_environment') {
|
||||
const manager=this.environmentManager(),plan=manager.own(session,args.plan_id,args.fingerprint);
|
||||
result=await this.requestCommand(session,event,{command:plan.invocation.executable+'\n'+plan.invocation.args.map(arg=>JSON.stringify(arg)).join('\n'),
|
||||
environmentPlanId:plan.id,environmentSummary:{root:plan.root,registry:plan.registry,scripts:plan.scripts,offline:plan.offline,timeoutMs:plan.timeoutMs,lifecycle:plan.lifecycle,installScriptPackages:plan.installScriptPackages},
|
||||
reason:'准备所属独立工作区依赖;'+(plan.scripts==='skip'?'跳过所有安装脚本':'允许根工程和依赖安装脚本')+';完成后仍需工程检查。'},run,async()=>{
|
||||
const approval=session.approvals.findLast(row=>row.environmentPlanId===plan.id&&row.status==='approved'&&row.runId===run.id);
|
||||
const {promise}=await manager.start(session,plan.id,plan.fingerprint,{approved:true,signal:run.controller.signal,source:'agent',approvalId:approval?.id});
|
||||
const job=await promise;return {status:job.status,job_id:job.id,plan_id:plan.id,summary:job.summary,log_artifact_id:job.logArtifactId,environment:job.after,requires_verification:job.requiresVerification};
|
||||
});
|
||||
}
|
||||
else if (tool === 'plan_checks') result = await this.checkRunner().plan(session, args.names);
|
||||
else if (tool === 'plan_delivery') {
|
||||
const plan = await this.gitDelivery().plan(session, args.message === undefined ? {} : { message: args.message }, { source: 'agent' });
|
||||
@@ -661,9 +679,9 @@ export class Runtime {
|
||||
? '终端命令不能为空,也不能超过 6,000 字符。' : 'MCP审批内容不能为空,也不能超过24,000字符;参数仍按工具契约核对。');
|
||||
const approval = { id: randomUUID(), toolCallId: event.toolCallId, eventId: event.id, invocationId: event.invocationId,
|
||||
taskId: run.taskId, runId: run.id, projectId: session.projectId, command,
|
||||
...(execute ? args.mcpRegistrationId ? { mcpRegistrationId: args.mcpRegistrationId } : args.browserPlanId ? { browserPlanId: args.browserPlanId, browserSummary: args.browserSummary } : { checkPlanId: args.checkPlanId, checkScripts: args.checkScripts } : {}),
|
||||
...(execute ? args.environmentPlanId ? {environmentPlanId:args.environmentPlanId,environmentSummary:args.environmentSummary} : args.mcpRegistrationId ? { mcpRegistrationId: args.mcpRegistrationId } : args.browserPlanId ? { browserPlanId: args.browserPlanId, browserSummary: args.browserSummary } : { checkPlanId: args.checkPlanId, checkScripts: args.checkScripts } : {}),
|
||||
reason: String(args.reason ?? '').slice(0, 800), cwd: args.mcpRegistrationId ? '所属MCP临时目录(将在启动后记录)' : run.project.root,
|
||||
shell: args.mcpRegistrationId ? 'MCP · 外部独立进程' : args.browserPlanId ? '浏览器 · 独立Edge环境' : execute ? '工程检查器 · 直接进程' : executionEnvironment().shell, status: 'pending', createdAt: now() };
|
||||
shell: args.environmentPlanId ? '依赖准备 · 固定npm命令' : args.mcpRegistrationId ? 'MCP · 外部独立进程' : args.browserPlanId ? '浏览器 · 独立Edge环境' : execute ? '工程检查器 · 直接进程' : executionEnvironment().shell, status: 'pending', createdAt: now() };
|
||||
session.approvals.push(approval);
|
||||
event.phase = 'waiting'; session.status = 'awaiting_approval';
|
||||
this.store.invocationState(session, event, 'waiting');
|
||||
@@ -751,11 +769,11 @@ export class Runtime {
|
||||
await this.workers?.stopParent(sessionId);
|
||||
assertOriginal();
|
||||
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); await this.mcp?.stop(sessionId); await this.taskPlans?.settle(sessionId); return; }
|
||||
if (!run) { await this.environments?.stop(sessionId); 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.mcp?.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 this.evaluations?.stopAll(); await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); 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.mcp?.stopAll(); await this.taskPlans?.settle(); }
|
||||
async stopAll() { await this.evaluations?.stopAll(); await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); await this.environments?.stopAll(); 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.mcp?.stopAll(); await this.taskPlans?.settle(); }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { publicEnvironmentDiagnostic } from '../core/environment/environment-manager.mjs';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { EventEmitter } from 'node:events';
|
||||
@@ -305,6 +306,11 @@ export class Store extends EventEmitter {
|
||||
if (event) { event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary; }
|
||||
changed = true;
|
||||
}
|
||||
for (const job of this.core.environment_job.values()) {
|
||||
if (job.sessionId !== session.id || !['queued','running','stopping'].includes(job.status)) continue;
|
||||
job.status = 'unknown'; job.requiresVerification = true; job.finishedAt = now();
|
||||
job.summary = '宿主中断,原依赖进程与结果需只读核对;不按历史PID结束进程,不自动重放。'; changed = true;
|
||||
}
|
||||
for (const event of session.events ?? []) {
|
||||
if (['running', 'waiting', 'retrying'].includes(event.phase)) {
|
||||
const invocation = [...this.core.tool.values()].find(item => item.sessionId === session.id && item.callId === event.toolCallId);
|
||||
@@ -672,6 +678,11 @@ 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,
|
||||
...([...this.core.environment_diagnostic.values()].some(value=>value.sessionId===session.id) ? {
|
||||
environmentDiagnostics: [...this.core.environment_diagnostic.values()].filter(value=>value.sessionId===session.id && value.taskId===task?.id).slice(-4).map(publicEnvironmentDiagnostic),
|
||||
environmentPlans: [...this.core.environment_plan.values()].filter(value=>value.sessionId===session.id && value.taskId===task?.id).slice(-5),
|
||||
environmentJobs: [...this.core.environment_job.values()].filter(value=>value.sessionId===session.id && (value.taskId===task?.id || value.requiresVerification)).filter((value,index,all)=>index>=all.length-12 || value.requiresVerification || ['queued','running','stopping'].includes(value.status)),
|
||||
} : {}),
|
||||
mcpJobs: [...this.core.mcp_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-30),
|
||||
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),
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
export const ENVIRONMENT_ACTIVE = new Set(['queued','running','stopping']);
|
||||
export const environmentPlanSeal = plan => Object.fromEntries(['schemaVersion','id','sessionId','projectId','taskId','runId','diagnosticId','root','workspace','sourceFingerprint','nodeIdentity','dependencyInputs','registry','scripts','offline','timeoutMs','invocation','configFiles','cacheDirectory','lifecycle','installScriptPackages','packageCount'].map(key=>[key,plan[key]]));
|
||||
export function unresolvedEnvironments(store,projectId) {
|
||||
return [...(store.core.environment_job?.values() ?? [])].filter(job=>job.projectId===projectId
|
||||
&& (ENVIRONMENT_ACTIVE.has(job.status) || job.requiresVerification && !job.reconciliation));
|
||||
}
|
||||
export function assertEnvironmentsResolved(store,projectId) {
|
||||
if (unresolvedEnvironments(store,projectId).length) throw Object.assign(new Error('工程依赖正在准备或中断结果待核对,请先处理所属环境记录。'),{status:409});
|
||||
}
|
||||
@@ -57,7 +57,8 @@ export function evaluationSeal(batch) {
|
||||
export function evaluationSampleSeal(batch, sample) {
|
||||
return { schemaVersion: 1, batchId: batch.id, batchFingerprint: batch.fingerprint, sampleId: sample.id, groupId: sample.groupId,
|
||||
baseCommit: batch.source.head, definition: evaluationSeal(batch).samples.find(value => value.id === sample.id),
|
||||
files: sample.files, commands: sample.commands, children: sample.children };
|
||||
files: sample.files, commands: sample.commands, children: sample.children,
|
||||
...(sample.environmentInputs ? { environmentInputs:sample.environmentInputs } : {}) };
|
||||
}
|
||||
export function evaluationSummary(batch) {
|
||||
const outcomes = batch.samples.map(sample => sample.report?.summary ?? { original: sample.baselineAttemptedAt ? 'unknown' : 'pending', candidate: ['failed','stopped','unknown'].includes(sample.status) ? sample.status : ['candidate_running','candidate_complete','awaiting_review','paused','collecting','adopting','sealed'].includes(sample.status) ? 'unknown' : 'pending' });
|
||||
|
||||
@@ -7,6 +7,7 @@ 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', 'engine_run', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory', 'task_checkpoint', 'mcp_job', 'collaboration', 'worker', 'input_attachment'];
|
||||
CORE_KINDS.push('resume_plan');
|
||||
CORE_KINDS.push('evaluation');
|
||||
CORE_KINDS.push('environment_diagnostic','environment_plan','environment_job');
|
||||
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);
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ export function updateTaskContract(task, instruction) {
|
||||
if (current.checks === 'skip') task.constraints.push('用户明确要求无需测试;不得自动扩大为工程测试任务。');
|
||||
}
|
||||
|
||||
export const DIAGNOSTIC_TOOLS = new Set(['inspect_session', 'inspect_project', 'list_files', 'read_file', 'search_files', 'read_artifact', 'inspect_task_plan', 'read_browser_result', 'read_registered_skill',
|
||||
export const DIAGNOSTIC_TOOLS = new Set(['diagnose_environment','inspect_session', 'inspect_project', 'list_files', 'read_file', 'search_files', 'read_artifact', 'inspect_task_plan', 'read_browser_result', 'read_registered_skill',
|
||||
'inspect_engine_checks', 'list_research_targets', 'read_research_evidence']);
|
||||
export const AUTOMATIC_CHECK_TOOLS = new Set(['plan_checks', 'run_checks', 'plan_browser', 'run_browser']);
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
|
||||
import { isId, accountedTokens, emptyUsage } from './execution.mjs';
|
||||
import { selectedEngineInput } from './engine-execution.mjs';
|
||||
|
||||
export const WORKER_TOOLS = new Set(['inspect_session', 'inspect_project', 'index_project', 'query_code', 'read_artifact',
|
||||
export const WORKER_TOOLS = new Set(['diagnose_environment','plan_environment','prepare_environment','inspect_session', 'inspect_project', 'index_project', 'query_code', 'read_artifact',
|
||||
'list_files', 'read_file', 'search_files', 'propose_file', 'propose_patch', 'prepare_change_set', 'plan_checks', 'run_checks']);
|
||||
export const COLLABORATION_ACTIVE = new Set(['preparing', 'starting', 'running', 'stopping', 'collecting', 'merge_preparing', 'reconciling']);
|
||||
export const COLLABORATION_CLOSED = new Set(['completed', 'discarded', 'resolved_external']);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import fs from 'node:fs';
|
||||
import { assertEnvironmentsResolved } from './environment.mjs';
|
||||
import path from 'node:path';
|
||||
|
||||
export const WORKSPACE_ACTIVE = new Set(['creating', 'verifying', 'registering']);
|
||||
@@ -18,6 +19,7 @@ export function unresolvedWorkspaces(store, projectId, { exceptId = null, includ
|
||||
}
|
||||
|
||||
export function assertWorkspacesResolved(store, projectId, options) {
|
||||
assertEnvironmentsResolved(store, projectId);
|
||||
if (unresolvedWorkspaces(store, projectId, options).length) throw conflict(
|
||||
'这个项目的Git隔离工作区正在准备、创建或结果待核对,请先在所属会话处理工作区记录。');
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# Agent Workbench:核心代理能力研究与产品计划
|
||||
|
||||
## 当前任务:1.21 工程依赖与可复现环境
|
||||
|
||||
用户继续授权全量开发、及时回顾/验证/修复。基线e259ddc,分支feat/reproducible-env-1.21;按PLAN-1.21 A–F推进。保留正式1.20.3/PID36552、原Provider与用户全部项目/历史;研发验收只使用独立数据/端口、自有工程和HTTP服务,不主动调用真实模型。
|
||||
|
||||
1. [complete] A:回顾1.20.3及现有检查/隔离工作区/审批/停止契约,接入只读工程环境诊断与真实运行器身份。
|
||||
2. [complete] B/C:固定npm lockfile的所属隔离准备计划,原依赖/锁文件/注册源/生命周期脚本可见;审批、所属进程/预算/取消、原日志、失败与unknown恢复。
|
||||
3. [in_progress] D:真实环境身份与Task检查/固定评测已接入。回顾真实React工程发现Vite留下空目录被误判,已修正为文件/链接字节身份并保留全部目录遍历保护;相关专项和真实工程复验中。
|
||||
4. [complete] E:中文桌面/390px诊断→计划→确认→执行→日志及停止、过期锁文件、unknown核对、迟到响应等7组通过;原失败日志保持,最终冻结版本还须随包复验。
|
||||
5. [in_progress] F:迁移登记1.21后两组升级通过;源码验证串行,避免固定9229端口争用。继续固定Node/React/Python、完整回归、独立源码/发行/安装、保留状态升级、封存和本地Git。
|
||||
|
||||
## 当前任务:1.20.3 模型能力与错误保留上线
|
||||
|
||||
用户授权将MODEL-FIDELITY-PLAN实现并本地上线,同时明确内置浏览器阶段。基线02cefd0;保留正式Provider/凭据、用户项目与全部历史失败,不调用真实模型或重放原任务。QA使用独立HTTP/SSE、数据和端口。
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, until, launchWorkbench, compatibleFixture,completion,call,assertToolPairs } from './helpers.mjs';
|
||||
import { environmentProject } from './fixtures/environment-project.mjs';
|
||||
import { EnvironmentManager } from '../src/core/environment/environment-manager.mjs';
|
||||
import { diagnoseEnvironment,inspectNodeEnvironment,dependencyTree,nodeEnvironmentBinding,verifyNodeBinding } from '../src/core/environment/environment-inspector.mjs';
|
||||
import { CheckRunner } from '../src/core/check-runner.mjs';
|
||||
import { verifiedCheck } from '../src/core/delivery-report.mjs';
|
||||
import { inspectProject } from '../src/core/project-inspector.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { assertEnvironmentsResolved } from '../src/shared/contracts/environment.mjs';
|
||||
import { installUpgrade } from '../src/server/hot-upgrade.mjs';
|
||||
|
||||
function manager(f,options={}){const value=new EnvironmentManager(f.store,{allowHttpLoopback:true,...options});f.onCleanup(()=>value.stopAll());return value;}
|
||||
const write=(project,name,value)=>fs.writeFileSync(path.join(project.root,name),value);
|
||||
const read=(project,name)=>fs.readFileSync(path.join(project.root,name),'utf8');
|
||||
|
||||
test('unfixed dependency URLs and invalid integrity are reported without exposing URL credentials or allowing a plan',t=>{
|
||||
const f=fixture(t);write(f.project,'package.json',JSON.stringify({dependencies:{a:'1.0.0'}}));
|
||||
write(f.project,'package-lock.json',JSON.stringify({lockfileVersion:3,packages:{'':{dependencies:{a:'1.0.0'}},'node_modules/a':{version:'1.0.0',resolved:'https://private-token@example.invalid/a.tgz',integrity:'sha1-invalid'}}}));
|
||||
const node=inspectNodeEnvironment(f.project);assert.equal(node.preparable,false);assert.match(node.issues.join(),/来源/);assert.match(node.issues.join(),/sha512/);assert.ok(!JSON.stringify(node).includes('private-token'));
|
||||
});
|
||||
test('hot upgrade refuses an active dependency operation or evaluation before changing runtime objects',()=>{
|
||||
for(const name of ['environments','evaluations']){const runtime={[name]:{active:new Map([['owned',{}]])}},context={server:{listening:true},store:{},provider:{},runtime,token:'owned-token',clients:new Set()};
|
||||
assert.throws(()=>installUpgrade(context,{appDirectory:process.cwd()}),/Wait for active/);assert.ok(runtime[name].active.has('owned'));}
|
||||
});
|
||||
|
||||
test('read-only environment diagnosis identifies actual runtime, missing dependencies and sealed inputs without installing or running scripts',async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f),m=manager(f),before=read(p.project,'package-lock.json');
|
||||
const diagnostic=await m.diagnose(p.session);
|
||||
assert.equal(diagnostic.node.status,'needs_preparation');assert.deepEqual(diagnostic.node.missing,['awb-env-fixture']);
|
||||
assert.match(diagnostic.node.runtime.node.sha256,/^[a-f0-9]{64}$/);assert.ok(diagnostic.node.runtime.npm.version);
|
||||
assert.equal(diagnostic.node.lifecycle[0].name,'postinstall');assert.equal(p.requests(),0);
|
||||
assert.equal(fs.existsSync(path.join(p.root,'node_modules')),false);assert.equal(read(p.project,'package-lock.json'),before);
|
||||
assert.equal(f.store.artifactStore.read(f.store.owned('artifact',diagnostic.artifactId,p.session.id)),JSON.stringify((({artifactId,artifactSha256,...data})=>data)(diagnostic)));
|
||||
});
|
||||
test('diagnosis rejects unsupported managers, lock integrity and credential configuration without reading config content',async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f,{dependency:false});
|
||||
write(p.project,'.npmrc','_authToken=diagnostic-must-not-read-this');
|
||||
let node=inspectNodeEnvironment(p.project);assert.equal(node.preparable,false);assert.match(node.issues.join(),/npmrc/);assert.ok(!JSON.stringify(node).includes('diagnostic-must-not-read-this'));
|
||||
fs.unlinkSync(path.join(p.root,'.npmrc'));
|
||||
const manifest=JSON.parse(read(p.project,'package.json'));manifest.packageManager='pnpm@10.0.0';write(p.project,'package.json',JSON.stringify(manifest));
|
||||
node=inspectNodeEnvironment(p.project);assert.equal(node.status,'unsupported');assert.equal(node.preparable,false);
|
||||
});
|
||||
test('approved real npm ci runs only in owned worktree, skips scripts, retains logs and binds later actual tests', {timeout:60000},async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f),m=manager(f);
|
||||
await assert.rejects(m.plan(f.session,{}),/独立工作区/);
|
||||
const plan=await m.plan(p.session,{registry:p.registry});assert.equal(plan.scripts,'skip');
|
||||
await assert.rejects(m.start(p.session,plan.id,plan.fingerprint),/批准/);
|
||||
const started=await m.start(p.session,plan.id,plan.fingerprint,{approved:true}),job=await started.promise;
|
||||
assert.equal(job.status,'prepared',job.summary+'\n'+job.logExcerpt);assert.equal(job.result.exitCode,0);assert.ok(job.process.pid);assert.equal(job.process.rootExited,true);
|
||||
assert.equal(fs.existsSync(path.join(p.root,'node_modules/lifecycle.txt')),false);assert.equal(fs.existsSync(path.join(p.sourceRoot,'node_modules')),false);
|
||||
assert.equal(f.store.core.task.get(p.session.taskId).verification.status,'not_configured');assert.ok(p.requests()>0);
|
||||
assert.match(f.store.artifactStore.read(f.store.owned('artifact',job.logArtifactId,p.session.id)),/added 1 package/);
|
||||
await assert.rejects(m.start(p.session,plan.id,plan.fingerprint,{approved:true}),/已经使用/);
|
||||
const checks=new CheckRunner(f.store);const checkPlan=await checks.plan(p.session,['test']);const check=await(await checks.start(p.session,checkPlan.id)).promise;
|
||||
assert.equal(check.status,'passed',check.summary);assert.equal(check.results[0].tests.passed,1);assert.equal(check.environment.identity,job.after.identity);
|
||||
assert.ok(verifiedCheck(f.store,p.session,await inspectProject(p.project)));
|
||||
fs.appendFileSync(path.join(p.root,'node_modules/awb-env-fixture/index.cjs'),'\n// external change');
|
||||
assert.equal(verifiedCheck(f.store,p.session,await inspectProject(p.project)),null);
|
||||
const stale=await(await checks.start(p.session,checkPlan.id)).promise;assert.equal(stale.status,'stale');assert.equal(stale.results.length,0);
|
||||
});
|
||||
test('explicitly allowing lifecycle scripts executes sealed root script and preserves the separate preparation result', {timeout:60000},async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f),m=manager(f),plan=await m.plan(p.session,{registry:p.registry,scripts:'allow'});
|
||||
const job=await(await m.start(p.session,plan.id,plan.fingerprint,{approved:true})).promise;
|
||||
assert.equal(job.status,'prepared',job.logExcerpt);assert.equal(read(p.project,'node_modules/lifecycle.txt'),'approved');
|
||||
assert.equal(f.store.core.task.get(p.session.taskId).verification.status,'not_configured');
|
||||
});
|
||||
test('stale lockfile, tampered plan/config, cross-session identities and mismatched download sources never dispatch npm',async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f),m=manager(f);
|
||||
await assert.rejects(m.plan(p.session,{}),/来源/);
|
||||
const plan=await m.plan(p.session,{registry:p.registry}),original=read(p.project,'package-lock.json');
|
||||
await assert.rejects(m.start(f.session,plan.id,plan.fingerprint,{approved:true}),/不属于/);
|
||||
write(p.project,'package-lock.json',original+'\n');await assert.rejects(m.start(p.session,plan.id,plan.fingerprint,{approved:true}),/变化/);
|
||||
write(p.project,'package-lock.json',original);fs.writeFileSync(plan.configFiles[0].path,'ignore-scripts=false');await assert.rejects(m.start(p.session,plan.id,plan.fingerprint,{approved:true}),/配置/);
|
||||
fs.writeFileSync(plan.configFiles[0].path,'');plan.invocation.args.push('--ignore-scripts=false');await assert.rejects(m.start(p.session,plan.id,plan.fingerprint,{approved:true}),/范围/);
|
||||
assert.equal(p.requests(),0);assert.equal(f.store.core.environment_job.size,0);
|
||||
});
|
||||
test('registry failure keeps original npm exit/log and performs no automatic fallback or replay', {timeout:60000},async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f,{response:'error'}),m=manager(f),plan=await m.plan(p.session,{registry:p.registry});
|
||||
const job=await(await m.start(p.session,plan.id,plan.fingerprint,{approved:true})).promise;
|
||||
assert.equal(job.status,'failed',job.summary);assert.notEqual(job.result.exitCode,0);assert.match(job.logExcerpt,/503|E503/);assert.equal(p.requests(),1);
|
||||
assert.equal(fs.existsSync(path.join(p.sourceRoot,'node_modules')),false);
|
||||
});
|
||||
test('stopping a hanging dependency download records only its owned process and preserves stopped logs', {timeout:60000},async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f,{response:'hang'}),m=manager(f),plan=await m.plan(p.session,{registry:p.registry});
|
||||
const {job,promise}=await m.start(p.session,plan.id,plan.fingerprint,{approved:true});await until(()=>p.requests()>0);
|
||||
assert.equal(m.projectActive(p.project.id),true);assert.throws(()=>assertEnvironmentsResolved(f.store,p.project.id),/准备/);
|
||||
await m.stop(p.session.id,job.id);await promise;assert.ok(['cancelled','unknown'].includes(job.status),job.summary);
|
||||
assert.ok(job.logArtifactId);assert.equal(job.result.process.treeTermination,job.status==='unknown'?'unknown':'confirmed');assert.equal(m.active.size,0);
|
||||
});
|
||||
test('restart retains unknown preparation, blocks writes and checks, and requires explicit read-only reconciliation',async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f,{dependency:false}),m=manager(f),plan=await m.plan(p.session,{offline:true});
|
||||
const job={id:crypto.randomUUID(),sessionId:p.session.id,projectId:p.project.id,taskId:p.session.taskId,runId:p.session.runId,planId:plan.id,planFingerprint:plan.fingerprint,status:'queued',process:null};
|
||||
f.store.putRecord('environment_job',p.session,job,'environment.queued');f.store.close();
|
||||
const recovered=new Store(f.data);f.onCleanup(()=>recovered.close());const session=recovered.session(p.session.id),original=recovered.core.environment_job.get(job.id);
|
||||
assert.equal(original.status,'unknown');assert.equal(original.requiresVerification,true);
|
||||
const runtime=new Runtime(recovered,new Provider());assert.throws(()=>runtime.start(session.id,'new task'),/环境|依赖/);
|
||||
await assert.rejects(new CheckRunner(recovered).plan(session),/依赖/);
|
||||
const resumedManager=new EnvironmentManager(recovered);await resumedManager.reconcile(session,job.id,plan.fingerprint);
|
||||
assert.equal(original.status,'unknown');assert.equal(original.requiresVerification,false);assert.ok(original.reconciliation.sha256);assert.doesNotThrow(()=>assertEnvironmentsResolved(recovered,p.project.id));
|
||||
});
|
||||
test('HTTP environment flow survives refresh, requires explicit approval and preserves task and artifact ownership', {timeout:60000},async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f,{dependency:false}),id=p.session.id;f.store.close();const host=await launchWorkbench(t,f.data),base='/sessions/'+id;
|
||||
let session=await host.api(base+'/environment-diagnostics',{});assert.equal(session.execution.environmentDiagnostics.at(-1).node.status,'ready');
|
||||
session=await host.api(base+'/environment-plans',{offline:true});const plan=session.execution.environmentPlans.at(-1);
|
||||
await assert.rejects(host.api(base+'/environment-jobs',{planId:plan.id,fingerprint:plan.fingerprint}),/批准/);
|
||||
await host.api(base+'/environment-jobs',{planId:plan.id,fingerprint:plan.fingerprint,approved:true});
|
||||
await until(async()=>{session=await host.api(base);return session.execution.environmentJobs.at(-1)?.finishedAt;},30000);
|
||||
assert.equal(session.execution.environmentJobs.at(-1).status,'prepared',session.execution.environmentJobs.at(-1).logExcerpt);
|
||||
assert.equal(session.execution.task.id,p.session.taskId);assert.equal(session.approvals.at(-1).environmentPlanId,plan.id);
|
||||
await host.close();const next=await launchWorkbench(t,f.data),again=await next.api(base);assert.equal(again.execution.environmentJobs.at(-1).status,'prepared');
|
||||
});
|
||||
test('Python environment diagnosis reads declarations and runtime identity without executing project code or installing packages',async t=>{
|
||||
const f=fixture(t);write(f.project,'pyproject.toml','[tool.pytest.ini_options]\ntestpaths=["tests"]\n');
|
||||
write(f.project,'conftest.py',"raise RuntimeError('must never import during diagnosis')");
|
||||
const diagnostic=await diagnoseEnvironment(f.project,{pythonExecutable:process.env.AGENT_WORKBENCH_TEST_PYTHON});
|
||||
assert.equal(diagnostic.node,null);assert.ok(diagnostic.python);assert.equal(diagnostic.python.preparation,'manual');assert.match(diagnostic.python.runtime.sha256,/^[a-f0-9]{64}$/);
|
||||
assert.equal(fs.existsSync(path.join(f.projectRoot,'__pycache__')),false);
|
||||
});
|
||||
test('empty build cache directories keep dependency identity while added executable files invalidate it',t=>{
|
||||
const f=fixture(t);write(f.project,'package.json','{"name":"dependency-identity","private":true}');
|
||||
fs.mkdirSync(path.join(f.projectRoot,'node_modules/a'),{recursive:true});write(f.project,'node_modules/a/package.json','{"name":"a","version":"1.0.0"}');
|
||||
const before=nodeEnvironmentBinding(f.project);
|
||||
fs.mkdirSync(path.join(f.projectRoot,'node_modules/.vite-temp'));
|
||||
fs.mkdirSync(path.join(f.projectRoot,'node_modules/.cache/empty'),{recursive:true});
|
||||
assert.deepEqual(nodeEnvironmentBinding(f.project),before);verifyNodeBinding(f.project,before);
|
||||
write(f.project,'node_modules/.vite-temp/config.mjs','export default {plugins:[]}');
|
||||
assert.throws(()=>verifyNodeBinding(f.project,before),/依赖已变化/);
|
||||
fs.unlinkSync(path.join(f.projectRoot,'node_modules/.vite-temp/config.mjs'));verifyNodeBinding(f.project,before);
|
||||
write(f.project,'node_modules/a/package.json','{"name":"a","version":"2.0.0"}');
|
||||
assert.throws(()=>verifyNodeBinding(f.project,before),/依赖已变化/);
|
||||
});
|
||||
|
||||
test('dependency snapshots reject external links and incomplete budgets instead of claiming environment equivalence',async t=>{
|
||||
const f=fixture(t);fs.mkdirSync(path.join(f.projectRoot,'node_modules/a'),{recursive:true});write(f.project,'node_modules/a/package.json','{}');
|
||||
assert.equal(dependencyTree(f.project,{maximumFiles:1}).status,'unverified');const before=nodeEnvironmentBinding(f.project);assert.equal(before,null);
|
||||
const external=path.join(f.root,'external');fs.mkdirSync(external);fs.symlinkSync(external,path.join(f.projectRoot,'node_modules/external'),process.platform==='win32'?'junction':'dir');
|
||||
assert.equal(dependencyTree(f.project).status,'unverified');
|
||||
});
|
||||
test('model-requested environment preparation uses the original approval boundary and never treats preparation as passed engineering checks',{timeout:60000},async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f,{dependency:false}),upstream=await compatibleFixture(t,(route,input,requests)=>{
|
||||
if(requests.length===1)return completion([call('env-diagnose','diagnose_environment',{})]);
|
||||
if(requests.length===2)return completion([call('env-plan','plan_environment',{offline:true})]);
|
||||
if(requests.length===3){const plan=JSON.parse(input.messages.findLast(value=>value.tool_call_id==='env-plan').content);return completion([call('env-run','prepare_environment',{plan_id:plan.id,fingerprint:plan.fingerprint})]);}
|
||||
return completion([],'依赖准备已完成,工程检查尚未执行。');
|
||||
});
|
||||
f.store.config={...f.store.config,mode:'compatible',baseUrl:upstream.baseUrl,model:'owned-environment-fixture'};
|
||||
const runtime=new Runtime(f.store,new Provider());f.onCleanup(()=>runtime.stopAll());runtime.start(p.session.id,'仅准备这个独立工作区的依赖,保留原记录,不需要测试');const running=runtime.active.get(p.session.id).promise;
|
||||
await until(()=>p.session.approvals.some(row=>row.environmentPlanId&&row.status==='pending'),30000);
|
||||
const approval=p.session.approvals.find(row=>row.environmentPlanId&&row.status==='pending');assert.equal(f.store.core.environment_job.size,0);assert.equal(approval.environmentSummary.scripts,'skip');
|
||||
runtime.decide(p.session.id,approval.id,true);await running;
|
||||
const snapshot=f.store.executionSnapshot(p.session),job=snapshot.environmentJobs.at(-1);assert.equal(job.status,'prepared',job.summary);assert.equal(f.store.core.task.get(p.session.taskId).verification.status,'not_configured');
|
||||
assert.equal(snapshot.environmentDiagnostics.at(-1).node.status,'ready');assert.equal(snapshot.environmentDiagnostics.at(-1).runId,job.runId);
|
||||
assert.equal(f.store.core.environment_job.get(job.id).approvalId,approval.id);assertToolPairs(p.session.providerMessages);
|
||||
});
|
||||
test('timeout and offline cache miss retain actual failures and new attempts require newly sealed plans',{timeout:60000},async t=>{
|
||||
const f=fixture(t),p=await environmentProject(f,{response:'hang'}),m=manager(f,{timeoutMs:1200});
|
||||
const offline=await m.plan(p.session,{registry:p.registry,offline:true}),missing=await(await m.start(p.session,offline.id,offline.fingerprint,{approved:true})).promise;
|
||||
assert.equal(missing.status,'failed');assert.match(missing.logExcerpt,/ENOTCACHED|cache/i);assert.equal(p.requests(),0);
|
||||
const plan=await m.plan(p.session,{registry:p.registry}),job=await(await m.start(p.session,plan.id,plan.fingerprint,{approved:true})).promise;
|
||||
assert.equal(job.result.timedOut,true);assert.ok(['failed','unknown'].includes(job.status));assert.ok(job.logArtifactId);assert.notEqual(job.id,missing.id);
|
||||
});
|
||||
@@ -15,6 +15,25 @@ import { verifyEvaluationSources } from '../src/core/evaluation/provenance.mjs';
|
||||
import { workerHttp } from './fixtures/workers-http.mjs';
|
||||
|
||||
export const definition = (count=1) => ({title:'修复求和并核对完整原测试',evidenceMode:'local-fixture',samples:Array.from({length:count},(_,index)=>({label:'加法样本'+index,goal:'修复加法运算,保留已有功能',criteria:'原3项加法测试及构建通过;不修改原测试',paths:['src/add.mjs'],checks:['test','build']}))});
|
||||
|
||||
test('both evaluation worktrees can approve fixed dependency preparation and different actual dependencies reject candidate execution',{timeout:90000},async t=>{
|
||||
const f=fixture(t);createDeliveryProject(f,{ownerChanges:false});
|
||||
const manifest=JSON.parse(fs.readFileSync(path.join(f.projectRoot,'package.json'),'utf8'));
|
||||
fs.writeFileSync(path.join(f.projectRoot,'package-lock.json'),JSON.stringify({name:manifest.name,version:manifest.version,lockfileVersion:3,requires:true,packages:{'':{name:manifest.name,version:manifest.version}}}));
|
||||
deliveryGit(f,['add','--','package-lock.json']);deliveryGit(f,['-c','user.name=Workbench QA','-c','user.email=qa@workbench.local','commit','-m','Seal owned lockfile']);
|
||||
const provider=new Provider();let requests=0;provider.complete=async()=>{requests++;throw new Error('Unexpected model call');};
|
||||
const runtime=new Runtime(f.store,provider),manager=runtime.evaluationManager();f.onCleanup(()=>runtime.stopAll());
|
||||
const batch=await manager.plan(f.session,definition()),sample=batch.samples[0];await manager.prepare(f.session,batch.id,batch.fingerprint,sample.id).promise;
|
||||
assert.equal(sample.status,'ready',batch.message);assert.ok(sample.environmentInputs.dependencyInputs);
|
||||
for(const child of sample.children){const owner=f.store.session(child.sessionId),environment=runtime.environmentManager(),plan=await environment.plan(owner,{offline:true});
|
||||
const job=await(await environment.start(owner,plan.id,plan.fingerprint,{approved:true})).promise;assert.equal(job.status,'prepared',job.summary+'\n'+job.logExcerpt);}
|
||||
await manager.baseline(f.session,batch.id,batch.fingerprint,sample.id).promise;assert.equal(sample.status,'baseline_complete',batch.message);
|
||||
const candidate=sample.children.find(child=>child.role==='candidate'),root=f.store.project(candidate.projectId).root;
|
||||
fs.mkdirSync(path.join(root,'node_modules','external'),{recursive:true});fs.writeFileSync(path.join(root,'node_modules','external','package.json'),'{}');
|
||||
await manager.start(f.session,batch.id,batch.fingerprint,sample.id).promise;assert.equal(sample.status,'failed');assert.match(sample.error,/依赖环境不同/);assert.equal(requests,0);
|
||||
await manager.seal(f.session,batch.id,batch.fingerprint,sample.id).promise;const report=manager.readReport(f.session,batch,sample);
|
||||
assert.equal(report.inputVerified,false);assert.equal(report.environmentComparison.matched,false);assert.equal(report.summary.candidate,'unknown');
|
||||
});
|
||||
test('evaluation denominator distinguishes attempted unsealed candidates from unexecuted samples',()=>{
|
||||
for(const status of ['candidate_running','candidate_complete','awaiting_review','paused','collecting','adopting','sealed']){
|
||||
const summary=evaluationSummary({evidenceMode:'local-fixture',samples:[{status}]});
|
||||
@@ -126,6 +145,10 @@ test('stop cancels only current candidate and preserves partial results instead
|
||||
const f=await prepared(t,{respond:({signal})=>new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}))});await baseline(f);
|
||||
const started=f.manager.start(f.session,f.batch.id,f.batch.fingerprint,f.sample.id);await until(()=>f.requests.length===1);await f.runtime.stop(f.session.id);await started.promise;
|
||||
assert.equal(f.requests.length,1);assert.equal(f.runtime.hasActivity(),false);assert.notEqual(f.sample.status,'candidate_complete');assert.deepEqual(ownerBytes(f),f.original);
|
||||
await f.manager.seal(f.session,f.batch.id,f.batch.fingerprint,f.sample.id).promise;
|
||||
const report=f.manager.readReport(f.session,f.batch,f.sample);
|
||||
assert.equal(report.summary.candidate,'stopped');assert.equal(report.inputVerified,false);
|
||||
assert.equal(report.environmentComparison.matched,false);assert.equal(report.original.attempts[0].status,'failed');assert.equal(f.requests.length,1);
|
||||
});
|
||||
test('restart recovers interrupted evaluations as unknown and keeps completed checks and plan identity',async t=>{
|
||||
const f=await prepared(t);await baseline(f);const fingerprint=f.batch.fingerprint,jobId=f.sample.baselineJobId;
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { WorkspaceManager } from '../../src/core/workspaces/git-workspaces.mjs';
|
||||
import { deliveryGit, writeDeliveryFile as write } from './delivery-project.mjs';
|
||||
|
||||
export async function environmentProject(f,{dependency=true,postinstall="node -e \"require('fs').writeFileSync('node_modules/lifecycle.txt','approved')\"",response='ok'}={}) {
|
||||
let registry='https://registry.npmjs.org/',requests=0,server=null,bytes;
|
||||
if(dependency) {
|
||||
const pack=path.join(f.root,'tar-content');fs.mkdirSync(path.join(pack,'package'),{recursive:true});
|
||||
fs.writeFileSync(path.join(pack,'package','package.json'),JSON.stringify({name:'awb-env-fixture',version:'1.0.0',main:'index.cjs'}));
|
||||
fs.writeFileSync(path.join(pack,'package','index.cjs'),'module.exports = { value: 42 };');
|
||||
const tar=path.join(f.root,'fixture.tgz');execFileSync(process.platform==='win32'?'tar.exe':'tar',['-czf',tar,'-C',pack,'package'],{windowsHide:true});bytes=fs.readFileSync(tar);
|
||||
server=http.createServer((request,result)=>{requests++;if(response==='hang'){request.on('close',()=>result.destroy());return;}
|
||||
if(response!=='ok'){result.writeHead(503,{'Content-Type':'text/plain'});result.end('fixture registry unavailable');return;}
|
||||
result.writeHead(200,{'Content-Type':'application/octet-stream'});result.end(bytes);
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));registry='http://127.0.0.1:'+server.address().port+'/';
|
||||
f.onCleanup(()=>{server.closeAllConnections();return new Promise(resolve=>server.close(resolve));});
|
||||
}
|
||||
const manifest={name:'environment-fixture',version:'1.0.0',private:true,type:'module',scripts:{test:'node --test test.test.mjs',...(postinstall?{postinstall}: {})},
|
||||
...(dependency?{dependencies:{'awb-env-fixture':'1.0.0'}}:{})};
|
||||
write(f,'package.json',JSON.stringify(manifest));write(f,'.gitignore','node_modules/\ndist/\n');
|
||||
write(f,'package-lock.json',JSON.stringify({name:manifest.name,version:manifest.version,lockfileVersion:3,requires:true,packages:{'':{name:manifest.name,version:manifest.version,...(dependency?{dependencies:manifest.dependencies}:{})},
|
||||
...(dependency?{'node_modules/awb-env-fixture':{version:'1.0.0',resolved:registry+'awb-env-fixture/-/awb-env-fixture-1.0.0.tgz',integrity:'sha512-'+createHash('sha512').update(bytes).digest('base64')}}:{})}}));
|
||||
write(f,'test.test.mjs',dependency?"import test from 'node:test';import assert from 'node:assert/strict';import fixture from 'awb-env-fixture';test('uses installed dependency',()=>assert.equal(fixture.value,42));":"import test from 'node:test';import assert from 'node:assert/strict';test('builtin check',()=>assert.equal(6*7,42));");
|
||||
deliveryGit(f,['init','--initial-branch=main']);deliveryGit(f,['-c','core.autocrlf=false','add','.']);deliveryGit(f,['-c','core.autocrlf=false','-c','user.name=Workbench QA','-c','user.email=qa@workbench.local','commit','-m','Owned dependency fixture']);
|
||||
const run=f.store.beginRun(f.session,'核对依赖环境并执行工程检查',false,f.store.config);f.session.status='paused';f.store.finishRun(f.session,run);
|
||||
const workspaces=new WorkspaceManager(f.store);f.onCleanup(()=>workspaces.stopAll());
|
||||
const workspace=await workspaces.prepare(f.session,'环境准备验收');const {promise}=await workspaces.start(f.session,workspace.id,workspace.fingerprint);
|
||||
const ready=await promise;if(ready.status!=='ready')throw new Error(ready.summary);
|
||||
const project=f.store.project(workspace.childProjectId),session=f.store.session(workspace.childSessionId),childRun=f.store.beginRun(session,'核对独立环境并检查',false,f.store.config);
|
||||
session.status='paused';f.store.finishRun(session,childRun);
|
||||
return {project,session,workspace,registry,requests:()=>requests,sourceRoot:f.projectRoot,root:project.root};
|
||||
}
|
||||
Reference in New Issue
Block a user