feat: verify existing file results and preserve honest task delivery

This commit is contained in:
Agent Workbench Dev
2026-11-02 14:30:38 +08:00
parent 0dc0325346
commit d5d9df8275
44 changed files with 1011 additions and 81 deletions
+3
View File
@@ -90,3 +90,6 @@ docs/release-efficiency-1.23-evidence/** -text whitespace=blank-at-eol,blank-at-
docs/release-efficiency-1.23-evidence/**/*.log binary
docs/release-efficiency-1.23-evidence/**/*.tap binary
docs/release-efficiency-release-identity.json -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
docs/existing-results-1.24-evidence/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
docs/existing-results-*.json -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
+8
View File
@@ -1,5 +1,13 @@
# Agent Workbench 更新记录
## 1.24.0 · 已有成果续接与真实交付(开发验收中)
- 当前已有文件可经完整读取和SHA核对纳入成果,保存Task/Run、原文件快照、任务要求与显式采用来源。
- 文件或要求变化会标明失效;模型重复登记不算进展,跨项目/会话和未读完整范围均拒绝。
- 文件成果、实际修改、工程检查、页面验收与Git分开;允许无新增修改的如实交付,明确修改要求仍需新改动。
- 新增当前成果界面、results计划类别和手机只读观察,保存失败保留输入,原失败运行不改写。
- 正式部署、发行与最终验收尚待完成。
## 1.23.0 · 发行效率与更新进度(已本地交付)
- 运行包保留离线帮助、原研究报告及必要运行时,完整历史证据按原路径/SHA独立分发;源码仍完整。
+15
View File
@@ -0,0 +1,15 @@
# 当前文件成果与无新增修改交付
1.24开发范围:把工程里已存在、满足当前任务的文本文件登记为成果,并继续后续工作。部署状态以QA-1.24和发行身份收据为准。
在「任务 → 当前文件成果」展开「核对已有文件」,选择项目文件,核对当前内容和SHA-256,填写它满足当前要求的原因。若来自本会话旧Task,显式选择原成果来源,再点击「核对并采用此文件」。源文件不变;原文件字节、采用原因、当前Task/Run、任务要求和旧来源保存为独立工件。
任务目标已满足时可以点击「按当前成果结束任务」。系统继续核对明确的修改要求、原工程检查、页面验收及执行计划。原失败运行保持原状态;任务结束不补造一次成功的模型运行。无新增修改时显示对应结果,不生成空提交,也不将用户原有未提交改动纳入本任务Git交付。
模型使用`verify_existing_files`前,须用本Task的`read_file`完整分页读取全部所选文件。SHA相同但只读了一段仍会拒绝。原调用ID、参数SHA、返回页和实际文件字节共同核对;同Task续接可沿用仍有效的读取,跨Task必须重新读取并显式选择来源。范围为当前项目、当前会话,单份最多8个1MB以内UTF-8文本文件。
文件或任务要求变化后,原凭据保持不变,当前核对显示失效。点击重新打开、核对当前文件,保留原采用原因并修订。相同文件和要求重复登记返回原凭据,不能制造新进展;同Task不能把自身凭据再次设为采用来源。每Task最多64份凭据,旧Task来源列表按当前文件限定。历史读取、当前成果、实际写入、测试、页面观察和Git提交各自保持真实来源。
复杂任务的计划可选「当前文件成果」类别,按文件范围引用原成果ID核验;「源码改动」仍要求本Task已应用的真实变更集。文字原因和文件SHA不能独立证明业务功能正确。明确修改、测试或页面行为要求仍需相应实际证据。
手机伴随页只显示当前Task/Run、文件SHA、原来源及当前/失效状态,不新增写文件、结束任务或访问宿主配置的权限。桌面390px与实际配对网关浏览器验收分别记录;它们不代替新iPhone实机验收。
+1 -1
View File
@@ -1,6 +1,6 @@
# 1.24 计划:已有成果续接与真实交付
状态:后续方案;先完成 1.23 独立发行验收、保留状态部署和回顾。这里的能力尚未实现,不能写入当前发行的完成清单。
状态:1.23已交付,1.24开发及独立验收进行中。成果凭据、完成判定、计划类别、报告和界面已实现,发行及正式部署尚未验收;不能当作当前正式能力。见EXISTING-FILE-RESULTS.md,最终状态以QA-1.24和发行身份为准。
目标是让工作台能继续修改、核对和交付工程里已经存在的成果。用户说“继续”“看看刚才的文件”时,应保留原目标与明确限制,根据当前文件和所属证据判断下一步;无需为了满足内部变更门槛而重写相同文件。
+21
View File
@@ -1,5 +1,17 @@
# 汇总发现
## 1.24 当前成果核对:实现依据
开发相关C轮77/77通过(运行期间继续实现,作为开发回归,最终冻结需重新绑定验证)。新增网页D轮首个过期SHA恢复流程通过,随后工件预览断言发现成果JSON缺少自描述kind;已补file-result类别。原D失败截图、DOM和result原件保留。回顾同时补齐:明确点名文件必须覆盖、旧提案晚应用不能满足新修改要求、requirements深复制防旧凭据随contract引用被修改、纯解释/否定修改不算写入、历史来源原工件逐层核对。
独立旧版复现保存于.qa/existing-results-baseline-1793599104871/receipt.json:完整read_file后无改动、delivery_incomplete。当前已补独立file_result/原文件快照、原调用分页覆盖、当前需求SHA、跨Task显式采用、results计划类别、运行结束核对和用户手动核对接口。尚未完成UI及发行验收,不记作正式能力。
首轮17项中15通过、2失败均为新测试用错既有返回契约(propose_file返回引用而非change对象;步骤核验响应status=completed)。保留原失败,修正测试调用后重验;没有据此改产品状态或降低断言。错误路径artifact-store已按store import定位storage目录;PowerShell rg不接受未展开的通配路径,后续使用实际文件。
当前read_file保留整个文件SHA、行范围和字符分页;可用原调用resultArtifact核对实际返回内容,不能把只读取一页当作读完全文。完成分支仅接受本Task applied;原有propose_file相同内容返回unchanged,因而会误暂停。采用独立file_result记录与JSON工件,核对当前需求、文件原字节及原读取覆盖;跨Task须显式采用,不混入Git提交。
恢复后补记:根工作目录无AGENTS.md,仓库内存在并已读取;不得向历史.qa递归列举(本次rg输出过大已停止/结束),今后仅搜索精确文件或浅层目录。一次占位补丁未匹配,未改文件;改为按真实标题补丁。源码路径以rg结果为准,避免重复猜测。
## 1.22最终交付核对
1.22.0已完成所属Vite预览、独立桌面浏览区、有界DOM/原截图与审批动作、独立登录资料/撤销/下载、手机原观察SHA核对的本地交付。独立源码683/683(C完整原轮通过,D严格绑定后沿用)、33类250组原B串行界面(产品输入相同,严格绑定后沿用)、源码/便携/实际安装各17组浏览流程、同载荷安装7组、正式30页及Edge/Electron两视口通过。原PID36552/Provider保持,17项目/32全部会话/3239记录/6229事件及1780工件文件原字节保持,9229关闭。本轮验收发起真实模型请求0。
@@ -843,6 +855,8 @@ B独立管线已运行,受门控的推广等待独立源码/便携/同载荷
冻结期间复核了历史UI与随包专项的收据归属:all-ui将原结果复制到版本化docs指针,并保留各自日志/独立UUID目录;随后随包环境、原生参数、等待、协议、视觉、缓存、伴随及评测验证器写各自原目录,不覆盖这些主回归docs收据。最终封存仍逐一核对原结果/日志中的显式目录和截图SHA;没有仅凭最新全局指针推断历史结果。此项为静态归属审查,不增加模型或重跑已通过的验证。
# 当前现场:两条基本操作缺口
1.24接续说明:下段为1.22历史现场。当前0dc0325干净起点,正式1.23已交付;runtime完成及task-plan changes只接受本Task已应用改动。新增成果凭据必须绑定当前文件、原读取工具/工件、任务要求与来源Task/Run,不能用模型文字绕过明确修改/检查要求。沿用中文React工作台,成果核对嵌入任务和文件流程。
正式服务实际 1.22.0,URL 的旧 release 参数不代表实际版本。网页的选择文件夹按钮被 desktop 条件隐藏;选中 pelican-bicycle.html 后只有源码且无预览入口。文件包含内联 SVG/JS 动画;现有任务浏览能力要求 Vite/桌面,不适用于直接打开普通 HTML。本次用已认证的本机一层目录浏览补网页选择;HTML 以独立 loopback 源、受限静态资源和 sandbox 渲染,不把项目脚本放进工作台 API 同源。
## 1.23 开始前回顾
@@ -863,3 +877,10 @@ B独立管线已运行,受门控的推广等待独立源码/便携/同载荷
### 1.23 最终正式交付与回顾
1.23.0已完成发行效率与真实更新进度的本地交付。运行包10902文件/651935923字节,完整历史证据独立分发,源码完整。703/703测试保留原B来源;C逐输入/日志SHA和22份构建绑定后续接全部剩余阶段通过,B原整轮失败不改写。完整安装11组归属B,C可执行/运行时字节严格绑定后实际重验三归档、便携及正式原安装器。正式网页5组与原生窗口回看通过;原PID36552/Provider、17项目/33全部会话/3239记录/6230事件/1780工件、每表每行/全部导出/工件原字节保持,9229关闭。真实配置模型请求0。正式原操作ddfe9b45e26d4ee34560d161a56bef7312797ee2efd9fa3c1d72935406374452,安装指针revision14,最终manifest 81a90b375bc21c589268c2c3d971165ebc2c146ab9954e3a897d37bdc3421349。原操作计时1017.119秒;外层含前后完整比较1028.473秒,二者不混作安装进程专属时间。证据223份/74383114字节按原SHA封存;私有快照仅哈希收据入Git。最终网页使用CUA实际验证,原生窗口从正式根启动器恢复并留在原文件;不重放已成功安装阶段。下一1.24只读预研确认当前完成分支要求本Task applied改动,计划先复现再增加当前文件采用凭据,尚未实现。
### 1.24 开发切片审查与验收续接
I轮实际Edge/Electron各7组、手机真实配对TLS网关观察2组,共16组/8截图通过;不等同新iPhone实机或真实模型自主工程。H轮在12组之后发生隐藏Electron窄屏截图超时,原结果保留;验收改用现有桌面验收器一致的showInactive/setContentSize并等待实际innerWidth,未更改产品渲染规则。
审查补齐来源列表请求序号和按路径刷新,拒绝同Task自采用制造新凭据,并将原记录与核验视图的TypeScript类型分开。J轮相关76项75通过,唯一失败是新测试的活动运行夹具缺project字段,修正夹具、保留原失败;K轮最新专项21/21通过。原C77/77及I16组是开发来源,最终冻结另验。版本和源码/便携/全UI/引擎/升级验收白名单同步1.24,未升级正式服务、未读取Key、未发起真实模型请求。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "local-agent-workbench",
"version": "1.23.0",
"version": "1.24.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "local-agent-workbench",
"version": "1.23.0",
"version": "1.24.0",
"dependencies": {
"@babel/parser": "7.29.11",
"@peculiar/x509": "3.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "local-agent-workbench",
"version": "1.23.0",
"version": "1.24.0",
"private": true,
"type": "module",
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
+19
View File
@@ -1,5 +1,15 @@
# 统一执行进度
- UI D/E/F开发轮原失败保留:D原成果工件缺kind(已补);E窄屏需从实际“查看任务记录”入口打开(修正验收步骤);F迟到回执脚本在fulfill前unroute,已改为等待原handler终态后解除,不改产品审批/返回逻辑。F19项专项/任务控制通过,F网页已通过6组。一次补丁重复文件操作、一次import上下文不匹配均原子拒绝,已按实际import和单文件修改完成。
- 1.24切片B/C:新file_result记录绑定完整当前read_file页/原调用与原文件快照、任务要求及显式旧来源。已接入模型工具/有限上下文、results计划核验、完成判定、只读手机投影和无新增修改报告。17项专项/原任务控制相关回归第二轮17/17通过,首轮15/17原失败仍保留。界面实现待构建与真实流程验收,未部署正式。
- 1.24恢复核对:分支与三份计划修改一致,尚无产品实现;已确认read_file全文SHA/分页格式及相同内容提案unchanged,准备保存独立复现。无正式模型请求或用户任务执行。
## 1.24启动
接续0dc0325并创建feat/existing-results-1.24;正式1.23不动。已读PLAN-1.24及执行规范,采用planning-with-files、product-ui-ux、frontend-design。catchup脚本无额外输出。初次计划补丁因progress标题不匹配拒绝,已改真实标题;一次session-store路径猜测改为rg定位。继续独立复现与成果凭据设计,不将预研当实现。
## 1.22最终交付核对
本地发行提交751bbbd后,最终审计拒绝候选A的54份原日志未进入Git(89,748字节),原文件仍在磁盘且全部与A已封存清单SHA/长度一致;B/C/开发/最终发行原件均齐全。按清单精确补入这些原字节,原失败/清单不改写;无需重跑已通过产品检查。后续最终审计必须检查全部五份清单的Git blob,不能只核对本次新增证据目录。该收尾遗漏与1.22实际安装/正式验收通过分别记录。
@@ -1321,3 +1331,12 @@ C严格绑定续接整轮通过:仅.gitattributes与当前桌面验收器差
### 1.23 最终正式交付与回顾
1.23.0已完成发行效率与真实更新进度的本地交付。运行包10902文件/651935923字节,完整历史证据独立分发,源码完整。703/703测试保留原B来源;C逐输入/日志SHA和22份构建绑定后续接全部剩余阶段通过,B原整轮失败不改写。完整安装11组归属B,C可执行/运行时字节严格绑定后实际重验三归档、便携及正式原安装器。正式网页5组与原生窗口回看通过;原PID36552/Provider、17项目/33全部会话/3239记录/6230事件/1780工件、每表每行/全部导出/工件原字节保持,9229关闭。真实配置模型请求0。正式原操作ddfe9b45e26d4ee34560d161a56bef7312797ee2efd9fa3c1d72935406374452,安装指针revision14,最终manifest 81a90b375bc21c589268c2c3d971165ebc2c146ab9954e3a897d37bdc3421349。原操作计时1017.119秒;外层含前后完整比较1028.473秒,二者不混作安装进程专属时间。证据223份/74383114字节按原SHA封存;私有快照仅哈希收据入Git。最终网页使用CUA实际验证,原生窗口从正式根启动器恢复并留在原文件;不重放已成功安装阶段。下一1.24只读预研确认当前完成分支要求本Task applied改动,计划先复现再增加当前文件采用凭据,尚未实现。
### 1.24 开发切片审查与验收续接
I轮实际Edge/Electron各7组、手机真实配对TLS网关观察2组,共16组/8截图通过;不等同新iPhone实机或真实模型自主工程。H轮在12组之后发生隐藏Electron窄屏截图超时,原结果保留;验收改用现有桌面验收器一致的showInactive/setContentSize并等待实际innerWidth,未更改产品渲染规则。
审查补齐来源列表请求序号和按路径刷新,拒绝同Task自采用制造新凭据,并将原记录与核验视图的TypeScript类型分开。J轮相关76项75通过,唯一失败是新测试的活动运行夹具缺project字段,修正夹具、保留原失败;K轮最新专项21/21通过。原C77/77及I16组是开发来源,最终冻结另验。版本和源码/便携/全UI/引擎/升级验收白名单同步1.24,未升级正式服务、未读取Key、未发起真实模型请求。
构建K轮调用固定npm入口但未固定其子进程PATH,Vite实际使用旧Node16而失败;保留原日志。L轮显式将固定Node24目录置于本次进程PATH首位,完整构建通过。QA Python本轮实测3.12.10/pytest8.4.2,以实际身份为准,不沿用历史3.10数字。
+1
View File
@@ -18,6 +18,7 @@ const prefixes = Object.freeze({
'1.22.0': 'embedded-browser',
'1.22.1': 'local-files',
'1.23.0': 'release-efficiency',
'1.24.0': 'existing-results',
});
export function releaseEvidencePrefix(version) {
const prefix = prefixes[version];
+1 -1
View File
@@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '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', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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 = [];
+21 -20
View File
@@ -9,35 +9,36 @@ 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', '1.21.0', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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 = [
...(version === '1.23.0' ? [['verify-release-efficiency-ui.mjs', null]] : []),
...(['1.22.1', '1.23.0'].includes(version) ? [['verify-local-files.mjs', null]] : []),
...(['1.22.0', '1.22.1', '1.23.0'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]),
...(['1.21.0', '1.22.0', '1.22.1', '1.23.0'].includes(version)?[['verify-environment-ui.mjs',null],['verify-model-fidelity-ui.mjs',null],['verify-model-wait-ui.mjs',null],['verify-task-control-ui.mjs',null]]:[]),
...(['1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
...(['1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.0'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []),
...(version === '1.24.0' ? [['verify-file-results-ui.mjs', null]] : []),
...(['1.23.0', '1.24.0'].includes(version) ? [['verify-release-efficiency-ui.mjs', null]] : []),
...(['1.22.1', '1.23.0', '1.24.0'].includes(version) ? [['verify-local-files.mjs', null]] : []),
...(['1.22.0', '1.22.1', '1.23.0', '1.24.0'].includes(version)?[['verify-embedded-browser.mjs',null]]:[]),
...(['1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0'].includes(version)?[['verify-environment-ui.mjs',null],['verify-model-fidelity-ui.mjs',null],['verify-model-wait-ui.mjs',null],['verify-task-control-ui.mjs',null]]:[]),
...(['1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0'].includes(version) ? [['verify-evaluations-ui.mjs', null]] : []),
...(['1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.0'].includes(version) ? [['verify-project-cache-ui.mjs', null]] : []),
...(['1.18.0', '1.19.0', '1.20.0', '1.20.1', '1.21.0', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.21.0', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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']);
@@ -93,7 +94,7 @@ 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, evidence.checks].find(Array.isArray);
const passed = [evidence.passed, evidence.cases, evidence.assertions, evidence.checks, evidence.results].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);
+1 -1
View File
@@ -22,7 +22,7 @@ export async function verifyControlledApi({ api, url, token, directory, appRoot,
const origin = new URL(url);
assert.equal(origin.hostname, '127.0.0.1'); assert.notEqual(origin.port, '4318');
const expectedVersion = JSON.parse(fs.readFileSync(path.join(appRoot, fs.existsSync(path.join(appRoot, 'MANIFEST.json')) ? 'MANIFEST.json' : 'package.json'), 'utf8')).version;
assert.ok(['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', '1.22.0', '1.22.1', '1.23.0'].includes(expectedVersion));
assert.ok(['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', '1.22.0', '1.22.1', '1.23.0', '1.24.0'].includes(expectedVersion));
const bootstrap = await api('/bootstrap'); assert.equal(bootstrap.version, expectedVersion);
assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const root = path.join(directory, 'compiled-controlled-node'), hooks = path.join(directory, 'disabled-hooks');
+166
View File
@@ -0,0 +1,166 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import https from 'node:https';
import assert from 'node:assert/strict';
import { randomUUID, X509Certificate } from 'node:crypto';
import { chromium, _electron, expect } from 'playwright/test';
import { fixture, launchWorkbench } from '../tests/helpers.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
import { FileResults } from '../src/core/tasks/file-results.mjs';
import { readText } from '../src/server/files.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-file-results-ui.mjs — isolated Edge/Electron existing-file receipts, changed bytes, explicit adoption, no-change delivery and late-response scope. Optional AGENT_WORKBENCH_QA_APP_ROOT. No model requests.'); process.exit(0); }
if (process.argv.length > 2) throw new Error('Use --help.');
const appRoot = path.resolve(process.env.AGENT_WORKBENCH_QA_APP_ROOT || '.'), directory = path.resolve('.qa/file-results-ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
const version = JSON.parse(fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8')).version;
const checks = [], screenshots = [], errors = [];
const mark = name => { checks.push(name); console.log('PASS ' + name); };
let stage = 'setup', result;
const shot = async (page, name) => { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' }); screenshots.push(file); };
const overflow = page => page.evaluate(() => ({ width: innerWidth, document: document.documentElement.scrollWidth })).then(value => assert.ok(value.document <= value.width + 1, JSON.stringify(value)));
async function mobileFlow(browser, host, f, htmlPath) {
const initial = await host.api('/companion'); assert.ok(initial.addresses.length);
const address = initial.addresses[0].address, reservation = http.createServer(); await new Promise(resolve => reservation.listen(0, address, resolve));
const port = reservation.address().port; await new Promise(resolve => reservation.close(resolve));
const gateway = await host.api('/companion/start', { address, port }), target = new URL(gateway.origin);
const cert = await fetch(host.url + '/api/companion/certificate', { headers: { 'X-Workbench-Token': host.bootstrap.token } }); assert.equal(cert.status, 200);
const ca = new X509Certificate(Buffer.from(await cert.arrayBuffer())).toString(); assert.equal(new X509Certificate(ca).ca, true);
const pair = await host.api('/companion/pair', { projectIds: [f.project.id], permissions: { observe: true, approve: false, stop: false }, expiresInHours: 24 });
let cookie = '';
const relay = http.createServer((request, response) => {
const forwarded = https.request(new URL(request.url, target), { method: request.method, ca, servername: '', headers: { Host: target.host, Origin: target.origin, Connection: 'close', ...(cookie ? { Cookie: cookie } : {}), ...(request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {}) } }, incoming => {
if (incoming.headers['set-cookie']?.length) cookie = incoming.headers['set-cookie'][0].split(';')[0];
const headers = { ...incoming.headers }; delete headers['set-cookie']; response.writeHead(incoming.statusCode, headers); incoming.pipe(response);
});
forwarded.on('error', () => { if (!response.headersSent) response.writeHead(503); response.end(); }); request.pipe(forwarded);
});
await new Promise(resolve => relay.listen(0, '127.0.0.1', resolve));
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }), mobile = await context.newPage();
mobile.on('pageerror', error => errors.push('mobile: ' + error.message));
try {
await mobile.goto('http://127.0.0.1:' + relay.address().port + '/#pair=' + new URLSearchParams(new URL(pair.url).hash.slice(1)).get('pair'));
await mobile.getByLabel('设备名称', { exact: true }).fill('当前成果观察夹具'); await mobile.getByRole('button', { name: '连接这台电脑', exact: true }).click();
await mobile.locator('.mobile-task-row').filter({ hasText: f.session.title }).click();
const panel = mobile.getByLabel('当前文件成果', { exact: true }); await expect(panel).toContainText('当前文件已核对');
const row = (await host.api('/sessions/' + f.session.id + '/file-results')).results[0]; await expect(panel).toContainText(row.files[0].sha256);
await expect(panel).toContainText(row.taskId.slice(0, 8)); await expect(panel).toContainText(row.runId.slice(0, 8)); await overflow(mobile); await shot(mobile, 'mobile-current-results');
await expect(mobile.getByRole('button', { name: '按当前成果结束任务', exact: true })).toHaveCount(0);
mark('mobile 390px: actual paired TLS gateway exposes current Task/Run and file SHA through observation only; no OS trust changes');
fs.appendFileSync(htmlPath, '<!-- 手机观察期间用户编辑 -->\n'); await mobile.reload();
await expect(mobile.getByRole('heading', { name: '项目任务', exact: true })).toBeVisible();
await mobile.locator('.mobile-task-row').filter({ hasText: f.session.title }).click();
await expect(mobile.getByLabel('当前文件成果', { exact: true })).toContainText('文件或要求已变化'); await overflow(mobile); await shot(mobile, 'mobile-stale-results');
mark('mobile 390px: authenticated refresh reports stale bytes and retains original SHA without granting file/finish permissions');
} catch (error) { await shot(mobile, 'mobile-failure').catch(() => {}); fs.writeFileSync(path.join(directory, 'mobile-failure.html'), await mobile.content().catch(() => 'unavailable')); throw error; }
finally { await context.close(); relay.closeAllConnections(); await new Promise(resolve => relay.close(resolve)); await host.api('/companion/close', {}); }
}
async function surface(kind) {
const disposers = [], t = { after: dispose => disposers.push(dispose) }, f = fixture(t);
const htmlPath = path.join(f.projectRoot, 'result.html');
fs.writeFileSync(htmlPath, '<!doctype html><html lang="zh"><meta charset="UTF-8"><title>已有成果</title><h1>当前已有成果</h1><p>用户保存的内容</p></html>\n');
const begin = (session, goal, title, forceNewTask = false) => {
const run = f.store.beginRun(session, goal, false, f.store.config, { forceNewTask }); session.status = 'paused'; session.title = title; f.store.finishRun(session, run, 'delivery_incomplete'); return run;
};
const goal = '创建 result.html 文件,已有内容满足时沿用,无需测试';
const originalRun = begin(f.session, goal, '核对已有HTML');
const sourceSession = f.store.createSession(f.project.id);
begin(sourceSession, goal, '显式采用旧成果');
const source = new FileResults(f.store).record(sourceSession, { files: [{ path: 'result.html', sha256: readText(f.project, 'result.html').sha256 }], reason: '原任务已保存HTML成果,作为后续显式采用的来源。' }, { source: 'user' });
begin(sourceSession, goal, '显式采用旧成果', true);
const blocked = f.store.createSession(f.project.id); begin(blocked, '修改 result.html 文件标题,无需测试', '修改要求不能绕过');
f.store.close();
const host = await launchWorkbench(t, f.data, {}, { appRoot });
assert.notEqual(new URL(host.url).port, '4318'); assert.equal(host.bootstrap.config.hasKey, false);
assert.equal(host.bootstrap.version, version);
let browser, application, page;
try {
if (kind === 'edge') { browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); await page.goto(host.url); }
else {
const executable = desktopExecutableIdentity(appRoot).path, packaged = executable.toLowerCase().endsWith('agentworkbench.exe');
application = await _electron.launch({ executablePath: executable, args: [...(packaged ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', new URL(host.url).port, '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
page = await application.firstWindow(); await (await application.browserWindow(page)).evaluate(window => { window.showInactive(); window.setContentSize(1440, 1000); });
await expect.poll(() => page.evaluate(() => innerWidth)).toBe(1440);
}
page.on('pageerror', error => errors.push(kind + ': ' + error.message));
await page.locator('.connection.connected').waitFor();
const panel = () => page.getByLabel('当前文件成果', { exact: true });
const select = async session => {
if (!await page.getByLabel('当前项目', { exact: true }).isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await page.getByLabel('当前项目', { exact: true }).selectOption(f.project.id);
await page.locator('.session-list button').filter({ hasText: session.title }).click();
await page.getByRole('button', { name: '查看任务记录', exact: true }).click(); await expect(panel()).toBeVisible();
};
const form = async () => { const details = panel().locator('.file-result-form'); if (!await details.evaluate(node => node.open)) await details.locator('summary').click(); };
const choose = async () => { await form(); await panel().getByLabel('成果文件', { exact: true }).selectOption('result.html'); await expect(panel().getByLabel('成果文件内容')).toContainText('当前已有成果'); };
const route = '/sessions/' + f.session.id;
stage = kind + ': stale-save recovery'; await select(f.session); await choose();
const reason = '核对已有HTML的标题与完整内容,沿用用户已有成果。'; await panel().getByLabel('成果采用原因').fill(reason);
fs.appendFileSync(htmlPath, '<!-- 保存前由用户修改 -->\n');
await panel().getByRole('button', { name: '核对并采用此文件', exact: true }).click();
await expect(panel().getByRole('status')).toContainText('变化'); await expect(panel().getByLabel('成果采用原因')).toHaveValue(reason);
assert.equal((await host.api(route + '/file-results')).results.length, 0);
await panel().getByRole('button', { name: '重新读取当前文件', exact: true }).click(); await expect(panel().getByLabel('成果文件内容')).toContainText('保存前由用户修改');
await panel().getByRole('button', { name: '核对并采用此文件', exact: true }).click();
await expect(panel().locator('.file-result-row')).toHaveCount(1); await expect(panel()).toContainText('当前文件已核对');
mark(kind + ': changed SHA refuses stale save, retains input, rereads actual bytes and records owned receipt'); await shot(page, kind + '-current-results');
await panel().getByRole('button', { name: '查看原成果凭据', exact: true }).click();
const modal = page.getByRole('dialog', { name: '执行结果工件', exact: true }); await expect(modal).toContainText('file-result'); await expect(modal).toContainText('SHA256'); await page.keyboard.press('Escape');
await panel().getByRole('button', { name: '按当前成果结束任务', exact: true }).click();
await expect(panel().getByRole('status')).toContainText('任务已按当前成果结束');
const completed = await host.api(route); assert.equal(completed.status, 'completed'); assert.equal(completed.execution.task.delivery.status, 'existing_verified');
assert.equal(completed.changes.length, 0); assert.equal(completed.execution.checks.length, 0); assert.equal(completed.execution.deliveries.length, 0); assert.equal(completed.execution.task.usage.requests, 0);
assert.deepEqual(completed.execution.run, originalRun);
mark(kind + ': current receipt ends no-test task, preserves old failed run and creates no file change/check/commit/model request');
await page.reload(); await page.locator('.connection.connected').waitFor(); await select(f.session); await expect(panel()).toContainText('结束时采用已有成果');
fs.appendFileSync(htmlPath, '<!-- 交付后用户继续编辑 -->\n'); await panel().getByRole('button', { name: '刷新成果状态', exact: true }).click(); await expect(panel()).toContainText('需要重新核对');
await panel().getByRole('button', { name: '重新打开此文件核对', exact: true }).click(); await form(); await expect(panel().getByLabel('成果采用原因')).toHaveValue(reason);
await expect(panel().getByLabel('成果文件内容')).toContainText('交付后用户继续编辑');
mark(kind + ': refresh retains receipt and later file edits produce specific stale recovery without discarding reason');
stage = kind + ': narrow current results';
if (application) await (await application.browserWindow(page)).evaluate(window => { window.showInactive(); window.setContentSize(390, 844); }); else await page.setViewportSize({ width: 390, height: 844 });
await expect.poll(() => page.evaluate(() => innerWidth)).toBe(390);
await page.getByRole('button', { name: '查看任务记录', exact: true }).click(); await expect(panel()).toBeVisible(); await panel().scrollIntoViewIfNeeded(); await overflow(page); await shot(page, kind + '-390-results');
mark(kind + ': 390px task entry displays readable paths/hashes and actions without page overflow');
if (application) await (await application.browserWindow(page)).evaluate(window => window.setContentSize(1440, 1000)); else await page.setViewportSize({ width: 1440, height: 1000 });
await expect.poll(() => page.evaluate(() => innerWidth)).toBe(1440);
stage = kind + ': explicit adoption'; await select(sourceSession); await choose(); await panel().getByLabel('成果采用原因').fill('按当前要求再次核对完整HTML,显式采用原任务成果。');
await expect(panel().getByRole('button', { name: '核对并采用此文件', exact: true })).toBeDisabled();
await panel().getByLabel('成果来源').selectOption(source.result_id); await panel().getByRole('button', { name: '核对并采用此文件', exact: true }).click();
await expect(panel().locator('.file-result-row')).toHaveCount(1); await expect(panel()).toContainText('采用自 Task');
const adopted = (await host.api('/sessions/' + sourceSession.id + '/file-results')).results[0]; assert.equal(adopted.files[0].origin.resultId, source.result_id); assert.notEqual(adopted.files[0].origin.sha256, adopted.files[0].sha256);
mark(kind + ': new task explicitly selects original source, preserving old/current SHA and Task/Run'); await shot(page, kind + '-adopted');
stage = kind + ': change guard'; await select(blocked); await choose(); await panel().getByLabel('成果采用原因').fill('只核对现有文件,不能替代本次要求的标题修改。');
await panel().getByRole('button', { name: '核对并采用此文件', exact: true }).click(); await expect(panel().locator('.file-result-row')).toHaveCount(1);
await panel().getByRole('button', { name: '按当前成果结束任务', exact: true }).click(); await expect(panel().getByRole('status')).toContainText('包含修改');
assert.equal((await host.api('/sessions/' + blocked.id)).status, 'paused');
mark(kind + ': unchanged adoption cannot satisfy explicit modification, error retains current task and form');
stage = kind + ': late response'; await select(f.session); await choose();
const delayedReason = '延迟回执仍须归属原任务,不能写入后来选择的任务。'; await panel().getByLabel('成果采用原因').fill(delayedReason);
let entered, release, finished, didEnter = false; const held = new Promise(resolve => { entered = resolve; }), released = new Promise(resolve => { release = resolve; }), responded = new Promise(resolve => { finished = resolve; });
const routeErrors = [];
const matcher = '**/api/sessions/' + f.session.id + '/file-results';
await page.route(matcher, async route => {
if (route.request().method() !== 'POST') return route.continue();
try { const response = await route.fetch(); didEnter = true; entered(); await released; await route.fulfill({ response }); }
catch (error) { routeErrors.push(error.message); entered(); }
finally { finished(); }
});
try {
await panel().getByRole('button', { name: '核对并采用此文件', exact: true }).click(); await held;
await select(blocked); release(); await responded; await page.unroute(matcher); assert.deepEqual(routeErrors, []);
await expect(panel()).not.toContainText(delayedReason); assert.equal((await host.api('/sessions/' + blocked.id)).status, 'paused');
assert.equal((await host.api(route + '/file-results')).results[0].reason, delayedReason);
mark(kind + ': delayed successful save remains with original Task after UI selection changes');
} finally { release(); if (didEnter) await responded; await page.unroute(matcher); }
if (kind === 'edge') { stage = 'mobile current files'; await mobileFlow(browser, host, f, htmlPath); }
assert.equal((await host.api('/bootstrap')).config.hasKey, false);
} catch (error) { if (page) { await shot(page, kind + '-failure').catch(() => {}); fs.writeFileSync(path.join(directory, kind + '-failure.html'), await page.content().catch(() => 'unavailable')); } throw error; }
finally { await browser?.close(); await application?.close(); for (const dispose of disposers.reverse()) await dispose(); }
}
try { await surface('edge'); await surface('electron'); assert.deepEqual(errors, []); result = { success: true, version, appRoot, directory, checks, screenshots, errors, realModelRequests: 0, scope: 'Actual isolated Edge and Electron UI; 390px is desktop narrow validation, not a new iPhone test.' }; }
catch (error) { result = { success: false, stage, version, appRoot, directory, checks, screenshots, errors, error: error.stack }; process.exitCode = 1; }
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2)); fs.writeFileSync('.qa/file-results-ui-latest.json', JSON.stringify(result, null, 2)); console.log('EVIDENCE ' + directory); console.log(JSON.stringify(result));
+7 -7
View File
@@ -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','1.21.0', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.22.1', '1.23.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', '1.22.0', '1.22.1', '1.23.0'].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', '1.22.0', '1.22.1', '1.23.0', '1.24.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', '1.22.0', '1.22.1', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.22.1', '1.23.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 };
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', '1.22.0', '1.22.1', '1.23.0', '1.24.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 {} } }
+34 -20
View File
@@ -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','1.21.0', '1.22.0', '1.23.0'].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', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.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();
'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', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].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', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].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', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].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', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].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', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].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', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0', '1.24.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','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0', '1.24.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();
@@ -161,7 +161,7 @@ try {
assert.equal(actualProjectCache.realModelRequests, 0); assert.deepEqual(actualProjectCache.pageErrors, []);
}
let actualEnvironment = null, actualEnvironmentEngineering = null;
if (['1.21.0','1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.21.0','1.22.0', '1.23.0', '1.24.0'].includes(evidence.version)) {
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":')));
@@ -179,7 +179,7 @@ try {
assert.equal(actualEnvironmentEngineering.pythonTests, 2); assert.equal(actualEnvironmentEngineering.realModelRequests, 0);
}
let actualEmbeddedBrowser = null;
if (['1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.22.0', '1.23.0', '1.24.0'].includes(evidence.version)) {
stage = 'actual embedded Electron, Vite and original mobile observation';
await run(['scripts/verify-embedded-browser.mjs', '--app-root', sourceRoot], 'embedded-browser.log');
actualEmbeddedBrowser = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/embedded-browser-latest.json'), 'utf8'));
@@ -189,7 +189,7 @@ try {
assert.equal(actualEmbeddedBrowser.realModelRequests, 0); assert.deepEqual(actualEmbeddedBrowser.errors, []);
}
let actualReleaseEfficiency = null;
if (evidence.version === '1.23.0') {
if (['1.23.0', '1.24.0'].includes(evidence.version)) {
stage = 'actual update status Edge/Electron and basic saved HTML flows';
const proofs = [];
for (const script of ['verify-release-efficiency-ui.mjs', 'verify-local-files.mjs']) {
@@ -202,6 +202,20 @@ try {
}
actualReleaseEfficiency = proofs;
}
let actualFileResults = null;
if (evidence.version === '1.24.0') {
stage = 'current file results Edge, Electron and paired mobile observation';
await run(['scripts/verify-file-results-ui.mjs'], 'file-results-ui.log');
actualFileResults = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/file-results-ui-latest.json'), 'utf8'));
assert.equal(actualFileResults.success, true); assert.equal(actualFileResults.version, evidence.version);
assert.equal(fs.realpathSync.native(actualFileResults.appRoot), sourceRoot); assert.equal(actualFileResults.checks.length, 16);
assert.equal(actualFileResults.realModelRequests, 0); assert.deepEqual(actualFileResults.errors, []);
assert.equal(actualFileResults.screenshots.length, 8);
for (const screenshot of actualFileResults.screenshots) {
assert.ok(fs.realpathSync.native(screenshot).startsWith(path.join(sourceRoot, '.qa') + path.sep));
assert.ok(fs.statSync(screenshot).size > 1000);
}
}
// 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'));
@@ -229,14 +243,14 @@ try {
for (const key of ['fail', 'cancelled', 'skipped', 'todo']) assert.equal(groupStats[key], 0);
}
let actualTaskControl = null;
if (['1.20.1', '1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.20.1', '1.21.0', '1.22.0', '1.23.0', '1.24.0'].includes(evidence.version)) {
stage = 'task control desktop and 390px';
await run(['scripts/verify-task-control-ui.mjs', '--app-root', sourceRoot], 'task-control-ui.log');
actualTaskControl = JSON.parse(fs.readFileSync(path.join(sourceRoot, '.qa/task-control-ui-validation.json'), 'utf8'));
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','1.21.0', '1.22.0', '1.23.0'].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', '1.22.0', '1.23.0', '1.24.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);
@@ -250,7 +264,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','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.17.0', '1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0', '1.24.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'));
@@ -260,7 +274,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','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.18.0', '1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0', '1.24.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'));
@@ -270,7 +284,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','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.19.0', '1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0', '1.24.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'));
@@ -280,7 +294,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','1.21.0', '1.22.0', '1.23.0'].includes(evidence.version)) {
if (['1.20.0', '1.20.1','1.21.0', '1.22.0', '1.23.0', '1.24.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();
@@ -299,7 +313,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, testPlan, actualReleaseEfficiency, actualEmbeddedBrowser, 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.' };
inputs, inputFiles: inputs.length, logs, buildMatchedFiles: Object.keys(expected).length, buildFiles: Object.entries(expected).map(([path, sha256]) => ({ path: path.replaceAll('\\', '/'), sha256 })), tests: stats, testPlan, actualFileResults, actualReleaseEfficiency, actualEmbeddedBrowser, 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 });
+2 -1
View File
@@ -29,6 +29,7 @@ export function DeliveryPanel({ session, busy, onSession, onError, openArtifact
const unresolved = jobs.some(job => job.requiresVerification);
const pending = session.changes.some(change => ['pending', 'conflict'].includes(change.status));
const hasApplied = session.changes.some(change => change.taskId === task?.id && change.status === 'applied');
const existingOnly = !hasApplied && !!session.execution?.fileResults?.length;
const reports = session.execution?.artifacts.filter(artifact => artifact.kind === 'delivery-report-markdown') ?? [];
const latestReport = reports.at(-1);
const waitingPlan = (session.execution?.deliveryPlans ?? []).filter(plan => plan.taskId === task?.id
@@ -105,7 +106,7 @@ export function DeliveryPanel({ session, busy, onSession, onError, openArtifact
<label className="form-field delivery-message">提交说明<textarea aria-label="提交说明" rows={2} value={message} maxLength={1600} disabled={busy || running} onChange={event => setMessage(event.target.value)} /></label>
<details className="delivery-author"><summary>Git署名</summary><p>默认采用项目Git署名;尚未配置时使用 Agent Workbench 本地身份。预览会展示实际署名。</p><label className="form-field">提交者姓名<input value={authorName} disabled={busy || running} onChange={event => setAuthorName(event.target.value)} placeholder="采用默认署名" autoComplete="off" /></label><label className="form-field">提交者邮箱<input type="email" value={authorEmail} disabled={busy || running} onChange={event => setAuthorEmail(event.target.value)} placeholder="采用默认邮箱" autoComplete="off" /></label></details>
<button type="button" className="button primary" aria-label="预览Git提交" disabled={!task || !hasApplied || pending || busy || running || unresolved || planning || !message.trim()} onClick={prepare}>{planning ? <LoaderCircle size={14} className="spin" /> : <GitCommitHorizontal size={14} />}预览Git提交</button>
{(!hasApplied || pending) && <p className="record-footnote">应用本任务的文件提案后,可以准备Git提交。</p>}
{existingOnly ? <p className="record-footnote">本任务沿用已有成果,无新增修改,不创建空提交。可生成报告核对成果与原检查。</p> : (!hasApplied || pending) && <p className="record-footnote">应用本任务的文件提案后,可以准备Git提交。</p>}
{jobs.slice().reverse().map(job => <div key={job.id} className={'delivery-job ' + (job.requiresVerification ? 'delivery-attention' : '')}>
<div className="record-heading"><Status value={job.status} /><code>{job.id.slice(0, 8)}</code>{active.includes(job.status) && <button type="button" className="text-button" onClick={() => api<Session>('/sessions/' + session.id + '/delivery-jobs/' + job.id + '/stop', {}).then(onSession).catch(onError)}>停止提交</button>}</div>
<time>{date(job.startedAt)} · {job.branch}</time>
+15
View File
@@ -0,0 +1,15 @@
.file-results .record-heading { flex-wrap: wrap; }
.file-result-row { border-top: 1px solid var(--line); padding: 13px 0; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.file-result-row > div:first-child { display: flex; flex-direction: column; gap: 2px; margin-bottom: 8px; }
.file-result-row small { color: var(--muted); font-size: 11px; }
.file-result-row > p { margin: 8px 0; }
.file-result-sha { display: block; font: 11px/1.65 "Cascadia Code", Consolas, monospace; overflow-wrap: anywhere; color: var(--muted); }
.file-result-error, .file-result-notice { padding: 9px 11px; background: #faf4e8; color: #684b19; border-left: 2px solid #b18c48; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.file-result-form { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 8px; }
.file-result-form summary { cursor: pointer; font-weight: 600; font-size: 12px; padding: 5px 0; }
.file-result-form label { display: flex; flex-direction: column; gap: 6px; margin: 12px 0; font-size: 12px; }
.file-result-form select, .file-result-form textarea { width: 100%; min-width: 0; border: 1px solid var(--line); border-radius: 5px; padding: 9px; background: var(--panel, #fff); font: inherit; color: inherit; }
.file-result-form pre { max-height: 230px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; background: #f3f6f4; border: 1px solid var(--line); padding: 10px; font: 11px/1.7 Consolas, monospace; }
.file-result-finish { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 9px; }
.file-result-outcome { padding: 10px; background: #edf7ef; color: #256148; font-size: 12px; line-height: 1.7; }
@media (max-width: 600px) { .file-results button, .file-result-form select { min-height: 42px; } .file-result-form textarea { font-size: 16px; } }
+83
View File
@@ -0,0 +1,83 @@
import { useEffect, useRef, useState } from 'react';
import { FileCheck2, FileText, LoaderCircle, RefreshCw } from 'lucide-react';
import { api } from './api';
import type { Session, FileResultView } from './types';
import './FileResultsPanel.css';
type View = { taskId: string; results: FileResultView[]; sources: { id: string; taskId: string; runId: string; reason: string; files: { path: string; sha256: string }[] }[] };
type File = { path: string; content: string; sha256: string; bytes: number };
export function FileResultsPanel({ session, busy, onSession, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task;
const [view, setView] = useState<View | null>(null), [files, setFiles] = useState<string[]>([]);
const [path, setPath] = useState(''), [file, setFile] = useState<File | null>(null), [source, setSource] = useState('');
const [reason, setReason] = useState(''), [notice, setNotice] = useState('');
const [loading, setLoading] = useState(false), [acting, setActing] = useState(false);
const scope = useRef(0), readRequest = useRef(0), viewRequest = useRef(0), flight = useRef(false);
const known = view?.sources.filter(row => row.files.some(file => file.path === path)) ?? [];
const current = view?.results.some(row => row.verification === 'current');
async function load() {
const id = scope.current, request = ++viewRequest.current; setLoading(true);
try {
const [result, inventory] = await Promise.all([api<View>('/sessions/' + session.id + '/file-results' + (path ? '?path=' + encodeURIComponent(path) : '')), api<{ files: { path: string; kind: string; bytes: number }[] }>('/projects/' + session.projectId + '/files')]);
if (scope.current !== id || viewRequest.current !== request) return;
setView(result); setFiles(inventory.files.filter(item => item.kind === 'file' && item.bytes <= 1024 * 1024).map(item => item.path));
} catch (error) { if (scope.current === id && viewRequest.current === request) setNotice(error instanceof Error ? error.message : String(error)); }
finally { if (scope.current === id && viewRequest.current === request) setLoading(false); }
}
useEffect(() => {
scope.current++; readRequest.current++; flight.current = false; setActing(false); setView(null); setPath(''); setFile(null); setSource(''); setReason(''); setNotice(''); void load();
return () => { scope.current++; readRequest.current++; };
}, [session.id, task?.id]);
useEffect(() => { void load(); }, [session.execution?.fileResults?.at(-1)?.id, session.execution?.run?.id, session.status]);
async function choose(value: string) {
setPath(value); setFile(null); setSource(''); setNotice('');
const id = scope.current, request = ++readRequest.current, viewId = ++viewRequest.current;
setLoading(false);
if (!value) return;
try { const [result, currentView] = await Promise.all([api<File>('/projects/' + session.projectId + '/file?path=' + encodeURIComponent(value)), api<View>('/sessions/' + session.id + '/file-results?path=' + encodeURIComponent(value))]);
if (scope.current === id && readRequest.current === request) { setFile(result); if (viewRequest.current === viewId) setView(currentView); }
} catch (error) { if (scope.current === id && readRequest.current === request) setNotice(error instanceof Error ? error.message : String(error)); }
}
async function save(complete = false) {
if (!task || !session.execution?.run || flight.current) return;
if (!complete && (!file || file.path !== path || !reason.trim())) return;
const id = scope.current; viewRequest.current++; setLoading(false); flight.current = true; setActing(true); setNotice('');
try {
const result = await api<View & { session: Session }>('/sessions/' + session.id + '/file-results' + (complete ? '/complete' : ''), {
taskId: task.id, runId: session.execution.run.id,
...(!complete && file ? { files: [{ path: file.path, sha256: file.sha256, ...(source ? { source_result_id: source } : {}) }], reason } : {}),
});
if (scope.current !== id) return;
setView(result); onSession(result.session); setNotice(complete ? '任务已按当前成果结束,原运行和检查记录保留。' : '当前文件已核对并登记;未新增文件改动、测试或Git提交。');
} catch (error) { if (scope.current === id) setNotice(error instanceof Error ? error.message : String(error)); }
finally { if (scope.current === id) { flight.current = false; setActing(false); } }
}
return <section className="task-record-section file-results" aria-label="当前文件成果" aria-busy={loading || acting}>
<div className="record-heading"><FileCheck2 size={15} /><h3>当前文件成果</h3><span>{view?.results.length ?? 0} 份凭据</span></div>
<p className="record-footnote">已有文件可以核对后沿用。成果、实际修改、检查与提交分别保留。</p>
<button type="button" className="text-button" disabled={loading || acting} onClick={() => void load()}>{loading ? <LoaderCircle size={13} className="spin" /> : <RefreshCw size={13} />}刷新成果状态</button>
{view?.results.map(row => <article className="file-result-row" key={row.id}>
<div><strong>{row.verification === 'current' ? '当前文件已核对' : row.verification === 'stale' ? '需要重新核对' : '原凭据需核查'}</strong><small>Task {row.taskId.slice(0, 8)} · Run {row.runId.slice(0, 8)}</small></div>
{row.files.map(item => <div key={item.path}><code>{item.path}</code><small className="file-result-sha">SHA-256 {item.sha256}</small>{item.origin && <p className="record-footnote">采用自 Task {item.origin.taskId.slice(0, 8)} · Run {item.origin.runId.slice(0, 8)}<br />原文件 SHA-256 {item.origin.sha256}</p>}
{row.verification !== 'current' && <button type="button" className="text-button" disabled={busy || acting} onClick={() => { void choose(item.path); setReason(row.reason); }}>重新打开此文件核对</button>}
</div>)}
<p>{row.reason}</p>{row.error && <p className="file-result-error">{row.error}</p>}
<button type="button" className="text-button" onClick={() => openArtifact(row.contractArtifactId)}><FileText size={13} />查看原成果凭据</button>
</article>)}
<details className="file-result-form">
<summary>核对已有文件</summary>
<label>选择项目内文件<select aria-label="成果文件" value={path} disabled={busy || acting || loading} onChange={event => void choose(event.target.value)}><option value="">选择一个文件</option>{files.map(value => <option key={value} value={value}>{value}</option>)}</select></label>
{path && <button type="button" className="text-button" disabled={busy || acting} onClick={() => void choose(path)}><RefreshCw size={13} />重新读取当前文件</button>}
{file && <><p className="record-footnote">{file.bytes.toLocaleString('zh-CN')} 字节 · 当前读取 SHA-256</p><code className="file-result-sha">{file.sha256}</code><pre aria-label="成果文件内容">{file.content.length > 12000 ? file.content.slice(0, 12000) + '\n…界面仅展开前12000字符;核对保存完整文件快照。' : file.content}</pre></>}
{!!known.length && <label>采用来源<select aria-label="成果来源" value={source} disabled={busy || acting} onChange={event => setSource(event.target.value)}><option value="">选择原任务成果</option>{known.map(row => <option key={row.id} value={row.id}>Task {row.taskId.slice(0, 8)} · {row.reason.slice(0, 60)}</option>)}</select></label>}
<label>采用原因<textarea aria-label="成果采用原因" rows={3} maxLength={600} placeholder="说明这个文件满足了当前任务的哪些要求" value={reason} disabled={busy || acting} onChange={event => setReason(event.target.value)} /></label>
<button type="button" className="button secondary" disabled={busy || acting || !file || !reason.trim() || !!known.length && !source} onClick={() => void save()}>{acting ? <LoaderCircle size={14} className="spin" /> : <FileCheck2 size={14} />}核对并采用此文件</button>
</details>
{current && task?.status !== 'completed' && <div className="file-result-finish"><p className="record-footnote">当前要求已满足时可结束。修改要求、原检查和执行计划仍需通过核对。</p><button type="button" className="button secondary" disabled={busy || acting} onClick={() => void save(true)}>按当前成果结束任务</button></div>}
{task?.delivery?.status === 'existing_verified' && <p className="file-result-outcome">结束时采用已有成果 · 无新增修改。当前有效性见逐项核对,检查与Git另列。</p>}
{notice && <p className="file-result-notice" role="status">{notice}</p>}
</section>;
}
+3 -1
View File
@@ -13,6 +13,7 @@ import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
import { EnvironmentPanel } from './EnvironmentPanel';
import { PreviewPanel } from './PreviewPanel';
import { FileResultsPanel } from './FileResultsPanel';
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');
@@ -21,7 +22,7 @@ stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保
stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续';
stopReasons.diagnostic_answered = '诊断答复已完成;原任务的目标与交付状态保持';
stopReasons.verification_incomplete = '答复已收到,当前任务的工程检查尚未通过';
stopReasons.delivery_incomplete = '答复已收到,要求的文件尚无已应用记录';
stopReasons.delivery_incomplete = '答复已收到,当前文件成果或要求的修改仍需核对';
const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中';
export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate, onOpenPreview }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; onOpenPreview?:()=>void; onWorkspaceRefresh: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void>; onWorkspaceNavigate: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void> }) {
@@ -94,6 +95,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
{!!task.instructions.length && <details className="task-instructions"><summary>追加要求 · {task.instructions.length}</summary>{task.instructions.map(instruction => <p key={instruction.id}><small>{instruction.source && instruction.source !== 'user' ? '系统操作 · ' + instruction.source : '用户要求'}</small><br />{instruction.content}</p>)}</details>}
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
</section>
{task && <FileResultsPanel session={session} busy={busy} onSession={onSession} openArtifact={openArtifact} />}
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <TaskCheckpointPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{execution?.progress.requiresVerification.length ? <section className="verification-note" role="status"><ShieldQuestion size={17} /><div><strong>{execution.progress.requiresVerification.length} 项结果需要核对</strong><p>这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。</p>{execution.progress.requiresVerification.map(tool => <code key={tool.id}>{tool.tool} · {tool.id.slice(0, 8)}</code>)}</div></section> : null}
+5 -5
View File
@@ -5,16 +5,16 @@ import { Modal, Status } from './components';
import type { Session, TaskPlanReply, TaskPlanStep, TaskPlanView } from './types';
import './TaskPlanPanel.css';
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '读取工程', changes: '源码改动', checks: '工程检查', browser: '页面验收' };
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '读取工程', changes: '源码改动', results: '当前文件成果', checks: '工程检查', browser: '页面验收' };
const readTools = { inspect_project: '识别工程', read_file: '读取文件', list_files: '文件清单', search_files: '搜索文件', index_project: '工程索引', query_code: '定位符号', read_research_evidence: 'REA原结果', inspect_engine_checks: '引擎核验', read_browser_result: '原页面记录' };
const browserActions = { fill: '填写', select: '选择', click: '点击', assert_text: '文本断言', assert_count: '数量断言', assert_visible: '可见断言' };
const cleanStep = (step: TaskPlanStep): TaskPlanStep => ({ key: step.key, title: step.title, criterion: step.criterion, kind: step.kind, depends_on: [...step.depends_on],
...(step.kind === 'analysis' ? { tools: [...(step.tools ?? [])] } : step.kind === 'changes' ? { paths: (step.paths ?? []).map(value => value.trim()).filter(Boolean) }
...(step.kind === 'analysis' ? { tools: [...(step.tools ?? [])] } : ['changes', 'results'].includes(step.kind) ? { paths: (step.paths ?? []).map(value => value.trim()).filter(Boolean) }
: step.kind === 'checks' ? { checks: (step.checks ?? []).map(value => value.trim()).filter(Boolean) } : { viewport_width: step.viewport_width, actions: [...(step.actions ?? [])] }) });
const freshStep = (kind: TaskPlanStep['kind'] = 'analysis'): TaskPlanStep => ({ key: 'step_' + crypto.randomUUID().slice(0, 8), title: kinds[kind], criterion: '', kind, depends_on: [],
...(kind === 'analysis' ? { tools: ['inspect_project'] } : kind === 'changes' ? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] }) });
...(kind === 'analysis' ? { tools: ['inspect_project'] } : ['changes', 'results'].includes(kind) ? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] }) });
const scopeText = (step: TaskPlanStep) => step.kind === 'analysis' ? (step.tools ?? []).map(tool => readTools[tool as keyof typeof readTools] ?? tool).join(' / ')
: step.kind === 'changes' ? step.paths?.join('、') : step.kind === 'checks' ? step.checks?.join(' / ')
: ['changes', 'results'].includes(step.kind) ? step.paths?.join('、') : step.kind === 'checks' ? step.checks?.join(' / ')
: `${step.viewport_width}px · ${(step.actions ?? []).map(action => browserActions[action as keyof typeof browserActions]).join(' / ')}`;
export function TaskPlanPanel({ session, busy, onSession, onError, openArtifact }: {
@@ -116,7 +116,7 @@ export function TaskPlanPanel({ session, busy, onSession, onError, openArtifact
const next = freshStep(event.target.value as TaskPlanStep['kind']); setDraft(steps => steps.map((value, at) => at === index ? { ...next, key: value.key, title: value.title, criterion: value.criterion, depends_on: value.depends_on } : value));
}}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
{step.kind === 'analysis' && <div className="plan-option-list"><span>可核验的读取结果(任一)</span>{Object.entries(readTools).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.tools?.includes(key) ?? false} onChange={event => update(index, { tools: event.target.checked ? [...(step.tools ?? []), key] : step.tools?.filter(tool => tool !== key) })} />{label}</label>)}</div>}
{step.kind === 'changes' && <label>改动文件(每行一项)<textarea aria-label={`步骤${index + 1}文件范围`} rows={3} value={step.paths?.join('\n') ?? ''} placeholder="src/main.tsx" onChange={event => update(index, { paths: event.target.value.split('\n') })} /></label>}
{['changes', 'results'].includes(step.kind) && <label>{step.kind === 'results' ? '成果文件' : '改动文件'}(每行一项)<textarea aria-label={`步骤${index + 1}文件范围`} rows={3} value={step.paths?.join('\n') ?? ''} placeholder="src/main.tsx" onChange={event => update(index, { paths: event.target.value.split('\n') })} /></label>}
{step.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label={`步骤${index + 1}检查范围`} value={step.checks?.join(',') ?? ''} placeholder="test,build 或 python:test,python:compile" onChange={event => update(index, { checks: event.target.value.split(',') })} /></label>}
{step.kind === 'browser' && <><label>页面宽度<select aria-label={`步骤${index + 1}页面宽度`} value={step.viewport_width} onChange={event => update(index, { viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option>{![1280, 390].includes(step.viewport_width ?? 0) && <option value={step.viewport_width}>{step.viewport_width}px</option>}</select></label>
<div className="plan-option-list"><span>必须实际完成的操作</span>{Object.entries(browserActions).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.actions?.includes(key) ?? false} onChange={event => update(index, { actions: event.target.checked ? [...(step.actions ?? []), key] : step.actions?.filter(action => action !== key) })} />{label}</label>)}</div></>}
+2 -1
View File
@@ -12,7 +12,8 @@ export interface MobileTask extends MobileBrief {
browserObservations?:{id:string;tabId:string;url:string;title:string;createdAt:string;revision:string;scope:{complete:boolean};screenshotSha256:string}[];
inputAttachments?: import('./types').InputAttachment[];
budgetPause?: import('./types').BudgetPause|null;
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string } } | null;
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string }; delivery?: { status: string; paths: string[]; checks: string } } | null;
fileResults?: { id: string; taskId: string; runId: string; verification: string; reason: string; contractSha256: string; files: { path: string; sha256: string; bytes: number; origin: { taskId: string; runId: string; sha256: string } | null }[] }[];
run: { id: string; status: string; steps: number; toolCalls: number; stopReason: string | null; usage: MobileUsage } | null;
progress: { total: number; completed: number; unknown: { id: string; tool: string; state: string; runId: string }[] };
events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number;
+2
View File
@@ -5,6 +5,7 @@ import { ArrowLeft, ChevronRight, ClipboardCheck, FileDiff, Folder, Link2, Refre
import type { CompanionDevice, MobileBrief, MobileTask } from '../companion-types';
import { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
import { MobileInputImage } from './MobileInputImage';
import './file-results.css';
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
@@ -124,6 +125,7 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
{!!selectedTask.progress.unknown.length && <div className="mobile-unknown"><strong>{selectedTask.progress.unknown.length} 项工具结果需要核对</strong><p>请在电脑核对原输入和实际结果。刷新、重连和手机审批均不会自动重新执行。</p>{selectedTask.progress.unknown.map(item => <code key={item.id}>{item.tool} · {stateLabel(item.state)}</code>)}</div>}
{selectedTask.browserObservations?.slice(-1).map(observation=><MobileBrowserObservation key={observation.id} sessionId={selectedTask.id} observation={observation} onError={cause=>{if(cause instanceof MobileError&&[401,403].includes(cause.status))revoke(cause.message);else setError(cause instanceof Error?cause.message:'原网页截图读取失败。');}}/>)}
{!!selectedTask.approvals.length && <section className="mobile-approvals"><h2><ShieldCheck size={18} />等待你的确认</h2>{selectedTask.approvals.map(approval => <article key={approval.id}><span>{approval.shell}</span><pre>{approval.command}</pre><p>{approval.reason}</p>{!me.device.permissions.approve ? <p className="mobile-muted">此设备仅可观察,请在电脑审批。</p> : !approval.actionable ? <p className="mobile-muted">原审批已失效,请在电脑核对。</p> : <div className="mobile-action-pair"><button disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: false })}>拒绝</button><button className="mobile-primary" disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: true })}>核对并批准</button></div>}</article>)}</section>}
{!!selectedTask.fileResults?.length && <section className="mobile-file-results" aria-label="当前文件成果"><h2>当前文件成果</h2>{selectedTask.fileResults.map(result => <article key={result.id}><strong>{result.verification === 'current' ? '当前文件已核对' : '文件或要求已变化,请在电脑重新核对'}</strong><p>Task {result.taskId.slice(0, 8)} · Run {result.runId.slice(0, 8)}</p>{result.files.map(file => <p key={file.path}><strong>{file.path}</strong><br /><code>SHA-256 {file.sha256}</code>{file.origin && <><br />来源 Task {file.origin.taskId.slice(0, 8)} · Run {file.origin.runId.slice(0, 8)}<br /><code>原 SHA-256 {file.origin.sha256}</code></>}</p>)}<p>{result.reason}</p><details><summary>原成果凭据 SHA-256</summary><code>{result.contractSha256}</code></details></article>)}<p className="mobile-muted">已有成果与新增修改分开记录;测试、差异和Git结果见各自原记录。</p></section>}
<nav className="mobile-tabs" aria-label="任务内容">{[['progress', '执行进展'], ['changes', '文件差异'], ['checks', '检查与报告']].map(([key, label]) => <button key={key} aria-current={tab === key ? 'page' : undefined} onClick={() => { setTab(key); setDocument(null); }}>{label}{key === 'changes' && !!selectedTask.changes.length && <span>{selectedTask.changes.length}</span>}</button>)}</nav>
{tab === 'progress' && <section className="mobile-progress"><div className="mobile-section-heading"><h2>原执行记录</h2><span>{selectedTask.progress.completed} / {selectedTask.progress.total} 工具完成</span></div><ol>{selectedTask.events.map(item => <li key={item.id}><div><strong>{item.label || '执行事件'}</strong><span className={'mobile-state state-' + item.phase}>{stateLabel(item.phase)}</span></div>{item.stream && item.stream.status !== "completed" && <div className="mobile-stream"><strong>{item.stream.status === "receiving" ? "正在接收模型输出" : "模型输出未完成"}</strong><span>{item.stream.textCharacters ?? 0} 字符 · 片段不执行工具</span>{item.stream.textPreview && <pre>{item.stream.textPreview}</pre>}</div>}{item.output && <details><summary>查看原输出片段{item.exitCode !== undefined ? ' · 退出码 ' + item.exitCode : ''}</summary><pre>{item.output}</pre></details>}</li>)}</ol>{!selectedTask.events.length && <p className="mobile-muted">尚无工具执行记录。</p>}{selectedTask.messages.map(message => <article className="mobile-message" key={message.id}><span>{message.role === 'assistant' ? '代理回复' : '系统记录'} · {time(message.createdAt)}</span><p>{message.content}</p></article>)}<p className="mobile-muted">手机显示最近60条执行记录和8条回复;完整记录保留在电脑原会话。</p></section>}
{tab === 'changes' && <section className="mobile-changes"><div className="mobile-section-heading"><h2>当前任务的改动</h2><span>{selectedTask.changes.length} 个文件</span></div>{!selectedTask.changes.length && <p className="mobile-muted">尚未提出文件改动。</p>}{selectedTask.changes.map(change => <button key={change.id} className="mobile-file-row" disabled={!!busy || !fresh} onClick={() => void openDiff(change)}><FileDiff size={19} /><div><strong>{change.path}</strong><span>{stateLabel(change.status)} · <b>+{change.additions}</b> / −{change.deletions}</span></div><ChevronRight size={17} /></button>)}<p className="mobile-muted">手机可查看原差异;应用、恢复和 Git 提交在电脑审查。</p></section>}
+6
View File
@@ -0,0 +1,6 @@
.mobile-file-results { padding: 18px; border-block: 1px solid #d8e2dc; background: #f5f8f6; }
.mobile-file-results h2 { font-size: 16px; margin: 0 0 12px; }
.mobile-file-results article { padding: 12px 0; border-bottom: 1px solid #d8e2dc; font-size: 13px; line-height: 1.65; }
.mobile-file-results p { margin: 8px 0; }
.mobile-file-results code { font-size: 11px; overflow-wrap: anywhere; word-break: break-word; }
.mobile-file-results details summary { min-height: 42px; display: flex; align-items: center; cursor: pointer; }
+6 -1
View File
@@ -165,6 +165,11 @@ export interface ContextHistoryGroup {
export interface ContextHistory { planId: string; groups: ContextHistoryGroup[]; offset: number; totalGroups: number; truncated: boolean }
export interface Task { id: string; goal: string; status: string; instructions: { id: string; content: string; createdAt: string; source?: string }[]; usage: Usage; budget: { maxTokens: number }; verification: { status: string; checkJobId: string | null }; origin: string; workspaceIdentity?: WorkspaceIdentity }
export interface Task { contract?: { schemaVersion: number; goal: string; checks: string; inheritedFromTaskId?: string }; delivery?: { status: string; paths: string[]; at: string; checks: string } }
export interface FileResultView {
id: string; taskId: string; runId: string; source: string; reason: string; createdAt: string; verification: 'current' | 'stale' | 'invalid'; error: string | null;
contractArtifactId: string; contractSha256: string; files: { path: string; sha256: string; bytes: number; origin: { taskId: string; runId: string; resultId: string; sha256: string } | null }[];
}
export interface ExecutionSnapshot { fileResults?: Omit<FileResultView, 'verification' | 'error'>[] }
export interface Artifact { id: string; taskId: string | null; runId: string | null; kind: string; mediaType: string; sha256: string; bytes: number; createdAt: string; status: string }
export interface ArtifactPreview extends Artifact { content: string; offset: number; totalCharacters: number; truncated: boolean }
export interface ProjectMemorySource { kind: 'project' | 'file' | 'artifact' | 'session' | 'task' | 'run'; id?: string; path?: string; sha256?: string; sourceFingerprint: string; label?: string; artifactKind?: string }
@@ -200,7 +205,7 @@ export interface ChangeSet {
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: string }[];
}
export interface TaskPlanStep {
key: string; title: string; criterion: string; kind: 'analysis' | 'changes' | 'checks' | 'browser'; depends_on: string[];
key: string; title: string; criterion: string; kind: 'analysis' | 'changes' | 'results' | 'checks' | 'browser'; depends_on: string[];
tools?: string[]; paths?: string[]; checks?: string[]; viewport_width?: number; actions?: string[];
}
export interface TaskPlanRecord { id: string; taskId: string; runId: string; revision: number; parentPlanId: string | null; steps: TaskPlanStep[]; contractArtifactId: string; contractSha256: string }
+8
View File
@@ -1,5 +1,6 @@
import { approvalBinding } from '../../shared/contracts/companion.mjs';
import { approvalKind } from '../../shared/approval-presentation.mjs';
import { FileResults } from '../tasks/file-results.mjs';
export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])]));
export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']);
@@ -32,6 +33,13 @@ export function mobileSession(store, runtime, session, redact = String) {
reports: [...store.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && reportKinds.has(value.kind))
.slice(-10).map(value => pick(value, ['id', 'kind', 'sha256', 'bytes', 'createdAt', 'taskId', 'runId'])),
};
if (task?.delivery) result.task.delivery = pick(task.delivery, ['status', 'paths', 'at', 'checks']);
if ([...store.core.file_result.values()].some(row => row.sessionId === session.id && row.taskId === session.taskId)) {
result.fileResults = new FileResults(store).inspect(session).results.slice(0, 8).map(row => ({
...pick(row, ['id', 'taskId', 'runId', 'createdAt', 'verification', 'contractSha256']), reason: row.reason,
files: row.files.map(file => ({ ...pick(file, ['path', 'sha256', 'bytes']), origin: file.origin ? pick(file.origin, ['taskId', 'runId', 'sha256']) : null })),
}));
}
// Only this explicit projection crosses the remote boundary. Never expose
// providerMessages, model configuration, tool input, host paths or full exports.
const clean = value => typeof value === 'string' ? redact(value) : Array.isArray(value) ? value.map(clean)
+1
View File
@@ -101,6 +101,7 @@ export function clearReadStreak(task) {
task.readProgress.sessionInspection = null;
task.readProgress.observations = [];
task.readProgress.checkPause = false;
task.readProgress.resultRepeats = 0;
}
export function recordFileRead(task, result, invocationId, runId) {
+27 -2
View File
@@ -9,8 +9,11 @@ import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { verifyPythonCheckEvidence } from './python-runtime.mjs';
import { currentBrowserVerification, verifyBrowserJob } from './browser/browser-manager.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
import { FileResults } from './tasks/file-results.mjs';
import { taskContract } from '../shared/contracts/task-control.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
existing_verified: '当前成果已核对,无新增修改', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
@@ -48,6 +51,8 @@ export class DeliveryReporter {
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('生成报告期间任务已切换,请重新生成。'), { status: 409 });
if (job && (job.sessionId !== session.id || job.taskId !== taskId)) throw new Error('提交记录不属于当前任务。');
const changes = session.changes.filter(change => change.taskId === taskId);
const resultManager = new FileResults(this.store), fileResults = resultManager.inspect(session).results, fileDelivery = resultManager.completion(session), contract = taskContract(task);
const hasFileScope = contract.kind === 'file' || fileResults.length > 0;
const jobs = [...this.store.core.delivery_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
const check = verifiedCheck(this.store, session, inspection);
const requiresVerification = [...this.store.core.tool.values()].filter(value => value.taskId === taskId && value.requiresVerification)
@@ -119,13 +124,22 @@ export class DeliveryReporter {
const status = requiresVerification.length || unresolved.length ? 'needs_verification'
: ['running', 'awaiting_approval', 'stopping'].includes(session.status) ? 'in_progress'
: deliveryReview || changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review'
: taskPlan.configured && !taskPlan.all_verified ? 'needs_plan_verification' : !check ? 'needs_checks' : browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: commits.length ? 'verified_committed' : 'verified_uncommitted';
: taskPlan.configured && !taskPlan.all_verified ? 'needs_plan_verification'
: hasFileScope && !fileDelivery.satisfied ? 'needs_results'
: !check && !(hasFileScope && fileDelivery.satisfied && (contract.checks === 'skip' || contract.checks === 'unspecified' && task.verification.status === 'not_configured')) ? 'needs_checks'
: browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: hasFileScope && !fileDelivery.newChanges ? 'existing_verified' : hasFileScope && contract.checks === 'skip' ? 'files_delivered'
: commits.length ? 'verified_committed' : 'verified_uncommitted';
const report = {
schemaVersion: 1, kind: 'engineering-delivery', generatedAt: new Date().toISOString(), status, statusLabel: labels[status],
project: { id: project.id, name: project.name, root: project.root }, workspace: projectWorkspaceIdentity(project),
task: { id: task.id, goal: task.goal, status: task.status, instructions: task.instructions, acceptance: task.acceptance ?? [],
contract, delivery: task.delivery ?? null,
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: 'not_recorded', note: '源码和检查证据不代替业务需求验收。' },
fileResults, fileDelivery,
checkPolicy: contract.checks === 'skip' ? 'not_requested' : contract.checks,
gitOutcome: { status: !fileDelivery.newChanges && hasFileScope ? 'no_new_changes' : commits.length ? 'committed' : 'uncommitted',
note: !fileDelivery.newChanges && hasFileScope ? '本任务无新增修改;未创建提交,已有用户修改保持原归属。' : '仅本任务实际应用的文件可进入Git交付预览。' },
source: { fingerprint: inspection.sourceFingerprint, scope: inspection.scope, gitHead: inspection.git.head, branch: inspection.git.branch },
runs: [...this.store.core.run.values()].filter(value => value.taskId === taskId).map(value => ({ id: value.id, resumeOf: value.resumeOf,
engine: value.engine, status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason,
@@ -172,6 +186,17 @@ export function renderDeliveryMarkdown(report) {
'分支:' + (report.source.branch ?? '未记录'), '', report.task.note, '', '## 改动', '',
'| 文件 | 状态 | SHA256 |', '| --- | --- | --- |'];
for (const change of report.changes) lines.push('| ' + [change.path, change.status, change.sha256].map(escapeCell).join(' | ') + ' |');
if (report.fileResults?.length) {
lines.push('', '## 当前已有成果', '', '成果核对保存当前文件与采用原因;不代表本任务新写入、测试通过或业务验收通过。', '',
'| 文件 | 当前核对 | 原文件 SHA256 | 来源 Task / Run | 凭据 |', '| --- | --- | --- | --- | --- |');
for (const result of report.fileResults) {
for (const file of result.files) lines.push('| ' + [file.path, result.verification, file.sha256,
file.origin ? file.origin.taskId + ' / ' + file.origin.runId + ' · 原SHA ' + file.origin.sha256 : '本次读取已有文件', result.contractArtifactId].map(escapeCell).join(' | ') + ' |');
lines.push('', '采用原因:' + result.reason, ...(result.error ? ['', result.error] : []));
}
}
if (report.gitOutcome) lines.push('', report.gitOutcome.note);
if (report.checkPolicy === 'not_requested') lines.push('', '测试约定:按用户要求未自动测试;不记作测试通过。');
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
+144
View File
@@ -0,0 +1,144 @@
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { readText, readLines, safePath } from '../../server/files.mjs';
import { filePage } from '../context/read-budget.mjs';
import { planHash, planError } from '../../shared/contracts/task-plans.mjs';
import { fileResultInput, fileResultRequirements, fileResultRequirementsHash, changeRequirement, requestedFilePaths } from '../../shared/contracts/file-results.mjs';
const contract = ({ contractArtifactId, contractSha256, ...value }) => value;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
export class FileResults {
constructor(store) { this.store = store; }
records(session) { return [...this.store.core.file_result.values()].filter(row => row.sessionId === session.id && row.taskId === session.taskId); }
artifact(session, id, kind, taskId, runId) {
const row = this.store.owned('artifact', id, session.id);
if (row.kind !== kind || row.taskId !== taskId || row.runId !== runId) throw planError('成果原工件的Task/Run或类别不一致。');
return { row, bytes: this.store.artifactStore.readBytes(row) };
}
original(session, record, depth = 0) {
if (depth > 16) throw planError('成果采用链超过16层,请重新核对独立成果范围。');
const run = this.store.owned('run', record.runId, session.id);
if (run.taskId !== record.taskId) throw planError('成果所属运行已不一致。');
const { row, bytes } = this.artifact(session, record.contractArtifactId, 'file-result', record.taskId, record.runId);
if (row.sha256 !== record.contractSha256 || !same(JSON.parse(bytes), contract(record))) throw planError('成果记录与封存原凭据不一致。');
for (const file of record.files) {
const source = this.artifact(session, file.snapshotArtifactId, 'file-result-source', record.taskId, record.runId);
if (source.row.sha256 !== file.sha256 || source.row.bytes !== file.bytes) throw planError('成果原文件快照不一致:' + file.path);
for (const read of file.reads) {
const invocation = this.store.owned('tool', read.invocationId, session.id);
if (invocation.taskId !== record.taskId || invocation.runId !== read.runId || invocation.tool !== 'read_file' || invocation.state !== 'completed'
|| invocation.requiresVerification || invocation.resultArtifactId !== read.artifactId || invocation.argsSha256 !== read.argsSha256) throw planError('成果原读取调用不一致:' + file.path);
const artifact = this.artifact(session, read.artifactId, 'tool-result', record.taskId, read.runId);
if (artifact.row.sha256 !== read.artifactSha256) throw planError('成果原读取工件已变化:' + file.path);
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(value => value.id === read.callId);
if (!call || call.function.name !== 'read_file' || planHash(call.function.arguments) !== read.argsSha256) throw planError('成果原读取参数已变化:' + file.path);
}
if (file.origin) {
const origin = this.original(session, this.store.owned('file_result', file.origin.resultId, session.id), depth + 1);
if (origin.taskId !== file.origin.taskId || origin.runId !== file.origin.runId || origin.contractSha256 !== file.origin.contractSha256
|| !origin.files.some(old => old.path === file.path && old.sha256 === file.origin.sha256)) throw planError('成果来源与原文件不一致:' + file.path);
}
}
return record;
}
verify(session, id, { current = true } = {}) {
const record = this.original(session, this.store.owned('file_result', id, session.id));
if (current) {
if (record.taskId !== session.taskId || record.requirementsSha256 !== fileResultRequirementsHash(this.store.owned('task', session.taskId, session.id))) throw planError('任务要求已变化,请按当前要求重新核对成果。', 'stale');
for (const file of record.files) {
try { if (readText(this.store.project(session.projectId), file.path).sha256 !== file.sha256) throw new Error('SHA256不同'); }
catch (error) { throw planError('当前文件已变化或无法读取:' + file.path + '。请重新打开并核对。', 'stale'); }
}
}
return record;
}
reads(session, file, current) {
const project = this.store.project(session.projectId), spans = [], receipts = [];
const lineOffsets = [0]; for (let i = 0; i < current.content.length; i++) if (current.content[i] === '\n') lineOffsets.push(i + 1);
for (const callId of file.read_call_ids) {
const row = [...this.store.core.tool.values()].find(item => item.sessionId === session.id && item.taskId === session.taskId && item.callId === callId);
if (!row || row.tool !== 'read_file' || row.state !== 'completed' || row.requiresVerification) throw planError('需要本Task已完成的read_file原调用:' + callId);
const call = session.providerMessages.flatMap(message => message.tool_calls ?? []).find(item => item.id === callId);
if (!call || call.function.name !== row.tool || planHash(call.function.arguments) !== row.argsSha256) throw planError('原文件读取参数与账本不一致。');
const args = JSON.parse(call.function.arguments);
if (args.path !== file.path) throw planError('读取路径与采用路径不一致。');
const { row: artifact, bytes } = this.artifact(session, row.resultArtifactId, 'tool-result', row.taskId, row.runId);
const result = JSON.parse(bytes), { tool_invocation_id, ...page } = result;
if (result.sha256 !== file.sha256 || !same(page, filePage(readLines(project, args), args, { callId, maximumMessageBytes: result.maximum_message_bytes }))) throw planError('读取后文件或原分页结果已变化:' + file.path, 'stale');
const start = lineOffsets[result.range_start_line - 1];
if (start === undefined) throw planError('读取行范围无效。');
let end = start + result.next_offset;
if (result.next_offset === result.total_characters && result.range_end_line < result.total_lines) end++;
spans.push([start + result.offset, end]);
receipts.push({ invocationId: row.id, callId, runId: row.runId, artifactId: artifact.id, artifactSha256: artifact.sha256, argsSha256: row.argsSha256 });
}
let covered = 0;
for (const [start, end] of spans.sort((a, b) => a[0] - b[0])) { if (start > covered) throw planError('文件尚未完整读取:' + file.path + '。请继续读取剩余行或next_offset。'); covered = Math.max(covered, end); }
if (covered < current.content.length) throw planError('文件尚未完整读取:' + file.path + '。请继续读取剩余行或next_offset。');
return receipts;
}
record(session, input, { source = 'agent' } = {}) {
const args = fileResultInput(input, { source }), task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
if (!['agent', 'user'].includes(source) || run.taskId !== task.id || run.purpose === 'diagnostic' && source !== 'user') throw planError('诊断运行不能登记或替代原任务成果。');
const project = this.store.project(session.projectId), prepared = [];
for (const file of args.files) {
const current = readText(project, file.path);
if (current.sha256 !== file.sha256) throw planError('文件已在核对后变化:' + file.path + '。请重新打开文件。', 'stale');
let origin = null;
if (file.source_result_id) {
const original = this.verify(session, file.source_result_id, { current: false });
if (original.taskId === task.id) throw planError('同一Task请复用原成果ID或重新核对当前文件,不重复采用自身成果。');
const old = original.files.find(item => item.path === file.path);
if (!old) throw planError('原成果不包含所选文件:' + file.path);
origin = { resultId: original.id, taskId: original.taskId, runId: original.runId, sha256: old.sha256, contractArtifactId: original.contractArtifactId, contractSha256: original.contractSha256 };
} else {
const previous = [...this.store.core.file_result.values()].findLast(item => item.sessionId === session.id && item.taskId !== task.id && item.files.some(old => old.path === file.path));
if (previous) throw planError('已有旧任务成果,请显式选择原成果ID后采用:' + previous.id);
}
const reads = source === 'agent' ? this.reads(session, file, current) : [];
const bytes = fs.readFileSync(safePath(project, file.path));
if (planHash(bytes) !== file.sha256) throw planError('保存凭据期间文件已变化:' + file.path, 'stale');
prepared.push({ file, current, bytes, reads, origin });
}
const requirements = fileResultRequirements(task), requirementsSha256 = fileResultRequirementsHash(task);
const fingerprint = planHash({ requirementsSha256, files: prepared.map(({ file, origin }) => ({ path: file.path, sha256: file.sha256, origin: origin?.resultId ?? null })).sort((a,b) => a.path.localeCompare(b.path)) });
const previous = this.records(session).find(item => item.fingerprint === fingerprint);
if (previous) { this.verify(session, previous.id); return { status: 'completed', result_id: previous.id, reused: true, files: previous.files, message: '返回原成果凭据,未改写文件、重放工具或新增进展。' }; }
if (this.records(session).length >= 64) throw planError('本Task已保存64份成果,请缩小任务范围。');
const files = prepared.map(({ file, current, bytes, reads, origin }) => {
const snapshot = this.store.artifactStore.write(session, run, bytes, { kind: 'file-result-source', mediaType: 'text/plain' }); this.store.core.artifact.set(snapshot.id, snapshot);
return { path: file.path, sha256: file.sha256, bytes: current.bytes, snapshotArtifactId: snapshot.id, reads, origin };
});
const row = { schemaVersion: 1, kind: 'file-result', id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
createdAt: new Date().toISOString(), source, reason: args.reason, requirements, requirementsSha256, fingerprint, files, status: 'recorded' };
const receipt = this.store.artifactStore.write(session, run, row, { kind: 'file-result' }); this.store.core.artifact.set(receipt.id, receipt);
row.contractArtifactId = receipt.id; row.contractSha256 = receipt.sha256;
this.store.putRecord('file_result', session, row, 'file_result.recorded');
return { status: 'completed', result_id: row.id, reused: false, files: row.files, message: '已核对当前文件并封存已有成果;未创建文件改动、测试或Git提交。' };
}
inspect(session, { path = null } = {}) {
const results = this.records(session).slice(-64).reverse().map(row => {
try { this.verify(session, row.id); return { ...row, verification: 'current', error: null }; }
catch (error) { return { ...row, verification: error.code === 'stale' ? 'stale' : 'invalid', error: error.message }; }
});
const sources = [...this.store.core.file_result.values()].filter(row => row.sessionId === session.id && row.taskId !== session.taskId && (!path || row.files.some(file => file.path === path))).slice(-12).reverse()
.map(row => ({ id: row.id, taskId: row.taskId, runId: row.runId, reason: row.reason, files: row.files.map(({ path, sha256 }) => ({ path, sha256 })) }));
return { taskId: session.taskId, results, sources };
}
completion(session) {
const task = this.store.owned('task', session.taskId, session.id), { results } = this.inspect(session);
const latest = new Map();
for (const change of session.changes.filter(item => item.taskId === task.id && item.status === 'applied')) latest.set(change.path, change);
const applied = [...latest.values()].filter(change => { try { return readText(this.store.project(session.projectId), change.path).sha256 === change.sha256 && change.baseSha256 !== change.sha256; } catch { return false; } });
const demand = changeRequirement(task), newApplied = applied.filter(change => !demand.after || change.createdAt >= demand.after && change.appliedAt >= demand.after);
const changed = newApplied.length > 0 && demand.paths.every(path => newApplied.some(change => change.path === path));
const current = results.filter(row => row.verification === 'current');
const paths = [...new Set([...applied.map(row => row.path), ...current.flatMap(row => row.files.map(file => file.path))])];
const targets = requestedFilePaths([task.contract?.goal ?? task.goal, ...(task.instructions ?? []).filter(item => item.source !== 'review-action').map(item => item.content)].join('\n'));
const missingPaths = targets.filter(path => !paths.includes(path));
return { satisfied: !missingPaths.length && (!demand.required || changed) && (applied.length > 0 || current.length > 0), requiresChange: demand.required && !changed, missingPaths,
status: applied.length ? 'files_applied' : 'existing_verified', paths,
resultIds: current.map(row => row.id), newChanges: applied.length, stale: results.filter(row => row.verification !== 'current').map(row => ({ id: row.id, error: row.error })) };
}
}
+10 -3
View File
@@ -4,6 +4,7 @@ import { safePath } from '../../server/files.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { ChangeSetManager } from '../workspaces/change-sets.mjs';
import { FileResults } from './file-results.mjs';
import { CheckRunner, parseTestEvidence } from '../check-runner.mjs';
import { verifyPythonCheckEvidence } from '../python-runtime.mjs';
import { browserPlanFor, verifyBrowserJob } from '../browser/browser-manager.mjs';
@@ -85,7 +86,7 @@ export class TaskPlanManager {
return inspection;
}
async evidence(session, step, id, cache = {}) {
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
const kind = { analysis: 'tool', changes: 'change_set', results: 'file_result', checks: 'check_job', browser: 'browser_job' }[step.kind];
const record = this.store.owned(kind, id, session.id);
if (record.taskId !== session.taskId || record.requiresVerification) throw planError('原证据不属于当前Task或结果仍待核对。');
const run = this.store.owned('run', record.runId, session.id);
@@ -100,6 +101,12 @@ export class TaskPlanManager {
return { kind, id: record.id, runId: record.runId, scope: 'historical_read_operation', tool: record.tool, callId: record.callId,
argsSha256: record.argsSha256, artifacts: [identity(artifact)] };
}
if (step.kind === 'results') {
const result = new FileResults(this.store).verify(session, record.id);
if (!step.paths.every(path => result.files.some(file => file.path === path))) throw planError('成果凭据尚未覆盖计划指定文件。');
return { kind, id: result.id, runId: result.runId, scope: 'current_existing_files', files: result.files.filter(file => step.paths.includes(file.path)).map(({ path, sha256, origin }) => ({ path, sha256, origin })),
artifacts: [identity(this.store.owned('artifact', result.contractArtifactId, session.id))] };
}
if (step.kind === 'changes') {
if (record.status !== 'completed' || record.direction !== 'apply' || !record.attemptedAt
|| !step.paths.every(file => record.files.some(value => value.path === file && value.writeAttempted && value.state === 'after'))) throw planError('步骤文件必须来自本Task已审查应用的完整变更集。');
@@ -147,11 +154,11 @@ export class TaskPlanManager {
}
proofs(session, plan) { return [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && value.planId === plan.id); }
candidates(session, step) {
const kind = { analysis: 'tool', changes: 'change_set', checks: 'check_job', browser: 'browser_job' }[step.kind];
const kind = { analysis: 'tool', changes: 'change_set', results: 'file_result', checks: 'check_job', browser: 'browser_job' }[step.kind];
return [...this.store.core[kind].values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId)
.filter(value => step.kind !== 'analysis' || step.tools.includes(value.tool)).filter(value => step.kind !== 'browser' || this.store.core.browser_plan.get(value.planId)?.viewport.width === step.viewport_width)
.slice(-12).reverse().map(value => ({ id: value.id, status: value.stale ? 'stale' : value.status ?? value.state,
label: step.kind === 'analysis' ? value.tool : step.kind === 'changes' ? value.files.map(file => file.path).join('、')
label: step.kind === 'analysis' ? value.tool : ['changes', 'results'].includes(step.kind) ? value.files.map(file => file.path).join('、')
: step.kind === 'checks' ? value.results.map(result => result.name).join(' / ') : step.viewport_width + 'px · ' + (value.assertions?.passed ?? 0) + '项断言',
runId: value.runId }));
}
+14 -1
View File
@@ -348,7 +348,7 @@ return async (request, response) => {
}
}
if (method === 'POST' && workerForProject(store, session.projectId)
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|file-results|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
if (method === 'GET' && action === 'evaluations') return json(response,runtime.evaluationManager().view(session));
if (method === 'POST' && action === 'evaluations') {
const batch=await runtime.evaluationManager().plan(session,await body(request));
@@ -489,6 +489,19 @@ return async (request, response) => {
if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('核对期间任务已变化,请刷新当前计划。'), { status: 409 });
return json(response, plan);
}
if (method === 'GET' && action === 'file-results') return json(response, runtime.fileResults().inspect(session, { path: url.searchParams.get('path') }));
if (method === 'POST' && ['file-results', 'file-results/complete'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('任务或运行已切换,未修改其他任务成果。'), { status: 409 });
if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('工程仍有活动,请等待原操作结束后核对。'), { status: 409 });
await verifyWorkspaceProject(store, store.project(session.projectId));
if (taskId !== session.taskId || runId !== session.runId || runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('核对期间任务或工程活动已变化。'), { status: 409 });
if (action === 'file-results/complete') {
if (Object.keys(input).length) throw Object.assign(new Error('结束任务不接受额外完成结论。'), { status: 400 });
await runtime.completeFileResults(session);
} else runtime.fileResults().record(session, input, { source: 'user' });
return json(response, { session: store.publicSession(session), ...runtime.fileResults().inspect(session) });
}
if (method === 'POST' && ['task-plans', 'task-proofs'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (typeof taskId !== 'string' || typeof runId !== 'string' || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('提交的任务或运行已变化,未修改其他任务计划。'), { status: 409 });
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.23.0';
export const APP_VERSION = '1.24.0';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+1
View File
@@ -68,6 +68,7 @@ export function projectContext(project) {
'工程任务先用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。补丁锚点重叠/重复或文件变化时重新读取,不猜测写入位置。',
'已有文本文件满足当前目标时,完整分页读取后用verify_existing_files登记当前SHA和原read_call_ids,说明采用原因;跨Task须显式选择source_result_id。无需重写相同文件,不把旧成果冒充新写入;明确修改要求、测试和页面验收仍需各自真实证据。',
'跨文件修改的提案准备完整后,用prepare_change_set将本Task的change_id封存成整批审查。准备不表示应用;用户核对整个批次并确认,结果未知时先用工作台恢复入口核对,不重放文件写入。',
'复杂工程任务先了解实际范围,再用plan_task保存有限依赖步骤及真实通过条件;verify_task_step引用原工具调用、已应用批次或当前检查/页面job核验。不能删改原条件掩盖失败;inspect_task_plan核对未完成项,模型文字不代替步骤核验。简单问答无需新建工程计划。',
'浏览器实际观察的controls.selector已在该DOM核对仅匹配一个元素,优先使用此定位并核对当前页面变化。按钮的nth-of-type可能在多个父元素各匹配一次,不能假定唯一。浏览器失败返回原错误;根据实际字段修正新计划,不重复读完的同一页。',
+59 -4
View File
@@ -37,6 +37,10 @@ import { EngineRunner } from '../core/engines/engine-runner.mjs';
import { BrowserManager, publicBrowserPlan } from '../core/browser/browser-manager.mjs';
import { browserPlanInput } from '../shared/contracts/browser.mjs';
import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs';
import { FileResults } from '../core/tasks/file-results.mjs';
import { fileResultInput, fileResultToolDefinitions } from '../shared/contracts/file-results.mjs';
import { verifiedCheck } from '../core/delivery-report.mjs';
import { currentBrowserVerification } from '../core/browser/browser-manager.mjs';
import { taskPlanInput, taskProofInput, PLAN_READ_TOOLS } from '../shared/contracts/task-plans.mjs';
import { taskPlanToolDefinitions } from '../shared/contracts/task-plan-tools.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
@@ -66,6 +70,7 @@ labels.act_browser_tab = '执行原页面固定动作';
labels.plan_task = '保存任务依赖计划';
labels.verify_task_step = '核验任务步骤原证据';
labels.inspect_task_plan = '核对任务计划与未完成项';
labels.verify_existing_files = '核对当前已有成果';
labels.read_registered_skill = '读取已登记技能修订';
labels.call_registered_mcp = '请求调用已登记MCP工具';
@@ -75,6 +80,7 @@ export function validateToolArgs(tool, args) {
if (tool === 'read_registered_skill') { skillReadInput(args); return; }
if (tool === 'call_registered_mcp') { mcpCallInput(args); return; }
if (tool === 'plan_task') { taskPlanInput(args); return; }
if (tool === 'verify_existing_files') { fileResultInput(args); return; }
if (tool === 'verify_task_step') { taskProofInput(args); return; }
if (tool === 'inspect_task_plan') { if (Object.keys(args).length) throw new Error('任务计划查询只读取当前Task,不接受执行命令。'); return; }
if (tool === 'inspect_browser_tabs') { if (Object.keys(args).length) throw new Error('标签页查询不接受附加参数。'); return; }
@@ -128,6 +134,39 @@ export class Runtime {
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') }); }
fileResults() { return this.results ??= new FileResults(this.store); }
async fileDelivery(session) {
const task = this.store.owned('task', session.taskId, session.id), delivery = this.fileResults().completion(session);
if (!delivery.satisfied) return { ...delivery, stopReason: 'delivery_incomplete', message: delivery.requiresChange
? '当前要求包含修改,尚无对应追加要求之后的实际文件改动。已有成果核对不能代替修改。'
: '要求的文件尚无当前有效成果或已应用改动。' + (delivery.missingPaths.length ? '缺少:' + delivery.missingPaths.join('、') + '。' : '') + '请完整读取并核对已有成果,或生成可审查改动。' };
const policy = taskContract(task).checks;
if (policy !== 'skip' && (policy === 'required' || task.verification?.status !== 'not_configured')) {
const inspection = await inspectProject(this.store.project(session.projectId));
if (!verifiedCheck(this.store, session, inspection)) return { ...delivery, satisfied: false, stopReason: 'verification_incomplete', message: '当前工程检查尚无对应当前输入的通过证据,已有成果不能代替检查。' };
}
const browser = await currentBrowserVerification(this.store, session);
if (browser.required && browser.status !== 'passed') return { ...delivery, satisfied: false, stopReason: 'verification_incomplete', message: '当前页面验收尚未通过,已有成果不能代替页面检查。' };
return delivery;
}
async completeFileResults(session) {
if (this.projectHasActivity(session.projectId)) throw Object.assign(new Error('工程仍有活动,请停止或等待原操作结束后核对成果。'), { status: 409 });
const taskId = session.taskId, runId = session.runId;
if (workerForSession(this.store, session)) throw Object.assign(new Error('受限子任务不能独立结束父项目成果。'), { status: 409 });
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))
|| [...this.store.core.tool.values()].some(tool => tool.taskId === taskId && tool.requiresVerification)) throw Object.assign(new Error('仍有待审改动或未知结果,请先核对原操作。'), { status: 409 });
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true }); assertWorkersResolved(this.store, session.projectId); assertMcpResolved(this.store, session.projectId); assertChangeSetsResolved(this.store, session.projectId);
const delivery = await this.fileDelivery(session);
if (!delivery.satisfied) throw Object.assign(new Error(delivery.message), { status: 409 });
const plan = await this.taskPlanner().inspect(session, { candidates: false });
if (plan.configured && !plan.all_verified) throw Object.assign(new Error('原执行计划仍有未核验步骤,请先核对。'), { status: 409 });
if (session.taskId !== taskId || session.runId !== runId || this.projectHasActivity(session.projectId) || !this.fileResults().completion(session).satisfied) throw Object.assign(new Error('核对期间任务、文件或活动已变化,请重新核对。'), { status: 409 });
const task = this.store.owned('task', taskId, session.id);
task.delivery = { ...delivery, at: now(), checks: taskContract(task).checks === 'skip' ? 'not_requested' : task.verification.status };
session.status = 'completed';
this.store.message(session, 'system', '已按当前成果结束任务;' + (delivery.newChanges ? '实际修改另列。' : '无新增修改。') + '原运行、检查与Git记录保留,未请求模型。');
this.store.save(session, { type: 'file_result.task_completed' });
}
taskPlanner() { return this.taskPlans ??= new TaskPlanManager(this.store, { redact: value => this.provider.redact(value),
projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
browserManager() { return this.browser ??= new BrowserManager(this.store, { appDirectory: this.appDirectory,
@@ -290,6 +329,7 @@ export class Runtime {
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
.map(tool => ({ invocation_id: tool.id, call_id: tool.callId, tool: tool.tool, status: tool.state, requires_verification: true }));
const fileResults = this.fileResults().inspect(session);
const context = this.provider.redact(projectContext(run.project) + (run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({
parent_task_id: run.worker.parentTaskId, worker_id: run.worker.id, write_paths: run.worker.paths, budget: run.worker.budget,
rule: '只有范围内提案、审查应用和当前工程检查构成完成;不得请求任意终端、独立Git提交、外部工具或嵌套协作。',
@@ -299,6 +339,10 @@ export class Runtime {
goal: taskContract(task).goal, instructions: task.instructions.filter(instruction => instruction.source !== 'review-action'), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract: taskContract(task),
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question : '')
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ (fileResults.results.length || fileResults.sources.length ? '\n当前成果与可显式采用的旧来源(任务数据,原文件不等于新写入):' + JSON.stringify({
current: fileResults.results.slice(0, 8).map(row => ({ id: row.id, taskId: row.taskId, runId: row.runId, verification: row.verification, error: row.error, reason: row.reason, files: row.files.map(({ path, sha256, origin }) => ({ path, sha256, origin })) })),
sources: fileResults.sources.slice(0, 4),
}) : '')
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '')
+ (taskPlan ? '\n当前Task依赖计划与尚未核验的原步骤(任务数据,不授权额外操作):\n' + JSON.stringify({
@@ -308,7 +352,7 @@ export class Runtime {
}) : ''));
const skillCatalog = run.worker ? null : this.skillRegistry().catalog(session.projectId);
const mcpCatalog = run.worker ? null : this.mcpRegistry().catalog(session.projectId);
const availableTools = [...toolDefinitions, ...taskPlanToolDefinitions, ...([...this.store.core.browsing_tab.values()].some(tab=>tab.sessionId===session.id&&tab.taskId===run.taskId&&tab.status==='open')?browsingToolDefinitions:[]), ...(skillCatalog?.entries.some(value => value.status === 'current') ? skillToolDefinitions : []),
const availableTools = [...toolDefinitions, ...taskPlanToolDefinitions, ...fileResultToolDefinitions, ...([...this.store.core.browsing_tab.values()].some(tab=>tab.sessionId===session.id&&tab.taskId===run.taskId&&tab.status==='open')?browsingToolDefinitions:[]), ...(skillCatalog?.entries.some(value => value.status === 'current') ? skillToolDefinitions : []),
...(mcpCatalog?.entries.length ? mcpToolDefinitions : []),
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : []),
@@ -413,9 +457,12 @@ export class Runtime {
this.store.finishStep(session, stepRecord);
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
if (run.record.purpose === 'diagnostic') { session.status = 'completed'; run.stopReason = 'diagnostic_answered'; }
else if (session.status === 'completed' && taskContract(task).kind === 'file' && !session.changes.some(change => change.taskId === task.id && change.status === 'applied')) {
session.status = 'paused'; run.stopReason = 'delivery_incomplete';
this.store.message(session, 'system', '答复已收到,但原目标要求的文件尚无已应用记录,不能视为文件交付完成。请生成可审查的文件改动。');
else if (session.status === 'completed' && taskContract(task).kind === 'file') {
const delivery = await this.fileDelivery(session);
if (!delivery.satisfied) {
session.status = 'paused'; run.stopReason = delivery.stopReason;
this.store.message(session, 'system', '答复已收到,但' + delivery.message);
} else task.delivery = { ...delivery, at: now(), checks: taskContract(task).checks === 'skip' ? 'not_requested' : task.verification?.status ?? 'not_configured' };
}
else if (session.status === 'completed' && taskContract(task).checks !== 'skip' && (['failed', 'stale', 'unknown', 'unverified', 'running'].includes(task.verification?.status)
|| taskContract(task).checks === 'required' && task.verification?.status !== 'passed')) {
@@ -563,6 +610,14 @@ export class Runtime {
result = { status: 'planned', plan_id: plan.id, revision: plan.revision, steps: plan.steps, contract_artifact_id: plan.contractArtifactId,
note: '计划已保存,步骤尚未核验;保留原目标和通过条件,按原工具结果核验,不直接标记完成。' }; }
else if (tool === 'inspect_task_plan') result = await this.taskPlanner().inspect(session, { candidates: false });
else if (tool === 'verify_existing_files') {
result = this.fileResults().record(session, args);
const task = this.store.core.task.get(run.taskId);
if (!result.reused) clearReadStreak(task);
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0 };
progress.resultRepeats = result.reused ? (progress.resultRepeats ?? 0) + 1 : 0;
if (progress.resultRepeats >= 3) { progress.pause = true; progress.warning = '连续核对同一成果没有推进任务,请使用原成果凭据继续交付。'; }
}
else if (tool === 'verify_task_step') result = await this.taskPlanner().verify(session, args, { source: 'agent' });
else if (tool === 'inspect_engine_checks') result = { status: 'completed', engine_checks: this.engineManager().jobs(session)
.filter(job => job.taskId === run.taskId).map(job => this.engineManager().summary(session, job)), note: '已保存的引擎连接核验;完整原记录使用report_artifact_id读取,查询不会启动引擎。' };
+3
View File
@@ -689,6 +689,9 @@ 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.file_result.values()].some(value => value.sessionId === session.id && value.taskId === task?.id) ? {
fileResults: [...this.core.file_result.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-16),
} : {}),
browsingTabs: [...this.core.browsing_tab.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-16),
browsingActions: [...this.core.browsing_action.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-24),
previewPlans: [...this.core.preview_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5),
+1
View File
@@ -10,6 +10,7 @@ CORE_KINDS.push('evaluation');
CORE_KINDS.push('environment_diagnostic','environment_plan','environment_job');
CORE_KINDS.push('preview_plan','preview_job');
CORE_KINDS.push('browsing_profile','browsing_tab','browsing_observation','browsing_action');
CORE_KINDS.push('file_result');
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);
+23
View File
@@ -0,0 +1,23 @@
// This recognizes explicit file actions only; it does not certify business semantics.
export const negatedFileAction = prefix => /(?:不要|无需|不需要|不用|禁止|不得|不必|勿|不允许|不能|不再|避免|不)(?:\s|再|去|进行|执行|直接|自动|擅自|任何|做|你)*(?:.{0,24}(?:或|和|以及)\s*)?$|\b(?:do not|don't|without|never|no need to|must not|cannot|can't)\b.{0,40}$|(?:解释|说明|分析|告诉我).{0,24}(?:怎么|如何)\s*$|\bhow\s+to\s*$/i.test(prefix);
export function requestedFilePaths(text) {
const paths = [];
for (const clause of String(text).split(/[,,;;。\n]/)) {
const action = /(?:创建|新建|保存|写入|修改|重写|修复|调整|替换)|\b(?:create|save|write|modify|rewrite|fix|change|replace)\b/i.exec(clause);
if (!action || negatedFileAction(clause.slice(0, action.index))) continue;
const suffix = clause.slice(action.index + action[0].length);
if (/\b(?:from|using|based on)\b|(?:根据|参考)/i.test(suffix.split(/(?:[\w\u3400-\u9fff@.-]+\/)*[\w\u3400-\u9fff@-]+\.(?:html?|svg|txt|md|json|[cm]?[jt]sx?|css|py|ya?ml)\b/i)[0])) continue;
for (const match of suffix.matchAll(/(?:[\w\u3400-\u9fff@.-]+\/)*[\w\u3400-\u9fff@-]+\.(?:html?|svg|txt|md|json|[cm]?[jt]sx?|css|py|ya?ml)\b/ig)) paths.push(match[0]);
}
return [...new Set(paths)];
}
export function changeRequirement(task) {
const positive = text => String(text).split(/[,,;;。\n]/).some(clause => {
const match = /(?:修改|重写|修复|改写|调整|新增功能|增加功能|删除|替换)|\b(?:modify|rewrite|fix|change|delete|replace)\b/i.exec(clause);
return match && !negatedFileAction(clause.slice(0, match.index));
});
const latest = (task.instructions ?? []).findLast(item => item.source !== 'review-action' && positive(item.content));
const goal = task.contract?.goal ?? task.goal;
return latest ? { required: true, after: latest.createdAt, text: latest.content, paths: requestedFilePaths(latest.content) }
: { required: positive(goal), after: task.createdAt, text: goal, paths: requestedFilePaths(goal) };
}
+38
View File
@@ -0,0 +1,38 @@
import { isId } from './execution.mjs';
import { isContinuation, taskContract } from './task-control.mjs';
import { planHash, planError, taskRequirements } from './task-plans.mjs';
export { requestedFilePaths, changeRequirement } from './file-intent.mjs';
export function fileResultInput(input, { source = 'agent' } = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['files', 'reason'].includes(key))
|| typeof input.reason !== 'string' || !input.reason.trim() || input.reason.length > 600 || input.reason.includes('\0')
|| !Array.isArray(input.files) || !input.files.length || input.files.length > 8) throw planError('成果核对需要1–8个文件和采用原因(最多600字)。', 'input', 400);
const files = input.files.map(file => {
if (!file || typeof file !== 'object' || Object.keys(file).some(key => !['path', 'sha256', 'read_call_ids', 'source_result_id'].includes(key))
|| typeof file.path !== 'string' || !file.path || file.path.length > 240 || /[\\:\0]/.test(file.path) || file.path.startsWith('/')
|| file.path.split('/').some(part => !part || part === '.' || part === '..') || !/^[a-f0-9]{64}$/.test(file.sha256)
|| file.source_result_id !== undefined && !isId(file.source_result_id)) throw planError('需要项目内文件路径、当前SHA256和有效来源ID。', 'input', 400);
const calls = file.read_call_ids ?? [];
if (!Array.isArray(calls) || calls.length > 128 || calls.some(id => typeof id !== 'string' || !id || id.length > 160) || new Set(calls).size !== calls.length
|| source === 'agent' && !calls.length || source === 'user' && calls.length) throw planError('模型需引用本Task实际read_file调用;用户核对由宿主直接读取。', 'input', 400);
return { path: file.path, sha256: file.sha256, read_call_ids: calls, ...(file.source_result_id ? { source_result_id: file.source_result_id } : {}) };
});
if (new Set(files.map(file => file.path.toLowerCase())).size !== files.length) throw planError('核对文件不能重复。', 'input', 400);
return { files, reason: input.reason.trim() };
}
export function fileResultRequirements(task) {
const value = taskRequirements(task);
value.instructions = value.instructions.filter(item => !isContinuation(item.content));
return structuredClone({ ...value, contract: taskContract(task) });
}
export const fileResultRequirementsHash = task => planHash(fileResultRequirements(task));
export const fileResultToolDefinitions = [{ type: 'function', function: {
name: 'verify_existing_files', description: '把已存在且满足当前要求的文本文件登记为当前成果,不改写文件、不代替测试或业务验收。先用本Task的read_file完整分页读取,再传当前SHA与原read_call_ids;跨Task采用须显式source_result_id。文件/要求变化凭据失效。明确修改要求仍需本Task实际修改。返回原成果ID,可用于results类计划步骤;相同文件不重复登记。',
parameters: { type: 'object', additionalProperties: false, required: ['files', 'reason'], properties: {
reason: { type: 'string', minLength: 1, maxLength: 600 }, files: { type: 'array', minItems: 1, maxItems: 8, items: { type: 'object', additionalProperties: false, required: ['path', 'sha256', 'read_call_ids'], properties: {
path: { type: 'string' }, sha256: { type: 'string', pattern: '^[a-f0-9]{64}$' }, read_call_ids: { type: 'array', minItems: 1, maxItems: 128, items: { type: 'string' } }, source_result_id: { type: 'string' },
} } },
} },
} }];
+12 -2
View File
@@ -1,4 +1,5 @@
// Task intent is retained independently of short follow-ups and system actions.
import { changeRequirement, requestedFilePaths, negatedFileAction } from './file-intent.mjs';
export const isContinuation = content => /^(?:请)?(?:继续(?:完成|执行|开发|原任务|这个任务)?|接着(?:完成|执行)?|continue(?:\s+(?:the\s+)?(?:task|work))?)[。.!!\s]*$/i.test(String(content).trim());
export function isDiagnosticQuestion(content) {
@@ -29,15 +30,16 @@ function hasFileDeliveryRequest(goal) {
// Do not connect a past-tense modifier ("保存的原工件") to a later
// prohibition ("不修改文件") and turn a read into a delivery requirement.
const clauses = String(goal).split(/[,,;;。\n]|而是|但是|\bbut\b/i);
const action = /(?:创建|新建|保存|写入)(?!的|过的|好的|后的|下来的).{0,60}?(?:文件|HTML|[\w-]+\.(?:html?|txt|svg|md)\b)|\bcreate\b.{0,60}?\b(?:file|html|svg)\b/ig;
const action = /(?:创建|新建|保存|写入|修改|重写|修复|调整|替换)(?!的|过的|好的|后的|下来的).{0,60}?(?:文件|HTML|[\w-]+\.(?:html?|txt|svg|md)\b)|\b(?:create|modify|rewrite|fix|change|replace)\b.{0,60}?\b(?:file|html|svg)\b/ig;
return clauses.some(clause => [...clause.matchAll(action)].some(match => {
const prefix = clause.slice(0, match.index);
return !/(?:不要|无需|不需要|不用|禁止|不得|不必|勿|不允许|不能|不再|避免|不)(?:\s|再|去|进行|执行|直接|自动|擅自|你|任何)*(?:.{0,24}(?:或|和|以及)\s*)?$|\b(?:do not|don't|without|never|no need to|must not|cannot|can't)\b.{0,40}$/i.test(prefix);
return !negatedFileAction(prefix);
}));
}
export function updateTaskContract(task, instruction) {
const current = taskContract(task);
if (hasFileDeliveryRequest(instruction)) current.kind = 'file';
// Only an explicit new user instruction changes the check policy.
if (/无需(?:任何)?测试|不(?:需要|用|要)(?:进行|做|运行)?测试|\b(?:no tests?|without (?:running )?tests?)\b/i.test(instruction)) current.checks = 'skip';
else if (/(?:运行|执行|通过|修复|补充|添加).{0,12}(?:测试|工程检查)|\b(?:run|pass|fix|add)\b.{0,24}\b(?:tests?|checks?)\b/i.test(instruction)) current.checks = 'required';
@@ -65,6 +67,14 @@ export function settleAppliedTask(store, session) {
if (!applied.length) return;
if (!task) { if (!session.taskId) session.status = 'completed'; return; }
const contract = taskContract(task, id => store.core.task.get(id));
const demand = changeRequirement(task), recent = applied.filter(change => change.taskId === task.id && (!demand.after || change.createdAt >= demand.after && change.appliedAt >= demand.after));
const paths = new Set(applied.map(change => change.path));
const targets = requestedFilePaths([contract.goal, ...(task.instructions ?? []).filter(item => item.source !== 'review-action').map(item => item.content)].join('\n'));
if (targets.some(path => !paths.has(path)) || demand.required && (!recent.length || demand.paths.some(path => !recent.some(change => change.path === path)))) {
session.status = 'paused';
store.message(session, 'system', '文件已应用,但当前目标的文件范围或追加修改要求尚未满足,请按原目标继续核对。');
return;
}
task.delivery = { status: 'files_applied', paths: applied.map(change => change.path), at: new Date().toISOString(),
checks: contract.checks === 'skip' ? 'not_requested' : task.verification?.status ?? 'not_configured' };
session.status = contract.checks === 'required' || task.currentTaskPlanId || ['failed', 'stale', 'unknown', 'unverified'].includes(task.verification?.status) && contract.checks !== 'skip'
+2 -2
View File
@@ -3,9 +3,9 @@ export const taskPlanToolDefinitions = [
type: 'object', additionalProperties: false, required: ['expected_revision', 'steps'], properties: { expected_revision: { type: 'integer', minimum: 0 }, steps: { type: 'array', minItems: 1, maxItems: 12, items: {
type: 'object', additionalProperties: false, required: ['key', 'title', 'criterion', 'kind'], properties: {
key: { type: 'string', pattern: '^[a-z][a-z0-9_-]{0,39}$' }, title: { type: 'string', maxLength: 100 }, criterion: { type: 'string', maxLength: 300 },
kind: { type: 'string', enum: ['analysis', 'changes', 'checks', 'browser'] }, depends_on: { type: 'array', items: { type: 'string' }, maxItems: 12 },
kind: { type: 'string', enum: ['analysis', 'changes', 'results', 'checks', 'browser'] }, depends_on: { type: 'array', items: { type: 'string' }, maxItems: 12 },
tools: { type: 'array', description: 'analysis必填,只读工具名称,例如inspect_project/read_file/query_code。', items: { type: 'string' } },
paths: { type: 'array', description: 'changes必填,实际改动的项目相对文件路径。', items: { type: 'string' }, maxItems: 32 },
paths: { type: 'array', description: 'changes/results必填,项目相对文件路径。changes仅核验本Task实际应用;results核验verify_existing_files的当前文件成果。', items: { type: 'string' }, maxItems: 32 },
checks: { type: 'array', description: 'checks必填,实际检查名称,例如test/typecheck/build或python:test。', items: { type: 'string' }, maxItems: 6 },
viewport_width: { type: 'integer', description: 'browser必填,固定桌面/手机视口宽度。', minimum: 320, maximum: 1440 },
actions: { type: 'array', description: 'browser需要的实际操作,始终要求非空通过断言及进程退出。', items: { type: 'string', enum: ['fill', 'select', 'click', 'assert_text', 'assert_count', 'assert_visible'] } },
+3 -3
View File
@@ -23,15 +23,15 @@ export function taskPlanInput(input) {
if (!Array.isArray(input.steps) || !input.steps.length || input.steps.length > TASK_PLAN_LIMITS.steps) throw planError('任务计划需要1–12个步骤。', 'input', 400);
const steps = input.steps.map(value => {
if (!object(value) || Object.keys(value).some(key => !['key', 'title', 'criterion', 'kind', 'depends_on', 'tools', 'paths', 'checks', 'viewport_width', 'actions'].includes(key))
|| typeof value.key !== 'string' || !keyPattern.test(value.key) || !['analysis', 'changes', 'checks', 'browser'].includes(value.kind)) throw planError('步骤需要key、title、criterion和有效证据类别。', 'input', 400);
|| typeof value.key !== 'string' || !keyPattern.test(value.key) || !['analysis', 'changes', 'results', 'checks', 'browser'].includes(value.kind)) throw planError('步骤需要key、title、criterion和有效证据类别。', 'input', 400);
const step = { key: value.key, title: text(value.title, 100, '步骤标题'), criterion: text(value.criterion, 300, '通过条件'), kind: value.kind,
depends_on: unique(value.depends_on ?? [], '前置依赖', TASK_PLAN_LIMITS.steps).sort() };
const allowed = value.kind === 'analysis' ? ['tools'] : value.kind === 'changes' ? ['paths'] : value.kind === 'checks' ? ['checks'] : ['viewport_width', 'actions'];
const allowed = value.kind === 'analysis' ? ['tools'] : ['changes', 'results'].includes(value.kind) ? ['paths'] : value.kind === 'checks' ? ['checks'] : ['viewport_width', 'actions'];
if (['tools', 'paths', 'checks', 'viewport_width', 'actions'].some(key => value[key] !== undefined && !allowed.includes(key))) throw planError('步骤证据字段与类别不一致。', 'input', 400);
if (value.kind === 'analysis') {
step.tools = unique(value.tools, '读取工具', PLAN_READ_TOOLS.length).sort();
if (!step.tools.length || step.tools.some(tool => !PLAN_READ_TOOLS.includes(tool))) throw planError('工程读取只能引用已声明的实际只读工具。', 'input', 400);
} else if (value.kind === 'changes') {
} else if (['changes', 'results'].includes(value.kind)) {
step.paths = unique(value.paths, '文件范围').sort();
if (!step.paths.length || step.paths.some(file => /[\\:\0]/.test(file) || file.startsWith('/') || file.split('/').some(part => !part || part === '..' || ['.git', '.hg', '.svn'].includes(part)))) throw planError('源码步骤需要项目内常规相对文件路径。', 'input', 400);
} else if (value.kind === 'checks') {
+12
View File
@@ -1,5 +1,17 @@
# Agent Workbench:核心代理能力研究与产品计划
## 当前阶段:1.24 已有成果续接与真实交付
接续0dc0325,分支feat/existing-results-1.24;按PLAN-1.24 A–E实施。保留正式1.23/PID36552、Provider及原任务;使用独立数据/端口和声明夹具,不请求真实模型,不委派代理。
1. [complete] A:固定旧版门槛并保存独立误暂停复现,专项包括用户修改/跨任务/诊断/无需测试。
2. [complete] B:当前成果凭据、来源Task/Run/文件SHA、完整分页、显式采用、失效与实际宿主重启持久化已通过开发验收。
3. [complete] C:完成判定、无新增修改报告及results计划已实现;明确文件/新修改要求、原检查、活动/切换/未知结果仍不能绕过。
4. [in_progress] D:开发I轮16组网页/实际Electron/390px/手机网关观察通过;来源列表并发刷新和同Task自采用防刷凭据修正后,继续最终冻结验收。
5. [in_progress] E:版本及发行验收器已同步1.24,最新K轮21/21专项;继续完整相关UI/独立源码、实际安装、原状态保持、证据封存、本地Git与回顾。
初查发现完成分支只接受本Task已应用改动;用实际读取凭据补齐,不直接删除门槛。一次猜测session-store.mjs未命中,已按rg定位store.mjs;首次计划补丁因progress标题不匹配原子拒绝,本次按实际标题修改。
## 已完成:1.23 发行效率与更新进度
接续已交付1.22.1,基线397099b,分支feat/release-efficiency-1.23。用户授权全量推进并及时回顾;按docs/PLAN-1.23.md执行,不委派新代理。保留正式宿主、Provider、用户项目与原证据;研发使用独立数据/端口,不发起真实模型请求。
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fixture, launchWorkbench } from './helpers.mjs';
import { beginPlanTask } from './fixtures/task-plan-fixture.mjs';
import { readText } from '../src/server/files.mjs';
test('current-file HTTP receipts bind Task/Run and bytes, persist on restart and end without altering original runs or user Git data', async t => {
const f = fixture(t); beginPlanTask(f, '创建 README.md 文件,沿用已有内容,无需测试');
const taskId = f.session.taskId, runId = f.session.runId, sha256 = readText(f.project, 'README.md').sha256;
const originalRun = structuredClone(f.store.core.run.get(runId)); f.store.close();
let host = await launchWorkbench(t, f.data), route = '/sessions/' + f.session.id;
const input = { taskId, runId, files: [{ path: 'README.md', sha256 }], reason: '实际读取现成说明,符合当前文件交付范围。' };
await assert.rejects(host.api(route + '/file-results', { ...input, taskId: crypto.randomUUID() }), /切换/);
await assert.rejects(host.api(route + '/file-results', { ...input, runId: crypto.randomUUID() }), /切换/);
await assert.rejects(host.api(route + '/file-results', { ...input, status: 'completed' }), /核对需要/);
await assert.rejects(host.api(route + '/file-results', { ...input, files: [{ path: '../outside.md', sha256 }] }), /项目内文件/);
const saved = await host.api(route + '/file-results', input);
assert.equal(saved.results.length, 1); assert.equal(saved.results[0].verification, 'current');
const again = await host.api(route + '/file-results', input); assert.equal(again.results.length, 1);
await host.close(); host = await launchWorkbench(t, f.data);
const restored = await host.api(route + '/file-results'); assert.deepEqual(restored.results, saved.results);
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), 'User edit\n');
assert.equal((await host.api(route + '/file-results')).results[0].verification, 'stale');
await assert.rejects(host.api(route + '/file-results/complete', { taskId, runId }), /当前有效成果/);
await assert.rejects(host.api(route + '/file-results', input), /变化/);
const file = await host.api('/projects/' + f.project.id + '/file?path=README.md');
await host.api(route + '/file-results', { ...input, files: [{ path: file.path, sha256: file.sha256 }], reason: '重新核对用户编辑后的完整说明。' });
const completed = await host.api(route + '/file-results/complete', { taskId, runId });
assert.equal(completed.session.status, 'completed'); assert.equal(completed.session.execution.task.delivery.status, 'existing_verified');
assert.deepEqual(completed.session.execution.run, originalRun); assert.equal(completed.session.changes.length, 0);
assert.equal(completed.session.execution.checks.length, 0); assert.equal(completed.session.execution.deliveries.length, 0);
assert.match(fs.readFileSync(path.join(f.projectRoot, 'README.md'), 'utf8'), /User edit/);
});
+190
View File
@@ -0,0 +1,190 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { FileResults } from '../src/core/tasks/file-results.mjs';
import { TaskPlanManager } from '../src/core/tasks/task-plan-manager.mjs';
import { DeliveryReporter, renderDeliveryMarkdown } from '../src/core/delivery-report.mjs';
import { mobileSession } from '../src/core/companion/projection.mjs';
import { readText, readLines, proposeFile, applyChange } from '../src/server/files.mjs';
import { filePage } from '../src/core/context/read-budget.mjs';
import { fixture, call, assertToolPairs } from './helpers.mjs';
const answer = content => ({ message: { role: 'assistant', content }, usage: { prompt_tokens: 11, completion_tokens: 3 } });
const calls = (...tools) => ({ ...answer(''), message: { role: 'assistant', content: '', tool_calls: tools } });
function harness(t, respond) {
const f = fixture(t), provider = new Provider(); let round = 0;
provider.complete = async (...args) => respond(round++, f, args);
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
f.runtime = runtime; f.manager = runtime.fileResults(); f.wait = () => runtime.active.get(f.session.id).promise; return f;
}
function begin(f, goal = '创建 README.md 文件,已有成果满足时采用,无需测试。', forceNewTask = false) {
const run = f.store.beginRun(f.session, goal, false, f.store.config, { forceNewTask });
f.session.status = 'paused'; f.store.finishRun(f.session, run, 'fixture_ready'); return run;
}
function read(f, args) {
const run = f.store.core.run.get(f.session.runId), invocation = call('read-' + crypto.randomUUID(), 'read_file', args);
f.session.providerMessages.push({ role: 'assistant', content: '', tool_calls: [invocation] });
const event = f.store.event(f.session, { kind: 'tool', phase: 'queued', tool: 'read_file', toolCallId: invocation.id, label: 'Fixture actual read' });
const record = f.store.beginInvocation(f.session, invocation, run, event); f.store.invocationState(f.session, event, 'running');
const result = filePage(readLines(f.project, args), args, { callId: invocation.id });
event.phase = 'completed'; f.store.finishInvocation(f.session, event, result);
f.session.providerMessages.push({ role: 'tool', tool_call_id: invocation.id, content: JSON.stringify(result) });
return invocation.id;
}
function input(f, extra = {}) { return { files: [{ path: 'README.md', sha256: readText(f.project, 'README.md').sha256, ...extra }], reason: '已按当前目标核对现有文件内容。' }; }
test('full actual read and existing receipt complete a no-test file task without fabricating changes, checks or commits', async t => {
const f = harness(t, (round, f) => round === 0 ? calls(call('existing-read', 'read_file', { path: 'README.md' }))
: round === 1 ? calls(call('existing-result', 'verify_existing_files', input(f, { read_call_ids: ['existing-read'] }))) : answer('已核对已有成果,无新增修改。'));
const bytes = fs.readFileSync(path.join(f.projectRoot, 'README.md'));
f.runtime.start(f.session.id, '创建 README.md 文件,已有成果满足时采用,无需测试。'); await f.wait();
assert.equal(f.session.status, 'completed');
const task = f.store.core.task.get(f.session.taskId);
assert.equal(task.delivery.status, 'existing_verified'); assert.equal(task.delivery.newChanges, 0); assert.equal(task.delivery.checks, 'not_requested');
assert.equal(f.session.changes.length, 0); assert.equal(f.store.core.check_job.size, 0); assert.equal(f.store.core.delivery_job.size, 0);
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'README.md')), bytes);
const row = f.manager.records(f.session)[0]; assert.equal(f.manager.verify(f.session, row.id).id, row.id);
assert.equal(row.files[0].reads[0].callId, 'existing-read'); assertToolPairs(f.session.providerMessages);
f.runtime.start(f.session.id, '继续完成'); await f.wait();
assert.equal(f.session.taskId, task.id); assert.equal(f.manager.inspect(f.session).results[0].verification, 'current'); assert.equal(f.session.status, 'completed');
});
test('partial pages, partial lines, wrong hashes and failed reads cannot be adopted; contiguous full paging can', t => {
const f = fixture(t); begin(f); const manager = new FileResults(f.store);
const a = read(f, { path: 'README.md', start_line: 1, end_line: 1 });
assert.throws(() => manager.record(f.session, input(f, { read_call_ids: [a] })), /完整读取/);
const b = read(f, { path: 'README.md', start_line: 2, end_line: 4, limit: 8 });
assert.throws(() => manager.record(f.session, input(f, { read_call_ids: [a, b] })), /完整读取/);
const c = read(f, { path: 'README.md', start_line: 2, end_line: 4, offset: 8 });
const result = manager.record(f.session, input(f, { read_call_ids: [a, b, c] }));
assert.equal(manager.verify(f.session, result.result_id).files[0].reads.length, 3);
const invocation = [...f.store.core.tool.values()].find(row => row.callId === c); invocation.state = 'unknown'; invocation.requiresVerification = true;
assert.throws(() => manager.verify(f.session, result.result_id), /读取调用/);
});
test('user edits and new requirements invalidate receipts, and a second task must explicitly adopt a source in its own project/session', t => {
const f = fixture(t); begin(f); const manager = new FileResults(f.store);
const old = manager.record(f.session, input(f), { source: 'user' }), oldTask = f.session.taskId;
assert.throws(() => manager.record(f.session, input(f, { source_result_id: old.result_id }), { source: 'user' }), /不重复采用自身成果/);
assert.equal(manager.records(f.session).length, 1);
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nUser contribution\n');
assert.equal(manager.inspect(f.session).results[0].verification, 'stale');
assert.throws(() => manager.record(f.session, { ...input(f), files: [{ path: 'README.md', sha256: manager.records(f.session)[0].files[0].sha256 }] }, { source: 'user' }), /变化/);
begin(f, '创建 README.md 文件,沿用已有内容,无需测试。', true);
assert.notEqual(f.session.taskId, oldTask);
assert.throws(() => manager.record(f.session, input(f), { source: 'user' }), /显式选择/);
const adopted = manager.record(f.session, input(f, { source_result_id: old.result_id }), { source: 'user' });
const origin = manager.verify(f.session, adopted.result_id).files[0].origin;
assert.equal(origin.taskId, oldTask); assert.notEqual(origin.sha256, manager.records(f.session)[0].files[0].sha256);
const otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot); fs.writeFileSync(path.join(otherRoot, 'README.md'), 'other');
const otherProject = f.store.addProject(otherRoot), other = f.store.createSession(otherProject.id);
f.store.beginRun(other, '创建 README.md 文件', false, f.store.config);
assert.throws(() => manager.verify(other, adopted.result_id, { current: false }), /不属于/);
begin(f, '补充需求:标题必须更清晰');
assert.equal(manager.inspect(f.session).results[0].verification, 'stale');
});
test('adopting an unchanged file never satisfies an explicit modification or a new modification instruction', async t => {
const f = fixture(t); const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
begin(f, '修改 README.md 文件标题,无需测试'); const manager = runtime.fileResults();
manager.record(f.session, input(f), { source: 'user' });
assert.equal(manager.completion(f.session).requiresChange, true);
await assert.rejects(runtime.completeFileResults(f.session), /修改/);
const proposed = proposeFile(f.store, f.session, { path: 'README.md', content: '# Correct title\n', reason: '修改标题' });
applyChange(f.store, f.session, f.session.changes.at(-1).id);
assert.equal(manager.completion(f.session).satisfied, true);
await new Promise(resolve => setTimeout(resolve, 10));
begin(f, '再修改 README.md 文件,增加结果说明', true);
manager.record(f.session, input(f, { source_result_id: manager.records({ ...f.session, taskId: f.store.core.task.get(f.session.taskId).previousTaskId })[0].id }), { source: 'user' });
assert.equal(manager.completion(f.session).requiresChange, true);
});
test('required checks and stale passing flags cannot be bypassed by current file receipts', async t => {
const f = fixture(t), runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
begin(f, '创建 README.md 文件并运行测试');
runtime.fileResults().record(f.session, input(f), { source: 'user' });
await assert.rejects(runtime.completeFileResults(f.session), /工程检查/);
f.store.core.task.get(f.session.taskId).verification = { status: 'passed', checkJobId: crypto.randomUUID() };
await assert.rejects(runtime.completeFileResults(f.session), /工程检查/);
assert.equal(f.session.status, 'paused');
});
test('results plan proofs bind current file receipts while changes proofs still demand real applied change sets', async t => {
const f = fixture(t); begin(f); const manager = new FileResults(f.store), planner = new TaskPlanManager(f.store);
const result = manager.record(f.session, input(f), { source: 'user' });
const plan = await planner.plan(f.session, { expected_revision: 0, steps: [{ key: 'existing', title: '核对已有说明', criterion: '当前说明原文件SHA与完整成果凭据一致', kind: 'results', paths: ['README.md'] }] });
const proof = await planner.verify(f.session, { plan_id: plan.id, expected_revision: 1, step_key: 'existing', evidence_id: result.result_id });
assert.equal(proof.status, 'completed'); assert.equal((await planner.inspect(f.session)).all_verified, true);
await assert.rejects(planner.evidence(f.session, { kind: 'changes', paths: ['README.md'] }, result.result_id), /不属于/);
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), 'new owner text');
assert.equal((await planner.inspect(f.session)).all_verified, false);
});
test('duplicate receipts cannot create progress indefinitely or reset no-progress reads', async t => {
const f = harness(t, (round, f) => round === 0 ? calls(call('loop-read', 'read_file', { path: 'README.md' })) : calls(call('loop-' + round, 'verify_existing_files', input(f, { read_call_ids: ['loop-read'] }))));
f.runtime.start(f.session.id, '创建 README.md 文件,无需测试'); await f.wait();
assert.equal(f.session.status, 'paused'); assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'no_progress');
assert.equal(f.manager.records(f.session).length, 1); assert.ok(f.store.core.run.get(f.session.runId).steps < 10);
});
test('manual completion preserves the failed original run and refuses unknown operations', async t => {
const f = fixture(t), runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
const run = begin(f); runtime.fileResults().record(f.session, input(f), { source: 'user' });
const original = structuredClone(run);
await runtime.completeFileResults(f.session);
assert.equal(f.session.status, 'completed'); assert.equal(f.store.core.task.get(f.session.taskId).status, 'completed');
assert.deepEqual(run, original); assert.equal(f.session.changes.length, 0);
f.store.core.tool.set('unknown', { id: 'unknown', taskId: f.session.taskId, requiresVerification: true });
await assert.rejects(runtime.completeFileResults(f.session), /未知结果/);
});
test('completion refuses active work, files changed during inspection and a newly selected task', async t => {
const f = fixture(t), runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
begin(f); runtime.fileResults().record(f.session, input(f), { source: 'user' });
runtime.active.set(f.session.id, { project: f.project });
try { await assert.rejects(runtime.completeFileResults(f.session), /仍有活动/); } finally { runtime.active.delete(f.session.id); }
const planner = runtime.taskPlanner();
planner.inspect = async () => { fs.appendFileSync(path.join(f.projectRoot, 'README.md'), 'Edit while inspecting\n'); return { configured: false }; };
await assert.rejects(runtime.completeFileResults(f.session), /核对期间/);
assert.equal(f.session.status, 'paused');
runtime.fileResults().record(f.session, input(f), { source: 'user' });
planner.inspect = async () => { begin(f, '创建 README.md 文件,无需测试', true); return { configured: false }; };
await assert.rejects(runtime.completeFileResults(f.session), /核对期间/);
assert.equal(f.session.status, 'paused');
assert.equal(f.store.core.task.get(f.session.taskId).delivery, undefined);
});
test('unrelated files cannot stand in for named output paths, nor can a late apply satisfy newer instructions with an old proposal', async t => {
const f = fixture(t), runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
begin(f, '创建 result.html 文件,无需测试'); const manager = runtime.fileResults();
manager.record(f.session, input(f), { source: 'user' });
assert.deepEqual(manager.completion(f.session).missingPaths, ['result.html']); assert.equal(manager.completion(f.session).satisfied, false);
begin(f, '修改 README.md 文件标题,无需测试', true);
proposeFile(f.store, f.session, { path: 'README.md', content: '# Early proposal\n', reason: '早于追加要求' });
await new Promise(resolve => setTimeout(resolve, 10));
begin(f, '再修改 README.md 文件,加入新要求');
applyChange(f.store, f.session, f.session.changes.at(-1).id);
assert.equal(manager.completion(f.session).requiresChange, true);
assert.equal(f.session.status, 'paused');
await assert.rejects(runtime.completeFileResults(f.session), /修改/);
});
test('delivery and mobile projections distinguish adopted bytes, new changes, no tests and no commit; mutations cannot rewrite receipts', async t => {
const f = fixture(t), runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
begin(f); const manager = runtime.fileResults(), saved = manager.record(f.session, input(f), { source: 'user' });
await runtime.completeFileResults(f.session);
const reporter = new DeliveryReporter(f.store), { report } = await reporter.create(f.session);
assert.equal(report.status, 'existing_verified'); assert.equal(report.checkPolicy, 'not_requested'); assert.equal(report.gitOutcome.status, 'no_new_changes');
assert.equal(report.verifiedCheckJobId, null); assert.equal(report.deliveries.length, 0); assert.match(renderDeliveryMarkdown(report), /未创建提交/);
const projection = mobileSession(f.store, runtime, f.session);
assert.equal(projection.fileResults[0].verification, 'current'); assert.equal(projection.fileResults[0].files[0].sha256, report.fileResults[0].files[0].sha256);
assert.equal(JSON.stringify(projection).includes(f.projectRoot.replaceAll('\\', '\\\\')), false);
const row = manager.records(f.session)[0]; row.reason = 'tampered';
assert.throws(() => manager.verify(f.session, saved.result_id), /封存原凭据/); row.reason = '已按当前目标核对现有文件内容。';
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), 'changed');
assert.equal((await reporter.create(f.session)).report.status, 'needs_results');
assert.equal(mobileSession(f.store, runtime, f.session).fileResults[0].verification, 'stale');
});
+2 -1
View File
@@ -18,7 +18,8 @@ test('operational questions are diagnostic while explicit repair requests remain
test('file delivery requires a positive instruction, not saved evidence or a prohibited write', () => {
for (const goal of ['读取保存的原工件,分段取得真实依据,不执行命令或修改文件。',
'读取保存过的 HTML 文件并解释内容', '不要创建文件,只分析结果', '读取工件,不执行命令或创建文件',
'Do not create a file; explain the evidence.', 'Read the saved file without creating HTML.']) {
'Do not create a file; explain the evidence.', 'Read the saved file without creating HTML.',
'不需要做任何修改 HTML 文件,只核对结果', '解释如何修改 HTML 文件', 'Explain how to modify an HTML file.']) {
assert.equal(taskContract({ goal }).kind, 'general', goal);
}
for (const goal of ['创建一个 HTML 文件,无需测试', '新建 result.txt', '把结果保存为 report.md 文件',