diff --git a/AGENTS.md b/AGENTS.md index 3468df6d..ea3a6322 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ 本仓库专注AI编程与能力研究工作台。其他项目不纳入本项目计划或代码。用户确定的研究对象为Codex、Claude Code、Cursor、DeepSeek Harness、WorkBuddy及DSH-purge;目标是将有证据的机制独立开发成自有Harness内置能力。 -1.0.0是已保存的基础里程碑;当前1.1.0已交付M1可靠内核、任务记录和Node/npm工程检查切片。后续实现与真实工程验收见docs/PRODUCT-PLAN.md、docs/CAPABILITIES.md和docs/RESEARCH-ROADMAP.md。计划中的能力不能写成已经实现。 +1.0.0是已保存的基础里程碑;1.1.0已交付M1可靠内核,1.2.0增加当前Task的本地Git交付及证据报告。后续实现与真实工程验收见docs/PRODUCT-PLAN.md、docs/CAPABILITIES.md和docs/RESEARCH-ROADMAP.md。计划中的能力不能写成已经实现。 ## 研究与来源 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e75ad73..fc4a791c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Agent Workbench 更新记录 +## 1.2.0 · 2026-10-29 + +- 任务记录增加本地Git提交预览、实际文件diff、署名和说明;确认只提交当前Task已应用且检查有效的文件,保留其他暂存与工作区改动。 +- 提交job持久记录准备、发布、核对和报告阶段;实际退出后不重放提交,提供独立的结果核对与索引恢复操作。 +- JSON/Markdown交付报告直接汇总实际任务、运行、测试日志、模型用量、源码指纹和commit,可查看与下载;业务需求验收状态单独记录。 +- 源码检查与Git元数据分别绑定指纹,单纯提交不会让未变化源码的测试过期;已跟踪删除、损坏日志和不完整快照仍会阻止交付。 +- 增加助手工具plan_delivery与delivery_report;模型可准备预览,实际提交由用户独立确认。 +- 修复重复点击当前会话导致内容清空;提交、差异、报告和恢复入口适配390px。 +- 完整92项行为/API/实际退出检查和9组交付界面验收通过。便携/源码、基础界面与真实模型的最终证据见[验收记录](docs/VALIDATION.md)。 + ## 1.1.0 · 2026-10-29 - 任务与每轮运行分别保存,原目标、追加要求、模型配置、累计用量和预算可在任务面板核对。 diff --git a/README.md b/README.md index 09492510..167dd7ce 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # 本地 Agent 工作台 -Agent Workbench 1.1.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。在项目对话、文件工具、审核和诊断的基础上,增加可靠Task/Run记录、SQLite保存、实际工程检查与审核后继续原任务的流程。 +Agent Workbench 1.2.0 将 Claude Code 与 Cursor 的机制研究整合为独立的本地 AI 编程工作台。任务与运行记录、实际工程检查、文件审查、本地Git提交及交付报告现在可以在同一个Task中完成。 -每次运行保留模型与预算、已完成工具和日志工件。检查通过需要实际退出码、测试数量和对应源码快照;应用改动后可点击「继续检查与交付」,沿用原目标进行测试与修复。版本改动见 [CHANGELOG](CHANGELOG.md),本轮验收范围见 [QA-1.1](docs/QA-1.1.md)。 +每次运行保留模型与预算、已完成工具和日志工件。检查通过需要实际退出码、测试数量和对应源码快照;应用改动后可点击「继续检查与交付」,沿用原目标进行测试与修复。提交前查看实际文件、diff、署名和检查结果,确认后生成本地提交及可下载的JSON/Markdown报告。版本改动见 [CHANGELOG](CHANGELOG.md),本轮验收范围见 [QA-1.2](docs/QA-1.2.md)。 ## 后续产品与能力建设 @@ -13,7 +13,7 @@ Agent Workbench 1.1.0 将 Claude Code 与 Cursor 的机制研究整合为独立 - [研究路线](docs/RESEARCH-ROADMAP.md)与[目标来源登记](research/targets.json):版本、来源、SDK限制及未解决问题。 - [本地Git流程](docs/GIT-WORKFLOW.md)与[项目执行规范](AGENTS.md):源码仓库已建立,main基线`bac87da`、标签`v1.0.0-baseline`;后续按独立小步检查并及时提交。 -1.1.0实现有界工程识别、只读Git基线和Node/npm检查job。增量工程索引、任务依赖图、patch/ChangeSet、用户工程Git/worktree自动交付、多worker、外部引擎、REA执行和桌面/手机配对按后续阶段建设。 +1.2.0实现有界工程识别、Node/npm检查job、当前Task已审核文件的Git交付及证据报告。增量工程索引、任务依赖图、patch/ChangeSet、隔离worktree、多worker、外部引擎、REA执行和桌面/手机配对按后续阶段建设。 ## 直接运行 @@ -28,6 +28,7 @@ Windows x64 便携包自带 Node.js 24.22.1和npm。解压后双击 `Start-Workb 5. 点击「模型连接」,选择兼容模型服务,填写接口根地址、模型和按需填写的 Key;可先「验证模型响应」,再保存连接。 6. 遇到请求失败,点击错误卡片的「查看运行诊断」。可在同一会话提问,助手通过本地 `inspect_session` 核对错误来源、近期工具和文件实际状态。 7. 点击「查看任务记录」查看目标、各轮运行、累计用量与工件。准备工程检查后,核对npm脚本再执行;查看实际测试数量与日志。应用全部提案后,用「继续检查与交付」继续同一目标。 +8. 检查通过后,在任务记录中「预览Git提交」,核对已审核路径、差异、署名和说明,再「确认创建本地提交」。工作台保留其他暂存与工作区改动,结果未知时提供「核对提交结果」;报告可直接查看和下载。Git需要本机安装,具体范围见[Git交付契约](docs/GIT-DELIVERY.md)。 ## 模型连接 diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index c0079f3f..7a325a16 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -1,6 +1,6 @@ # Agent Workbench 能力目标与验收矩阵 -日期:2026-10-29。1.0.0为已保存的基础里程碑,1.1.0为本轮M1实现。下表保留1.0.0缺口与完整产品目标;每项完成范围以实际验证记录为准。 +日期:2026-10-29。1.0.0为基础里程碑,1.1.0实现M1,1.2.0实现首个内置Git交付切片。下表保留1.0.0缺口与完整产品目标;每项完成范围以实际验证记录为准。 总体方案见 [PRODUCT-PLAN.md](PRODUCT-PLAN.md),研究问题与来源见 [RESEARCH-ROADMAP.md](RESEARCH-ROADMAP.md)。 @@ -21,6 +21,13 @@ 模块路径指 [建议架构](PRODUCT-PLAN.md#4-建议架构一套执行核心多种入口),不是当前目录结构。研究编号对应研究路线中的问题组。 +### 1.2.0 M2已实现切片 + +- C09/C13:Task绑定的Git预览、已审核文件的实际本地提交、其他工作区/暂存修改保留及JSON/Markdown报告;支持已有命名分支,尚无隔离worktree与自动合并。 +- C02/C07/C23:稳定plan/job身份、实际引用核对与9个真实退出切点、不重放提交;索引恢复只处理本次拥有的字节,外部变化保留需核对状态。 +- C11/C24:源码与Git基线分别验证,检查日志完整性和测试数量仍须满足;92项完整行为检查、9组桌面/390px交付界面通过。 +- C08、多类工程与完整M2/M6成功率仍待后续实施。范围见[QA-1.2](QA-1.2.md)与[Git交付契约](GIT-DELIVERY.md)。 + | ID / 能力 | 当前1.0.0基础与缺口 | 后续产品目标 | 参考问题 / 模块 / 阶段 | 必须看到的验收证据 | | --- | --- | --- | --- | --- | | C01 需求与任务规划 | 有对话和有限步数工具循环,没有任务依赖图 | 固定目标、约束和完成标准;拆任务、判断依赖、接收追加要求与重规划 | CX-1、WB-1 / tasks / M1–M2 | 追加要求后仍保留原目标;任务完成由验收条件决定 | @@ -52,7 +59,9 @@ - [provider.mjs](../src/server/provider.mjs):固定工具定义、深度3/160项的项目上下文、提取式投影、非流式模型请求。 - [runtime.mjs](../src/server/runtime.mjs):有限循环、内存active/waiters、命令审批与60秒进程生命周期。 -- [store.mjs](../src/server/store.mjs):JSON会话存储、备份与重启状态处理。 +- [store.mjs](../src/server/store.mjs):SQLite任务与事件、旧JSON迁移、备份与重启状态处理。 +- [git-delivery.mjs](../src/core/git-delivery.mjs):当前Task已审核文件的提交计划、独立索引/引用事务、结果核对和恢复。 +- [delivery-report.mjs](../src/core/delivery-report.mjs):实际检查与提交证据的JSON/Markdown报告。 - [files.mjs](../src/server/files.mjs):最多400文件/8MB的搜索预算、单文件提案、基线与原文备份。 - [app.mjs](../src/server/app.mjs):SSE快照、全局配置、默认12步/最高30步限制。快照revision与未来持久事件seq是两个概念。 diff --git a/docs/GIT-DELIVERY.md b/docs/GIT-DELIVERY.md new file mode 100644 index 00000000..625130d1 --- /dev/null +++ b/docs/GIT-DELIVERY.md @@ -0,0 +1,32 @@ +# 内置本地Git交付契约 + +本切片把已审核文件、实际工程检查、只读提交预览、持久提交job和交付报告绑定到同一个Task。代码检查不等同于业务需求已验收;报告只陈述已有证据。 + +## 准入与范围 + +- 当前工程必须是自己的Git仓库,已有HEAD;不自动初始化、推送或创建worktree。 +- 本机需要可用的Git;当前实现使用Git索引及prepare/commit引用事务,已在Git for Windows 2.54.0验证。便携包随附Node/npm,Git使用本机安装。 +- 只接受当前Task中已应用的普通文本文件。连续提案的基线链必须一致,当前文件SHA256必须等于最新已应用提案。 +- Git HEAD中的内容必须与该修改链起点一致。选中文件已有其他人的工作区修改、暂存修改、未合并或特殊索引标记时拒绝提交。 +- 新文件必须由本Task从不存在的基线创建。其他未跟踪文件不会进入提交。 +- 完整有界源码快照和至少一项实际有测试数量的通过记录必须一致;跳过、取消、未知、损坏日志和过期检查均不能准入。 +- 不执行自定义Git内容过滤器、外部diff或fsmonitor。本地提交不执行仓库hooks和GPG签名,预览明确说明该策略;依赖这些检查的团队工程须通过自己的Git流程交付。 +- 源码指纹与Git执行基线分别保存。文件未变化时,提交不使已有测试过期。 + +## 提交与保留 + +确认只接收已保存的planId。预览包含任务、HEAD/ref、作者、实际消息、明确文件清单、diff、检查记录和策略;任一基线变化需要新计划。 + +执行宿主持有项目互斥。Git使用参数数组、明确路径、受限环境和独立索引构建交付树;原索引持有标准index.lock,保留不属于此任务的所有索引条目。Git引用事务先比较原HEAD并prepare锁定HEAD和当前分支,再核对实际分支引用后commit或abort;支持已有命名分支。提交记录含唯一Workbench-Delivery trailer,禁止以重试生成第二个提交。 + +完成必须核对实际提交的父节点、树、路径、文件blob、唯一trailer、原工作区源码与无关索引条目。未知状态不会伪装成完成。 + +## 停止与恢复 + +job持久保存queued/preparing/prepared/publishing/committed/completed阶段及索引锁的本次身份。发布前停止不会更新HEAD;已发布后的停止继续核对实际结果,不能假定取消了提交。 + +服务实际退出后不自动重放。显式“核对提交结果”先只读确认预期提交和引用;只有本次持有的遗留索引锁及原索引SHA均匹配、原进程已结束时,才修复本次索引发布。遇到外部索引/引用变化保留需处理状态,不删除别人的锁、不覆盖外部修改。 + +## 交付报告 + +JSON和Markdown工件从实际Task、Run、模型快照、usage、提案、检查日志、源指纹及Git结果生成;带SHA256并可查看/下载。无需额外模型调用。报告明确区分待审核、需检查、检查通过待提交、已验证提交和结果待核对,不把模型文字中的“完成”作为交付证据。 diff --git a/docs/PRODUCT-PLAN.md b/docs/PRODUCT-PLAN.md index 1d10930a..f2d447fc 100644 --- a/docs/PRODUCT-PLAN.md +++ b/docs/PRODUCT-PLAN.md @@ -1,6 +1,6 @@ # Agent Workbench 后续产品与执行开发方案 -日期:2026-10-29。状态:规划版本;当前软件为1.0.0基础版本。本文中的后续能力与验收目标均为待实施项。 +日期:2026-10-29。本文保留完整产品规划;1.1.0已实现M1,1.2.0已实现M2的当前Task本地Git交付及证据报告切片。具体已实现范围见[能力矩阵](CAPABILITIES.md),其余阶段与完整验收目标继续实施。 ## 1. 产品目标 diff --git a/docs/QA-1.2.md b/docs/QA-1.2.md new file mode 100644 index 00000000..2e6fa532 --- /dev/null +++ b/docs/QA-1.2.md @@ -0,0 +1,15 @@ +# 1.2.0 内置Git交付验收 + +本轮覆盖同一个Task中的实际测试失败、四模块修复、文件审核、重新检查、Git预览/确认、结果核对和JSON/Markdown报告。完整M2的ChangeSet、增量工程索引、React/Python样本、worktree及后续引擎/桌面/手机配对仍继续开发。 + +| 用户可见行为 | 实际检查 | 已验证范围 | +| --- | --- | --- | +| 审核文件与检查绑定同一Task | 原Task/Run、文件链、源码指纹、日志完整性 | 完整92项行为/API通过 | +| 只读预览与独立确认 | 实际diff、署名、说明、planId与重复请求 | 9组交付UI通过 | +| 保留其他暂存和工作区改动 | 独立索引/树及Git引用事务 | 新/旧文件、CRLF、无关删除与索引标记 | +| 中断结果核对且不重放 | 9个真实进程退出切点及索引/引用归属 | 外部变化保留需核对状态 | +| 报告查看和下载 | JSON/Markdown真实工件SHA256、检查与commit | 桌面/390px与逐字节下载通过 | +| 重复选中会话内容保留 | 同id选择不清空、可只读刷新 | 重复点击回归通过 | +| 旧版原进程连续升级 | 旧0.1→1.0→SQLite→1.2→再次升级 | 合成内存连接与历史保留通过 | + +基础/诊断/任务UI、便携/源码ZIP和正式配置模型的最终记录随验收完成写入[VALIDATION](VALIDATION.md)。手机尺寸验证用于响应式界面;实际手机远程连接仍需后续配对网关。 diff --git a/docs/UPGRADE.md b/docs/UPGRADE.md index bb98c02f..0ca58293 100644 --- a/docs/UPGRADE.md +++ b/docs/UPGRADE.md @@ -1,16 +1,16 @@ -# 升级到 1.1.0并保留原连接 +# 升级到 1.2.0并保留原连接 升级脚本在原Node进程中替换工作台实现,保留现有内存连接对象、项目和会话。它不会读取、打印、导出或复制API Key。普通停止后重启会丢失仅在内存中的Key,需要重新填写。 ## 升级条件 -使用已完成构建的1.1.0便携包,保留原启动发行目录及当前实现目录。工作台中的任务、工程检查和命令审批均已结束,当前本地9229端口可用。脚本接受127.0.0.1上的0.1.0、1.0.0或1.1.0工作台,先核对进程PID和原发行路径,再迁移对象。升级后校验配置、项目、会话和PID,并关闭本次开启的调试端口。控制请求使用独立HTTP连接,避免调试暂停后复用超时连接。 +使用已完成构建的1.2.0便携包,保留原启动发行目录及当前实现目录。工作台中的任务、工程检查、Git交付和命令审批均已结束,当前本地9229端口可用。脚本接受127.0.0.1上的0.1.0、1.0.0、1.1.0或1.2.0工作台,先核对进程PID和原发行路径,再迁移对象。升级后校验配置、项目、会话和PID,并关闭本次开启的调试端口。控制请求使用独立HTTP连接,避免调试暂停后复用超时连接。 -首次进入1.1.0时,旧JSON数据在保留原字节备份的事务中迁移到SQLite。任务、运行、事件和工件使用新契约,旧历史以legacy-import标明来源。随附npm位于新发行runtime,原进程保留原Node可执行路径并使用新npm检查器。 +首次从旧JSON版本进入SQLite时,数据在保留原字节备份的事务中迁移,旧历史以legacy-import标明来源。已有SQLite实例保留原状态与Map并补齐新增Git记录类型。随附npm位于新发行runtime,原进程保留原Node可执行路径并使用新npm检查器。 ## 执行 -在解压后的1.1.0便携目录打开PowerShell。使用service-info保存的原启动目录,数据目录沿用当前启动配置;此前已经热升级的实例另传当前handler目录。 +在解压后的1.2.0便携目录打开PowerShell。使用service-info保存的原启动目录,数据目录沿用当前启动配置;此前已经热升级的实例另传当前handler目录。 ```powershell $awNewRoot = (Get-Location).Path @@ -20,9 +20,9 @@ if ($awServiceInfo.runtimeRoot) { $awUpgradeArguments += @('--handler-root', $aw & (Join-Path $awNewRoot 'runtime\node.exe') @awUpgradeArguments ``` -成功后访问 `http://127.0.0.1:4318/?release=1.1.0`,界面显示v1.1.0。任务记录和运行诊断可核对模型、预算、工具、工件与文件审核状态。已有项目路径继续指向原项目,不移动用户文件。 +成功后访问 `http://127.0.0.1:4318/?release=1.2.0`,界面显示v1.2.0。任务记录可查看工程检查、Git预览、提交与交付报告;已有项目路径继续指向原项目,不移动用户文件。 -`service-info.json`保留原启动目录,并更新当前实现目录`runtimeRoot`与版本。再次运行启动器会复用当前本地服务;以后需要重启时,从1.1.0目录启动。 +`service-info.json`保留原启动目录,并更新当前实现目录`runtimeRoot`与版本。再次运行启动器会复用当前本地服务;以后需要重启时,从1.2.0目录启动。 ## 验证范围 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 525ff9b0..8518e4fd 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,19 @@ # Agent Workbench 验收记录 +## 1.2.0 · 当前Task的Git交付与证据报告 + +Windows x64、Node24.22.1、Edge156.0.4314.42。构建通过;完整92项行为/API/实际退出恢复测试全部通过,0失败/跳过/取消。首轮90/92的两个失败已定位并修复,15项相关专项及最终完整回归均通过。 + +| 验证 | 结果 | 结构化证据 | +| --- | --- | --- | +| 完整行为/API/实际退出与连续升级 | 92/92通过 | [m2-tests-validation.json](m2-tests-validation.json) | +| 基础界面 | 10/10通过 | [m2-ui-validation.json](m2-ui-validation.json) | +| 模型错误与诊断界面 | 9/9通过 | [m2-diagnostics-ui-validation.json](m2-diagnostics-ui-validation.json) | +| 任务、工件、预算与审核后继续 | 7/7通过 | [m2-execution-ui-validation.json](m2-execution-ui-validation.json) | +| Git预览/确认/报告/未知结果核对 | 9/9通过 | [m2-delivery-ui-validation.json](m2-delivery-ui-validation.json) | + +桌面提交预览和390px报告已目视核对,文字、diff、hash、关闭入口与固定输入区均可用。全部界面检查无页面/请求异常。便携/源码包、正式原进程升级及配置模型的内置Git真实闭环正在进行,完成后补入此处;完整M2/M6验收和后续能力不计入上述结果。 + ## 1.1.0 · M1可靠内核与工程切片 2026-10-29,Windows x64,Node24.22.1,Edge156.0.4314.42。TypeScript/Vite/esbuild构建通过。完整68项行为/API/进程退出恢复检查通过,0失败/跳过/取消;新增Task/Run、SQLite事务、工件损坏、预算、工程检查与审核后继续的覆盖。 diff --git a/docs/m2-delivery-ui-validation.json b/docs/m2-delivery-ui-validation.json new file mode 100644 index 00000000..4c9f1406 --- /dev/null +++ b/docs/m2-delivery-ui-validation.json @@ -0,0 +1,31 @@ +{ + "success": true, + "version": "1.2.0", + "testedAt": "2026-10-29T08:23:37.531Z", + "browser": "156.0.4314.42", + "passed": [ + "actual failing tests and four source proposals retain the original project and task", + "reviewed changes continue the same Task through 14 real tests and model-prepared Git review", + "review shows actual paths, diffs, tests, author and policy; cancelling leaves Git unchanged", + "an index change after confirmation preview refuses the stale job and preserves both staged owners", + "390px confirmation keeps file hashes, diffs and actions inside the modal", + "double confirmation creates one four-file commit, retains owner bytes and publishes report with completion", + "report viewing and Markdown/JSON downloads preserve verified artifact bytes and truthful acceptance limits", + "mobile report preview closes cleanly and keeps the task input fixed", + "unknown Git results block new submission and the explicit reconcile action restores the existing commit" + ], + "pageErrors": [], + "requestFailures": [], + "projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\delivery-ui-069d8e99-b7f8-4dd9-abb2-8b55e1aaff68\\四模块交付工程", + "projectId": "8a3b97cc-61d4-4e39-96f4-2b22def997ec", + "sessionId": "0b0642eb-113f-451f-a550-76010f5ffaa5", + "taskId": "75f017e1-1159-4216-8941-5b33a89e0286", + "commit": "14cd93f53bb4c74f75512d04b7b395c655965c73", + "recoveryCommit": "2139da22a461ae7e9cf68dcefba6600fdecea819", + "testCounts": { + "baselineFailed": 13, + "passed": 14 + }, + "model": "controlled local HTTP fixture", + "confirmations": 2 +} \ No newline at end of file diff --git a/docs/m2-diagnostics-ui-validation.json b/docs/m2-diagnostics-ui-validation.json new file mode 100644 index 00000000..f70798b5 --- /dev/null +++ b/docs/m2-diagnostics-ui-validation.json @@ -0,0 +1,20 @@ +{ + "success": true, + "version": "1.2.0", + "url": "http://127.0.0.1:4321", + "date": "2026-10-29T08:38:14.039Z", + "passed": [ + "model response validation checks the tentative connection before saving", + "a model failure after successful tools shows source, attempts and local runtime diagnosis", + "explicit retry preserves the completed tool result without replaying the task", + "an error question receives the actual session diagnosis and formatted answer", + "review state exposes the review action and prevents application during a running request", + "approved Unicode commands execute in the declared shell and retain Chinese output", + "authentication errors do not retry and error/diagnostic controls fit a 390 px viewport", + "stop cancels pending retry and clears running model state", + "a transient service failure recovers within the bounded retry policy" + ], + "pageErrors": [], + "requestFailures": [], + "modelValidation": "controlled local HTTP fixture; actual configured model is verified separately" +} \ No newline at end of file diff --git a/docs/m2-execution-ui-validation.json b/docs/m2-execution-ui-validation.json new file mode 100644 index 00000000..cc5b18e2 --- /dev/null +++ b/docs/m2-execution-ui-validation.json @@ -0,0 +1,19 @@ +{ + "success": true, + "version": "1.2.0", + "testedAt": "2026-10-29T08:38:36.258Z", + "browser": "156.0.4314.42", + "passed": [ + "model-selected checks wait for approval and display actual counted results", + "verified artifact preview shows the real check log and hash", + "changed source invalidates old checks and manual confirmation runs the new plan", + "390px task drawer, log preview, close controls and fixed composer remain operable", + "reconnection synchronizes missed session changes in other projects", + "budget controls pause before tools and preserve the goal across recorded runs", + "applied proposals continue the original task into actual engineering verification" + ], + "pageErrors": [], + "requestFailures": [], + "projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\execution-ui-1d074ed9-8f2d-43e2-b012-53bc79e39075\\project", + "model": "controlled local HTTP fixture" +} \ No newline at end of file diff --git a/docs/m2-tests-validation.json b/docs/m2-tests-validation.json new file mode 100644 index 00000000..be6e79c6 --- /dev/null +++ b/docs/m2-tests-validation.json @@ -0,0 +1,20 @@ +{ + "testedAt": "2026-10-29T08:36:56.5605637Z", + "firstRun": { + "pass": 90, + "tests": 92, + "fail": 2 + }, + "version": "1.2.0", + "node": "v24.22.1", + "tests": { + "fail": 0, + "cancelled": 0, + "skipped": 0, + "tests": 92, + "todo": 0, + "pass": 92 + }, + "success": true, + "tap": ".qa/m2-final-tests.tap" +} diff --git a/docs/m2-ui-validation.json b/docs/m2-ui-validation.json new file mode 100644 index 00000000..5006d611 --- /dev/null +++ b/docs/m2-ui-validation.json @@ -0,0 +1,27 @@ +{ + "success": true, + "url": "http://127.0.0.1:4321", + "browser": "Microsoft Edge 156.0.4314.42", + "date": "2026-10-29T08:37:57.844Z", + "projectRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\ui-625675d3-61be-48fe-bad6-0eee2a151b60\\ui-project", + "viewports": [ + 1440, + 780, + 390 + ], + "passed": [ + "project selection and real file preview", + "real command consent, execution and stale snapshot rejection", + "diff review and verified file application", + "manual editor creates a reviewable proposal", + "file responses stay with the current selection", + "denial, session selection, reload, stale response rejection and export", + "project inventory responses cannot replace another project", + "780 and 390 px: project drawer, file, diff and trace controls, no page overflow", + "unified and detailed research reports render", + "model list, ephemeral key, compatible fixture tool loop and return to offline mode" + ], + "pageErrors": [], + "requestFailures": [], + "modelValidation": "controlled local HTTP fixture; no real model" +} \ No newline at end of file diff --git a/docs/screenshots/delivery-desktop-review.png b/docs/screenshots/delivery-desktop-review.png new file mode 100644 index 00000000..728674cc Binary files /dev/null and b/docs/screenshots/delivery-desktop-review.png differ diff --git a/docs/screenshots/delivery-mobile-report.png b/docs/screenshots/delivery-mobile-report.png new file mode 100644 index 00000000..b5a894ed Binary files /dev/null and b/docs/screenshots/delivery-mobile-report.png differ diff --git a/findings.md b/findings.md index 51404361..551b923a 100644 --- a/findings.md +++ b/findings.md @@ -116,3 +116,25 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏 - M2 Git交付需新增sourceFingerprint:当前检查fingerprint包含HEAD/status,提交仅改变Git元数据也会导致旧指纹不同。源文件一致性与提交前Git准入基线需分开验证;提交只包含当前Task已应用的路径,已有暂存/工作区修改应保持。 - Git提交副作用要持久job身份、未知结果核对和不重放;新core kind在原进程热升级时也要补齐Map,不能因ensureStorage已初始化直接跳过。 - 新示例dist是构建产物,按具体路径加入ignore。首次补丁误用不存在的starter-project/node_modules行未写文件,已按实际/dist/锚点修正。 + +## M2持续实现 + +- 已核对main的3781591,恢复时工作区干净。1.1.0最终包验证结束,继续内置Git/交付报告切片;保留4318原进程和内存连接。 +- sourceFingerprint只绑定有界源码和工程声明;既有fingerprint继续绑定Git基线用于执行计划准入。检查完成后的有效性改用源指纹,提交本身不会让未变化源码的测试过期。 +- 提交采用独立树/索引准备与Git原子引用事务,提交计划明确展示署名、说明、路径、diff、检查与本地提交策略。仓库hooks/签名不在此切片执行;不使用git add .,不接收任意路径或远端操作。 +- 严格拒绝选中文件已有用户修改、暂存修改、链接/子模块/自定义内容过滤器和过期基线。其余工作区与索引条目保留。持久job记录准备/发布/完成阶段;引用结果未知时只能核对,不能重放。 +- 首个接续补丁包含空progress.md更新块,整个补丁未应用;删去空块后重新应用。 +- Git2.54引用事务探针要求symref-verify在no-deref模式运行;首轮事务被Git拒绝且未更新HEAD。补充option no-deref,并按明确的refs/heads引用更新后复验。 +- 后两次探针证实HEAD symref-verify和当前分支更新在同一Git事务被判重复引用,均没有提交。改用明确命名分支、持有HEAD.lock和index.lock,再由Git事务比较更新该分支;此切片拒绝detached HEAD,不用无法证明的引用协议。 +- 自持HEAD.lock也会阻止Git为当前分支加锁,探针未写引用。最终改为Git update-ref --stdin分阶段prepare/commit:由Git锁定HEAD及其分支,在prepare后核对实际symbolic HEAD,再决定commit或abort;无需自己改HEAD文件。 +- 最终分阶段引用事务探针通过。实际Git交付首3项检查通过,包含真实3失败→3通过、新文件/修改文件、无关staged+unstaged+untracked内容保留和Git元数据变化不使源码检查过期。 +- 工程检查专项18/18通过;Task/Run/Git互斥、热Store补Map和报告JSON/Markdown已接入。界面沿用DESIGN.md海松/纸白及固定三栏,新增实际交付步骤、只读确认、差异和报告入口,构建通过。 +- 首轮Git/恢复22项中20通过,9个实际退出切点全部通过。一个测试的注入器在“核对”时再次修改源码导致预期恢复失败,改为只注入一次;API报告检查发现需处理完成与报告生成之间的时序,正在补充统一完成状态。 +- API首轮404实际是job先显示completed而reportArtifactId还未保存,调用方读到undefined路径。新增持久reporting阶段,普通完成与报告工件同次保存;进程在报告阶段退出时保留已核对Git结果并明确报告可补生成。核对/报告操作也纳入项目互斥和停止等待。 +- 助手工具plan_delivery/delivery_report已接入,专项证明模型只能准备归属明确的预览/阶段报告,实际Git仍是独立用户确认;不因为模型提议就提交。 +- 首轮交付UI前8组通过,手机确认与报告、hash换行/差异滚动/固定输入区已目视核对。第9组发现点击已选中会话会把session清空,却因id不变不重新加载;修复同id选择不清空,并提供只读刷新。新增同会话重复点击验证,等待第9组恢复入口复验。 +- 源指纹增加“已跟踪但被删除”标记,保留用户既有删除时仍可核对其范围;不能读取的非排除路径会使快照不完整。Git读取/修复拒绝链接索引及链接任务路径,本机缺Git/项目未初始化提供可操作说明。 +- 第二轮交付UI前8组及同会话重复点击通过,第9组正确拒绝核对仍活着的原PID:测试把注入异常的seed和浏览器放在同一进程。改用真实子进程在提交后退出再启动UI宿主,使恢复样本符合实际生命周期;没有绕过原进程存活检查。 +- 最终交付UI9/9通过。完整92项首轮90通过:连续升级时版本白名单漏1.2.0;恢复校验调用Git时损坏索引会先产生不清楚的原始错误。补版本支持,并在提交对象校验前核对索引/遗留锁的原字节,提交校验后仍重检以保留并发变化防护。 +- 修复后15项恢复/升级专项和92项完整回归全部通过;基础10/诊断9/任务7/交付9组界面均通过且0页面/请求异常。新QA宿主4321/PID38288独立于4318原进程。 +- Git与报告完成状态必须同次保存;实际模型验收从旧的验收器自行提交改为确认工作台的持久Git job,并校验报告SHA256、commit和原owner索引。源码包验收脚本采用独立解压、离线npm安装和构建逐字节比较。 diff --git a/package-lock.json b/package-lock.json index 88de51a3..a05f45b7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "local-agent-workbench", - "version": "1.1.0", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "local-agent-workbench", - "version": "1.1.0", + "version": "1.2.0", "dependencies": { "diff": "^8.0.2", "lucide-react": "^0.548.0", diff --git a/package.json b/package.json index 4fdf2b2f..19e67cd5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "local-agent-workbench", - "version": "1.1.0", + "version": "1.2.0", "private": true, "type": "module", "description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.", diff --git a/progress.md b/progress.md index c4d8a07b..a075279a 100644 --- a/progress.md +++ b/progress.md @@ -93,3 +93,13 @@ - 真实模型四模块交付验证已启动,只操作独立合成工程,不使用原用户项目作为实验输入。界面新版本链接已提交给当前Codex面板。 - 真实模型验收81秒完成:1Task/2Run/1次四文件审查,14项测试由1通过/13失败变为14通过;build和dist CLI结果一致,9个保护输入与原owner改动保留。交付源文件commit b17492ca,详细结果与可运行样本已保存。 - 继续M2首个内置Git交付切片:1.1.0的提交由验收器执行,产品需要Task绑定的审查计划/commit job/报告及未知结果核对。工作台原连接保持,开发仍在源码/独立QA进行。 + +## 2026-10-29 M2全量接续与1.2.0验收 + +- 接续现有未提交实现;4318仍为原PID23080/1.1.0,保留内存模型连接。Node24.22.1与1.2.0构建通过。 +- 交付UI9/9通过,页面/请求异常均为零:四文件审查、实际14项测试、重复确认仅一提交、无关索引保留、报告字节下载、390px和真实退出恢复。同会话重复点击不再清空内容。 +- 上轮后台完整回归已完成:92项中90通过,0跳过/取消。失败为1.2.0重复升级的版本准入遗漏,以及外部破坏索引先被Git解析后出现原始错误。已补版本支持与索引/锁字节先行核对,保留提交对象验证后的二次核对。 +- 下一步先复验上述实际恢复/升级边界,随后完整回归、版本文档/便携与源码验收及原进程更新。后续继续M2工程理解、精确改动和多类工程能力。 +- 15/15恢复与连续升级专项、92/92最终完整回归均通过;基础10/诊断9/任务7/交付9组UI全部通过,0页面/请求异常。桌面预览与390px报告已目视核对并保存截图。 +- 更新真实模型验收器,使四模块样本的最终commit/JSON/Markdown报告通过工作台自身的plan/job/API生成,并新增无关staged文件保留验证。增加可重复使用的ZIP/源码独立安装构建验收脚本。 +- 保存记录和重启QA的组合命令被自动审批拦截,工具仅给出blocked by policy,没有执行该命令。已分别保存证据,并在独立4321端口/新数据目录启动QA;4318没有停止、连接没有读取或复制。 diff --git a/scripts/upgrade-running.mjs b/scripts/upgrade-running.mjs index 231522a4..23111f87 100644 --- a/scripts/upgrade-running.mjs +++ b/scripts/upgrade-running.mjs @@ -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'].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'].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 = []; diff --git a/scripts/verify-archives.py b/scripts/verify-archives.py new file mode 100644 index 00000000..9415cb22 --- /dev/null +++ b/scripts/verify-archives.py @@ -0,0 +1,63 @@ +import hashlib +import json +from datetime import datetime, timezone +from pathlib import Path, PurePosixPath +import sys +import uuid +import zipfile + +workspace = Path(__file__).resolve().parent.parent +release_dir = (workspace / 'releases').resolve() +release = json.loads((release_dir / 'latest.json').read_text(encoding='utf-8')) +records = [] +extraction_root = None +version = None + +for kind, root_key in [('portable', 'portableRoot'), ('source', 'sourceRoot')]: + root = Path(release[root_key]).resolve() + archive = Path(release[kind]['path']).resolve() + assert root.is_relative_to(release_dir) and archive.is_relative_to(release_dir) + archive_bytes = archive.read_bytes() + assert len(archive_bytes) == release[kind]['bytes'] + assert hashlib.sha256(archive_bytes).hexdigest() == release[kind]['sha256'] + manifest = json.loads((root / 'MANIFEST.json').read_text(encoding='utf-8')) + version = version or manifest['version'] + assert manifest['version'] == version and manifest['kind'] == kind + expected = {entry['path']: entry for entry in manifest['files']} + assert len(expected) == len(manifest['files']) + with zipfile.ZipFile(archive) as bundle: + assert bundle.testzip() is None, 'CRC failure' + actual = {} + for entry in bundle.infolist(): + name = PurePosixPath(entry.filename.replace('\\', '/')) + assert not name.is_absolute() and '..' not in name.parts and name.parts[0] == root.name + if entry.is_dir(): + continue + relative = str(PurePosixPath(*name.parts[1:])) + assert relative not in actual, 'Duplicate archive entry' + actual[relative] = entry + assert set(actual) == set(expected) | {'MANIFEST.json'} + for relative, entry in actual.items(): + contents = bundle.read(entry) + target = (root / relative).resolve() + assert target.is_relative_to(root) and contents == target.read_bytes(), relative + if relative != 'MANIFEST.json': + assert len(contents) == expected[relative]['bytes'] + assert hashlib.sha256(contents).hexdigest() == expected[relative]['sha256'] + if kind == 'source' and '--extract-source' in sys.argv: + isolated = (workspace / '.qa' / ('source-check-' + uuid.uuid4().hex)).resolve() + assert isolated.is_relative_to((workspace / '.qa').resolve()) + isolated.mkdir(parents=True, exist_ok=False) + for entry in bundle.infolist(): + target = (isolated / entry.filename.replace('\\', '/')).resolve() + assert target.is_relative_to(isolated) + bundle.extractall(isolated) + extraction_root = str(isolated / root.name) + records.append({'kind': kind, 'path': str(archive), 'files': len(expected), 'crcPassed': True, + 'manifestAndDirectoryMatch': True, 'sha256': release[kind]['sha256']}) + +result = {'success': True, 'version': version, 'testedAt': datetime.now(timezone.utc).isoformat(), + 'archives': records, 'extractionRoot': extraction_root} +(workspace / '.qa').mkdir(exist_ok=True) +(workspace / '.qa/archives-validation.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8') +print(json.dumps(result, ensure_ascii=True)) diff --git a/scripts/verify-delivery-ui.mjs b/scripts/verify-delivery-ui.mjs new file mode 100644 index 00000000..63d09250 --- /dev/null +++ b/scripts/verify-delivery-ui.mjs @@ -0,0 +1,212 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import http from 'node:http'; +import assert from 'node:assert/strict'; +import { createHash, randomUUID } from 'node:crypto'; +import { spawn, execFileSync } from 'node:child_process'; +import { chromium, expect } from 'playwright/test'; +import { Store } from '../src/server/store.mjs'; +import { GitDelivery } from '../src/core/git-delivery.mjs'; +import { gitEnvironment } from '../src/core/git-process.mjs'; +import { checkedDelivery } from '../tests/fixtures/delivery-project.mjs'; + +// Owns an independent host and synthetic projects. It never connects to 4318. +const workspace = process.cwd(), root = path.resolve('.qa', 'delivery-ui-' + randomUUID()), data = path.join(root, 'data'); +const projectRoot = path.join(root, '四模块交付工程'), recoveryRoot = path.join(root, '提交恢复工程'); +const allowed = ['src/normalize.mjs', 'src/summary.mjs', 'src/render.mjs', 'src/cli.mjs']; +const bytesHash = value => createHash('sha256').update(value).digest('hex'); +fs.mkdirSync(root, { recursive: true }); fs.mkdirSync('.qa/screenshots', { recursive: true }); +fs.cpSync(path.join(workspace, 'benchmarks/node-delivery-v1/baseline'), projectRoot, { recursive: true }); +fs.writeFileSync(path.join(projectRoot, '.gitignore'), 'dist/\n'); +fs.writeFileSync(path.join(projectRoot, 'OWNER-NOTES.md'), 'Owner baseline notes\n'); +fs.writeFileSync(path.join(projectRoot, 'OWNER-STAGED.txt'), 'Owner baseline staged file\n'); +const git = args => execFileSync('git', ['--no-pager', '--no-optional-locks', '-C', projectRoot, ...args], { env: gitEnvironment(), encoding: 'utf8', windowsHide: true }); +const list = directory => fs.readdirSync(directory, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? list(path.join(directory, entry.name)) : [path.relative(projectRoot, path.join(directory, entry.name)).replaceAll('\\', '/')]); +const baselineFiles = list(projectRoot); +git(['init', '--initial-branch=main']); git(['config', 'core.autocrlf', 'false']); git(['config', 'user.name', 'Workbench UI QA']); git(['config', 'user.email', 'ui@workbench.invalid']); +git(['add', '--', ...baselineFiles]); git(['commit', '--no-gpg-sign', '-m', 'Sealed four-module UI input']); +const baselineHead = git(['rev-parse', 'HEAD']).trim(); +fs.appendFileSync(path.join(projectRoot, 'OWNER-NOTES.md'), 'Keep owner unstaged notes\n'); +fs.writeFileSync(path.join(projectRoot, 'OWNER-STAGED.txt'), 'Keep owner staged content\n'); git(['add', '--', 'OWNER-STAGED.txt']); +fs.appendFileSync(path.join(projectRoot, 'OWNER-STAGED.txt'), 'Keep later owner working copy\n'); +fs.writeFileSync(path.join(projectRoot, 'OWNER-UNTRACKED.txt'), 'Keep owner untracked file\n'); +const protectedFiles = [...baselineFiles.filter(relative => !allowed.includes(relative)), 'OWNER-UNTRACKED.txt']; +const protectedHashes = Object.fromEntries(protectedFiles.map(relative => [relative, bytesHash(fs.readFileSync(path.join(projectRoot, relative)))])); +const initialHashes = Object.fromEntries(allowed.map(relative => [relative, bytesHash(fs.readFileSync(path.join(projectRoot, relative)))])); +const repairs = Object.fromEntries(allowed.map(relative => [relative, fs.readFileSync(path.join(workspace, 'examples/delivery-report', relative), 'utf8')])); +const store = new Store(data), primary = store.addProject(projectRoot); +fs.mkdirSync(recoveryRoot); +fs.writeFileSync(path.join(recoveryRoot, 'README.md'), '# Recovery UI fixture\n'); +const recoveryProject = store.addProject(recoveryRoot), recoverySession = store.createSession(recoveryProject.id), seedCleanup = []; +const f = { root, projectRoot: recoveryRoot, data, store, project: recoveryProject, session: recoverySession, onCleanup: fn => seedCleanup.push(fn) }; +await checkedDelivery(f); +recoverySession.title = 'Git中断核对样本'; store.save(recoverySession); +const recoveryAdapter = new GitDelivery(store, { faultInjector: phase => { if (phase === 'committed') throw new Error('Controlled lost acknowledgement after actual publication'); } }); +const recoveryPlan = await recoveryAdapter.plan(recoverySession); +for (const cleanup of seedCleanup) await cleanup(); store.close(); +const exited = spawn(process.execPath, [path.join(workspace, 'tests/fixtures/delivery-crash-worker.mjs'), data, recoverySession.id, recoveryPlan.id, 'committed'], + { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); +let exitOutput = '', exitErrors = ''; +exited.stdout.on('data', bytes => { exitOutput += bytes.toString('utf8'); }); exited.stderr.on('data', bytes => { exitErrors += bytes.toString('utf8'); }); +assert.equal(await new Promise(resolve => exited.once('close', resolve)), 73, exitErrors); +const crashed = JSON.parse(exitOutput.trim()), recoveredStore = new Store(data), recoveryJob = structuredClone(recoveredStore.owned('delivery_job', crashed.jobId, recoverySession.id)); +assert.equal(recoveryJob.status, 'unknown'); recoveredStore.close(); + +let modelMode = 'initial'; +const model = http.createServer(async (request, response) => { + try { + const chunks = []; for await (const chunk of request) chunks.push(chunk); + const input = JSON.parse(Buffer.concat(chunks).toString('utf8')); + const last = input.messages.findLastIndex(item => item.role === 'user'); + const results = input.messages.slice(last + 1).filter(item => item.role === 'tool').map(item => JSON.parse(item.content)); + const plan = results.find(value => value.checks && value.fingerprint); + let calls = []; + if (!results.length) calls = [['inspect_project', {}]]; + else if (results.length === 1) calls = [['plan_checks', {}]]; + else if (results.length === 2) calls = [['run_checks', { plan_id: plan.id }]]; + else if (results.length === 3 && modelMode === 'initial') calls = allowed.map(relative => ['propose_file', { path: relative, content: repairs[relative], base_sha256: initialHashes[relative], reason: 'Controlled four-module repair after actual failure logs' }]); + else if (results.length === 3 && modelMode === 'final') calls = [['plan_delivery', { message: 'feat: prepare verified four-module delivery' }]]; + else if (results.length === 4 && modelMode === 'final') calls = [['delivery_report', {}]]; + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ choices: [{ message: { role: 'assistant', content: calls.length ? '' : modelMode === 'initial' ? '四个文件已准备提案,等待审查。' : '实际14项测试和构建通过,Git预览已准备,等待确认。', + ...(calls.length ? { tool_calls: calls.map(([name, args]) => ({ id: randomUUID(), type: 'function', function: { name, arguments: JSON.stringify(args) } })) } : {}) }, + finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 40, completion_tokens: 20, total_tokens: 60 } })); + } catch (error) { response.writeHead(500, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ error: { message: error.message } })); } +}); +await new Promise(resolve => model.listen(0, '127.0.0.1', resolve)); +const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: workspace, AGENT_WORKBENCH_DATA_DIR: data, AGENT_WORKBENCH_PORT: '0' }; delete env.AGENT_WORKBENCH_API_KEY; +const host = spawn(process.execPath, ['dist-server/server.mjs'], { cwd: workspace, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); +let url = '', hostOutput = '', hostErrors = ''; +host.stdout.on('data', bytes => { hostOutput += bytes.toString('utf8'); for (const line of hostOutput.split('\n')) { try { const value = JSON.parse(line); if (value.ready) url = value.url; } catch {} } }); +host.stderr.on('data', bytes => { hostErrors += bytes.toString('utf8'); }); +const until = async predicate => { const deadline = Date.now() + 20000; while (!(await predicate())) { if (Date.now() > deadline) throw new Error('QA host state timeout: ' + hostErrors); await new Promise(resolve => setTimeout(resolve, 20)); } }; +await until(() => url || host.exitCode !== null); assert.ok(url, hostErrors); assert.notEqual(new URL(url).port, '4318'); +const bootstrap = await (await fetch(url + '/api/bootstrap')).json(); +const api = async (route, input) => { + const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' }, ...(input === undefined ? {} : { body: JSON.stringify(input) }) }); + const result = await response.json(); assert.ok(response.ok, result.error); return result; +}; +await api('/config', { ...bootstrap.config, mode: 'compatible', model: 'delivery-ui-controlled-fixture', baseUrl: 'http://127.0.0.1:' + model.address().port + '/v1', apiKey: 'delivery-ui-volatile-fixture-key' }); +const browser = await chromium.launch({ executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); +const page = await context.newPage(), passed = [], pageErrors = [], requestFailures = [], confirmations = []; +page.on('pageerror', error => pageErrors.push(error.message)); +page.on('requestfailed', request => requestFailures.push(request.url() + ': ' + request.failure()?.errorText)); +page.on('request', request => { if (request.method() === 'POST' && /\/delivery-jobs$/.test(new URL(request.url()).pathname)) confirmations.push(request.postDataJSON().planId); }); +const mark = text => { passed.push(text); console.log('PASS ' + text); }; +const screenshot = name => page.screenshot({ path: '.qa/screenshots/' + name + '.png', scale: 'css' }); +const task = () => page.getByLabel('任务记录', { exact: true }); +const delivery = () => task().getByLabel('Git交付', { exact: true }); +const confirm = () => page.getByRole('dialog', { name: '确认本地Git提交', exact: true }); +const artifact = () => page.getByRole('dialog', { name: '执行结果工件', exact: true }); +let sessionId = ''; +const state = () => api('/sessions/' + sessionId); +const waitStatus = status => expect.poll(async () => (await state()).status, { timeout: 30000 }).toBe(status); +try { + await page.goto(url); await page.waitForLoadState('networkidle'); + await page.getByLabel('当前项目').selectOption(primary.id); + await page.getByRole('button', { name: '新建任务', exact: true }).click(); + await page.getByLabel('任务内容').fill('修复四模块并交付Git报告'); await page.getByRole('button', { name: '发送任务' }).click(); + await expect.poll(async () => (await api('/sessions')).find(value => value.title === '修复四模块并交付Git报告')?.id).toBeTruthy(); + sessionId = (await api('/sessions')).find(value => value.title === '修复四模块并交付Git报告').id; + await waitStatus('awaiting_approval'); await page.getByRole('button', { name: '确认执行', exact: true }).click(); await waitStatus('needs_review'); + const reviewed = await state(); assert.equal(reviewed.execution.checks[0].results[0].tests.failed, 13); + await page.getByRole('button', { name: '查看任务记录' }).click(); await expect(task()).toContainText('13'); + assert.equal(git(['rev-parse', 'HEAD']).trim(), baselineHead); + mark('actual failing tests and four source proposals retain the original project and task'); + await page.locator('.inspector-tabs').getByRole('button', { name: /改动/ }).click(); + for (const relative of allowed) { + await page.locator('.change-list').getByRole('button').filter({ hasText: relative }).click(); + await page.getByRole('button', { name: '应用这项改动', exact: true }).click(); + } + await waitStatus('completed'); modelMode = 'final'; await page.getByRole('button', { name: '继续检查与交付', exact: true }).click(); + await waitStatus('awaiting_approval'); await page.getByRole('button', { name: '确认执行', exact: true }).click(); await waitStatus('completed'); + const verified = await state(); assert.equal(verified.execution.task.id, reviewed.execution.task.id); assert.equal(verified.execution.checks.at(-1).status, 'passed'); + assert.equal(verified.execution.checks.at(-1).results[0].tests.passed, 14); assert.equal(verified.execution.deliveries.length, 0); + assert.equal(verified.execution.deliveryPlans.at(-1).preparedBy, 'agent'); + await page.getByRole('button', { name: '查看任务记录' }).click(); await expect(task()).toContainText('测试 14/14 通过'); + await page.locator('.session-select').filter({ hasText: '修复四模块并交付Git报告' }).click(); + await expect(task()).toContainText('测试 14/14 通过'); + mark('reviewed changes continue the same Task through 14 real tests and model-prepared Git review'); + + await delivery().getByLabel('提交说明', { exact: true }).fill('feat: ship the reviewed four-module delivery'); + await delivery().getByText('Git署名', { exact: true }).click(); await delivery().getByLabel('提交者姓名').fill('UI Reviewer'); await delivery().getByLabel('提交者邮箱').fill('reviewer@workbench.invalid'); + await delivery().getByRole('button', { name: '预览Git提交', exact: true }).click(); await expect(confirm()).toBeVisible(); + await expect(confirm()).toContainText('UI Reviewer'); await expect(confirm()).toContainText('14/14'); await expect(confirm()).toContainText(baselineHead.slice(0, 12)); await expect(confirm()).toContainText('不执行仓库hooks'); + for (const relative of allowed) { await confirm().locator('summary').filter({ hasText: relative }).click(); await expect(confirm().getByLabel('提交差异 ' + relative, { exact: true })).toBeVisible(); } + await confirm().locator('.delivery-confirm').evaluate(element => { element.scrollTop = 0; }); + await screenshot('delivery-desktop-review'); + await page.keyboard.press('Escape'); await expect(confirm()).not.toBeVisible(); assert.equal(git(['rev-parse', 'HEAD']).trim(), baselineHead); + mark('review shows actual paths, diffs, tests, author and policy; cancelling leaves Git unchanged'); + + await delivery().getByRole('button', { name: '预览Git提交', exact: true }).click(); await expect(confirm()).toBeVisible(); + git(['add', '--', 'OWNER-NOTES.md']); const protectedStage = git(['show', ':OWNER-STAGED.txt']), stagedNotes = git(['show', ':OWNER-NOTES.md']); + await confirm().getByRole('button', { name: '确认创建本地提交', exact: true }).click(); + await expect.poll(async () => (await state()).execution.deliveries.at(-1)?.status, { timeout: 20000 }).toBe('stale'); + await expect(delivery()).toContainText('提交预览后'); assert.equal(git(['rev-parse', 'HEAD']).trim(), baselineHead); + assert.equal(git(['show', ':OWNER-STAGED.txt']), protectedStage); assert.equal(git(['show', ':OWNER-NOTES.md']), stagedNotes); + mark('an index change after confirmation preview refuses the stale job and preserves both staged owners'); + + await delivery().getByRole('button', { name: '预览Git提交', exact: true }).click(); await expect(confirm()).toBeVisible(); + await page.setViewportSize({ width: 390, height: 844 }); await expect(confirm()).toBeVisible(); + await confirm().locator('summary').filter({ hasText: 'src/normalize.mjs' }).click(); + await screenshot('delivery-mobile-review'); + const box = await confirm().boundingBox(), confirmButton = await confirm().getByRole('button', { name: '确认创建本地提交', exact: true }).boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= 391 && box.y >= 0 && box.y + box.height <= 845); + assert.ok(confirmButton.x >= 0 && confirmButton.x + confirmButton.width <= 391); + assert.ok(await confirm().evaluate(element => element.scrollWidth <= element.clientWidth + 1)); + mark('390px confirmation keeps file hashes, diffs and actions inside the modal'); + await page.setViewportSize({ width: 1440, height: 1000 }); + await confirm().getByRole('button', { name: '确认创建本地提交', exact: true }).dblclick(); + await expect.poll(async () => (await state()).execution.deliveries.at(-1)?.status, { timeout: 25000 }).toBe('completed'); + const delivered = await state(), job = delivered.execution.deliveries.at(-1); + assert.equal(confirmations.filter(value => value === job.planId).length, 1); + assert.equal(job.workspacePreserved, true); assert.equal(job.indexPreserved, true); assert.equal(git(['rev-list', '--count', 'HEAD']).trim(), '2'); + assert.equal(git(['show', ':OWNER-STAGED.txt']), protectedStage); assert.equal(git(['show', ':OWNER-NOTES.md']), stagedNotes); + for (const [relative, expected] of Object.entries(protectedHashes)) assert.equal(bytesHash(fs.readFileSync(path.join(projectRoot, relative))), expected); + assert.deepEqual(git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD']).trim().split('\n').sort(), allowed.slice().sort()); + await expect(delivery()).toContainText(job.commit); await expect(delivery()).toContainText('实际提交已核对'); await screenshot('delivery-desktop-result'); + mark('double confirmation creates one four-file commit, retains owner bytes and publishes report with completion'); + + const jobCard = delivery().locator('.delivery-job').filter({ hasText: job.commit }); + await jobCard.getByRole('button', { name: '查看交付报告', exact: true }).click(); await expect(artifact()).toContainText('检查通过并已提交'); await expect(artifact()).toContainText('14/14'); + await screenshot('delivery-desktop-report'); await artifact().getByRole('button', { name: '关闭窗口' }).click(); + for (const [label, id, extension] of [['下载Markdown', job.reportMarkdownArtifactId, '.md'], ['下载JSON', job.reportArtifactId, '.json']]) { + const event = page.waitForEvent('download'); await jobCard.getByRole('button', { name: label, exact: true }).click(); const download = await event; + const target = path.join(root, 'download' + extension); await download.saveAs(target); + const meta = await api('/artifacts/' + id + '?session=' + sessionId); assert.equal(bytesHash(fs.readFileSync(target)), meta.sha256); + if (extension === '.json') assert.equal(JSON.parse(fs.readFileSync(target, 'utf8')).status, 'verified_committed'); + } + mark('report viewing and Markdown/JSON downloads preserve verified artifact bytes and truthful acceptance limits'); + + await page.setViewportSize({ width: 390, height: 844 }); await page.getByRole('button', { name: '查看任务记录' }).click(); + await delivery().getByRole('button', { name: '查看最新报告', exact: true }).click(); await expect(artifact()).toBeVisible(); await screenshot('delivery-mobile-report'); + await artifact().getByRole('button', { name: '关闭窗口' }).click(); await page.getByRole('button', { name: '关闭检视区' }).click(); + const composer = await page.getByLabel('任务内容').boundingBox(); assert.ok(composer.y >= 0 && composer.y + composer.height <= 844); + assert.ok(await page.locator('body').evaluate(element => element.scrollWidth <= 390)); mark('mobile report preview closes cleanly and keeps the task input fixed'); + + await page.setViewportSize({ width: 1440, height: 1000 }); + if (!await page.getByLabel('当前项目').isVisible()) await page.getByRole('button', { name: '展开项目栏' }).click(); + await page.getByLabel('当前项目').selectOption(recoveryProject.id); await page.locator('.session-select').filter({ hasText: 'Git中断核对样本' }).click(); + await page.getByRole('button', { name: '查看任务记录' }).click(); await expect(delivery()).toContainText('结果待核对'); + await expect(delivery().getByRole('button', { name: '预览Git提交', exact: true })).toBeDisabled(); await screenshot('delivery-unknown-result'); + await delivery().getByRole('button', { name: '核对提交结果', exact: true }).click(); + await expect.poll(async () => (await api('/sessions/' + recoverySession.id)).execution.deliveries[0].status, { timeout: 15000 }).toBe('completed'); + const recovered = await api('/sessions/' + recoverySession.id); + assert.equal(recovered.execution.deliveries[0].commit, recoveryJob.expectedCommit); assert.equal(fs.existsSync(path.join(recoveryRoot, '.git/index.lock')), false); + await expect(delivery()).toContainText('没有重新执行提交'); await screenshot('delivery-reconciled-result'); + mark('unknown Git results block new submission and the explicit reconcile action restores the existing commit'); + + assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []); + const result = { success: true, version: bootstrap.version, testedAt: new Date().toISOString(), browser: browser.version(), passed, pageErrors, requestFailures, + projectRoot, projectId: primary.id, sessionId, taskId: reviewed.execution.task.id, commit: job.commit, recoveryCommit: recoveryJob.expectedCommit, + testCounts: { baselineFailed: 13, passed: 14 }, model: 'controlled local HTTP fixture', confirmations: confirmations.length }; + fs.writeFileSync('.qa/delivery-ui-validation.json', JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2)); +} catch (error) { + await screenshot('delivery-ui-failure').catch(() => {}); fs.writeFileSync('.qa/delivery-ui-failure-dom.html', await page.content().catch(() => '')); + fs.writeFileSync('.qa/delivery-ui-validation.json', JSON.stringify({ success: false, error: error.message, passed, pageErrors, requestFailures, root, url }, null, 2)); + throw error; +} finally { + await browser.close(); await api('/shutdown', {}).catch(() => {}); await until(() => host.exitCode !== null).catch(() => host.kill()); + model.closeAllConnections(); await new Promise(resolve => model.close(resolve)); +} diff --git a/scripts/verify-live-delivery.mjs b/scripts/verify-live-delivery.mjs index ab47a891..be076ab1 100644 --- a/scripts/verify-live-delivery.mjs +++ b/scripts/verify-live-delivery.mjs @@ -3,6 +3,7 @@ import path from 'node:path'; import assert from 'node:assert/strict'; import { createHash, randomUUID } from 'node:crypto'; import { execFileSync, spawnSync } from 'node:child_process'; +import { APP_VERSION } from '../src/server/diagnostics.mjs'; // Operates only on a fresh synthetic project. The configured model remains in // the running host; bootstrap contains an API session token, never its model key. @@ -11,7 +12,7 @@ const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4318'; const origin = new URL(url); assert.equal(origin.hostname, '127.0.0.1'); assert.equal(origin.protocol, 'http:'); const bootstrap = await (await fetch(origin.origin + '/api/bootstrap')).json(); -assert.equal(bootstrap.version, '1.1.0'); assert.equal(bootstrap.config.mode, 'compatible'); +assert.equal(bootstrap.version, APP_VERSION); assert.equal(bootstrap.config.mode, 'compatible'); assert.ok(bootstrap.config.model, 'Configure a model on the running Workbench first.'); const api = async (route, input) => { const response = await fetch(origin.origin + '/api' + route, { method: input === undefined ? 'GET' : 'POST', @@ -30,19 +31,24 @@ fs.mkdirSync(caseRoot, { recursive: true }); fs.cpSync(path.join(workspace, 'benchmarks/node-delivery-v1/baseline'), projectRoot, { recursive: true }); fs.writeFileSync(path.join(projectRoot, '.gitignore'), 'dist/\n'); fs.writeFileSync(path.join(projectRoot, 'OWNER-NOTES.md'), '# Owner notes\nBaseline owner content.\n'); +fs.writeFileSync(path.join(projectRoot, 'OWNER-STAGED.txt'), 'Baseline staged owner content.\n'); const git = args => execFileSync('git', ['-c', 'core.autocrlf=false', '-c', 'user.name=Agent Workbench QA', '-c', 'user.email=qa@workbench.local', '-C', projectRoot, ...args], { encoding: 'utf8', windowsHide: true }); git(['init', '--initial-branch=main']); git(['add', '.']); git(['commit', '-m', 'test: seal delivery-report acceptance baseline']); const baselineCommit = git(['rev-parse', 'HEAD']).trim(); fs.appendFileSync(path.join(projectRoot, 'OWNER-NOTES.md'), 'Existing owner edit: ' + randomUUID() + '\n'); fs.writeFileSync(path.join(projectRoot, 'UNTRACKED-OWNER.txt'), 'Existing untracked owner file: ' + randomUUID() + '\n'); +fs.appendFileSync(path.join(projectRoot, 'OWNER-STAGED.txt'), 'Existing staged owner edit: ' + randomUUID() + '\n'); +git(['add', '--', 'OWNER-STAGED.txt']); const sha = file => createHash('sha256').update(fs.readFileSync(path.join(projectRoot, file))).digest('hex'); -const protectedPaths = ['README.md', 'package.json', 'test/delivery.test.mjs', 'scripts/build.mjs', 'fixtures/tasks.json', 'fixtures/invalid.json', '.gitignore', 'OWNER-NOTES.md', 'UNTRACKED-OWNER.txt']; +const protectedPaths = ['README.md', 'package.json', 'test/delivery.test.mjs', 'scripts/build.mjs', 'fixtures/tasks.json', 'fixtures/invalid.json', '.gitignore', 'OWNER-NOTES.md', 'OWNER-STAGED.txt', 'UNTRACKED-OWNER.txt']; const protectedHashes = Object.fromEntries(protectedPaths.map(file => [file, sha(file)])); const beforeSources = Object.fromEntries(allowed.map(file => [file, sha(file)])); const ownerDiff = git(['diff', '--', 'OWNER-NOTES.md']); +const ownerStagedDiff = git(['diff', '--cached', '--', 'OWNER-STAGED.txt']); const assertProtected = () => { for (const [file, hash] of Object.entries(protectedHashes)) assert.equal(sha(file), hash, 'Protected input changed: ' + file); assert.equal(git(['diff', '--', 'OWNER-NOTES.md']), ownerDiff, 'Existing owner edits changed.'); + assert.equal(git(['diff', '--cached', '--', 'OWNER-STAGED.txt']), ownerStagedDiff, 'Existing owner stage changed.'); }; const project = await api('/projects', { root: projectRoot }); const session = await api('/sessions', { projectId: project.id }); @@ -60,7 +66,7 @@ try { '依据实际失败读取有关文件,使用 read_artifact 进一步核对失败日志。只能用 propose_file 修改 src/normalize.mjs、src/summary.mjs、src/render.mjs、src/cli.mjs;' + '测试、fixtures、构建脚本、package.json、README 和 OWNER 文件必须保留。四模块都需修复,不能修改验收来通过。' + '本工程没有第三方依赖,不用安装。不要使用 run_command、不要自己提交Git;本轮终端仅通过已识别的npm检查计划运行。' + - '提案等待审查应用,随后继续同一目标并实际重新运行 test/build,依据日志修复直至通过;最后用中文报告实际测试数量、构建结果和改动。' }); + '提案等待审查应用,随后继续同一目标并实际重新运行 test/build,依据日志修复直至通过。检查通过后用 plan_delivery 准备本Task的四文件本地Git预览,等待用户独立确认;最后用中文报告实际测试数量、构建结果和改动。' }); while (Date.now() - started < 720000) { state = await api('/sessions/' + session.id); originalTaskId ??= state.execution.task.id; assert.equal(state.execution.task.id, originalTaskId, 'Engineering delivery must retain the original Task.'); @@ -118,8 +124,38 @@ try { assert.equal(built.status, 0); assert.equal(built.stderr, ''); assert.deepEqual(JSON.parse(built.stdout), { total: 4, counts: { todo: 0, doing: 1, done: 2, blocked: 1 }, completedPercent: 50, remainingMinutes: 50 }); const diff = git(['diff', '--', ...allowed]); assert.ok(diff.length > 0); fs.writeFileSync(path.join(caseRoot, 'reviewed-changes.diff'), diff); - git(['add', '--', ...allowed]); git(['commit', '--only', '-m', 'feat: repair delivery report with 14 verified acceptance cases', '--', ...allowed]); - const deliveredCommit = git(['rev-parse', 'HEAD']).trim(); assert.notEqual(deliveredCommit, baselineCommit); assertProtected(); + let deliveryPlan = state.execution.deliveryPlans?.filter(plan => plan.status === 'planned' && plan.taskId === originalTaskId && plan.runId === state.runId).at(-1); + if (!deliveryPlan) { + state = await api('/sessions/' + session.id + '/delivery-plans', { message: 'feat: repair delivery report with 14 verified acceptance cases' }); + deliveryPlan = state.execution.deliveryPlans.at(-1); + } + assert.deepEqual(deliveryPlan.paths.slice().sort(), allowed.slice().sort()); + assert.equal(deliveryPlan.checkJobId, passedJob.id); assert.equal(deliveryPlan.sourceFingerprint, passedJob.sourceFingerprint); + assert.equal(git(['rev-parse', 'HEAD']).trim(), baselineCommit); assertProtected(); + const queued = await api('/sessions/' + session.id + '/delivery-jobs', { planId: deliveryPlan.id }); + const deliveryJobId = queued.execution.deliveries.at(-1).id; + let deliveryJob; + for (let attempt = 0; attempt < 120; attempt++) { + deliveryJob = await api('/sessions/' + session.id + '/delivery-jobs/' + deliveryJobId); + if (!['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(deliveryJob.status)) break; + await new Promise(resolve => setTimeout(resolve, 500)); + } + assert.equal(deliveryJob.status, 'completed', deliveryJob.summary); assert.ok(deliveryJob.reportArtifactId); assert.ok(deliveryJob.reportMarkdownArtifactId); + const deliveredCommit = git(['rev-parse', 'HEAD']).trim(); assert.equal(deliveredCommit, deliveryJob.commit); + assert.notEqual(deliveredCommit, baselineCommit); assertProtected(); + assert.equal(git(['rev-list', '--count', 'HEAD']).trim(), '2'); + const readArtifact = async id => { + let offset = 0, content = '', artifact; + do { artifact = await api('/artifacts/' + id + '?session=' + session.id + '&offset=' + offset + '&limit=16000'); content += artifact.content; offset += artifact.content.length; } while (artifact.truncated && artifact.content.length); + assert.equal(createHash('sha256').update(content).digest('hex'), artifact.sha256); + return content; + }; + const deliveryJson = await readArtifact(deliveryJob.reportArtifactId), deliveryMarkdown = await readArtifact(deliveryJob.reportMarkdownArtifactId); + const report = JSON.parse(deliveryJson); assert.equal(report.status, 'verified_committed'); assert.equal(report.task.id, originalTaskId); + assert.equal(report.verifiedCheckJobId, passedJob.id); assert.equal(report.deliveries.at(-1).commit, deliveredCommit); + assert.equal(report.task.requirementsAcceptance, 'not_recorded'); assert.match(deliveryMarkdown, /14\/14/); + fs.writeFileSync(path.join(caseRoot, 'delivery-report.json'), deliveryJson); fs.writeFileSync(path.join(caseRoot, 'delivery-report.md'), deliveryMarkdown); + state = await api('/sessions/' + session.id); assert.deepEqual(git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD']).trim().split(/\r?\n/).sort(), [...allowed].sort()); const exported = await api('/sessions/' + session.id + '/export'); fs.writeFileSync(path.join(caseRoot, 'session.json'), JSON.stringify(exported, null, 2)); @@ -130,12 +166,12 @@ try { fs.writeFileSync(path.join(caseRoot, job.id + '-' + result.name + '.log'), text); } const result = { success: true, version: bootstrap.version, testedAt: new Date().toISOString(), model: bootstrap.config.model, - projectRoot, projectId: project.id, sessionId: session.id, taskId: originalTaskId, baselineCommit, deliveredCommit, + projectRoot, projectId: project.id, sessionId: session.id, taskId: originalTaskId, baselineCommit, deliveredCommit, deliveryPlan, deliveryJob, elapsedSeconds: Math.round((Date.now() - started) / 1000), runs: state.execution.runs.length, reviewRounds: reviewedRounds, applied, - protectedHashes, ownerEditsPreserved: true, buildOutput: JSON.parse(built.stdout), usage: state.execution.task.usage, + protectedHashes, ownerEditsPreserved: true, ownerStagePreserved: true, reportStatus: report.status, reportPath: path.join(caseRoot, 'delivery-report.md'), buildOutput: JSON.parse(built.stdout), usage: state.execution.task.usage, checks: state.execution.checks, decisions, diffPath: path.join(caseRoot, 'reviewed-changes.diff'), sessionPath: path.join(caseRoot, 'session.json'), credentialsHandling: 'Calls use the running host model configuration; no model key was read, copied or saved.', - intervention: 'Verifier approved only sealed npm scripts, checked four source proposals and applied them; implementation came from the configured model. The verifier saved a source-only local Git commit.', + intervention: 'Verifier approved only sealed npm scripts, reviewed and applied four source proposals, and confirmed an owned Git preview through the Workbench API. Implementation came from the configured model; the Workbench generated and verified the commit and evidence reports.', scope: 'One synthetic Node engineering sample; does not establish M2 or M6 delivery success rates.' }; saveEvidence(result); succeeded = true; console.log(JSON.stringify({ success: true, model: result.model, testsPassed: 14, buildPassed: true, deliveredCommit, elapsedSeconds: result.elapsedSeconds, reviewRounds: reviewedRounds, projectRoot, sessionId: session.id }, null, 2)); diff --git a/scripts/verify-live-session.mjs b/scripts/verify-live-session.mjs index de8e903b..173c11b4 100644 --- a/scripts/verify-live-session.mjs +++ b/scripts/verify-live-session.mjs @@ -6,7 +6,7 @@ import { createHash } from 'node:crypto'; const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4318'; const sessionId = process.env.AGENT_WORKBENCH_SESSION || '569c9457-d399-46e6-b53e-4b1fdbb02109'; const bootstrap = await (await fetch(url + '/api/bootstrap')).json(); -assert.ok(['1.0.0', '1.1.0'].includes(bootstrap.version)); +assert.ok(['1.0.0', '1.1.0', '1.2.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'compatible'); assert.ok(bootstrap.config.hasKey, 'The existing in-memory connection must be present.'); const api = async (route, input) => { diff --git a/scripts/verify-source-package.mjs b/scripts/verify-source-package.mjs new file mode 100644 index 00000000..de50f097 --- /dev/null +++ b/scripts/verify-source-package.mjs @@ -0,0 +1,54 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { spawn } from 'node:child_process'; + +const workspace = process.cwd(); +const evidence = JSON.parse(fs.readFileSync('.qa/archives-validation.json', 'utf8')); +assert.equal(evidence.success, true); +assert.ok(evidence.extractionRoot, 'Run python scripts/verify-archives.py --extract-source first.'); +const sourceRoot = fs.realpathSync.native(evidence.extractionRoot); +assert.ok(sourceRoot.startsWith(path.resolve('.qa') + path.sep)); +const npmCli = path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'); +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 expected = Object.fromEntries(['dist-client', 'dist-server'].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)$/i; +const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => allowedEnv.test(key))); +let stage = 'install'; +const resultFile = path.join(workspace, '.qa/source-package-validation.json'); + +function run(args, logName) { + console.log('Source package: ' + stage); + return new Promise((resolve, reject) => { + const outputFile = fs.createWriteStream(path.join(sourceRoot, logName)); + const child = spawn(process.execPath, args, { cwd: sourceRoot, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + let tail = ''; + const capture = bytes => { outputFile.write(bytes); tail = (tail + bytes.toString('utf8')).slice(-12000); }; + child.stdout.on('data', capture); child.stderr.on('data', capture); + const timer = setTimeout(() => child.kill(), 600000); + child.once('error', error => { clearTimeout(timer); outputFile.end(); reject(error); }); + child.once('close', code => { clearTimeout(timer); outputFile.end(); code === 0 ? resolve(tail) : reject(new Error(stage + ' failed (' + code + '): ' + tail)); }); + }); +} + +try { + await run([npmCli, 'ci', '--offline', '--no-audit', '--no-fund'], 'install.log'); + stage = 'build'; await run([npmCli, 'run', 'build'], 'build.log'); + const actualFiles = ['dist-client', 'dist-server'].flatMap(folder => files(path.join(sourceRoot, folder)).map(relative => path.join(folder, relative))); + 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); + stage = 'tests'; + const output = await run(['--test', '--test-concurrency=2', '--test-reporter=tap', ...files(path.join(sourceRoot, 'tests')).filter(file => !file.includes(path.sep) && file.endsWith('.test.mjs')).map(file => path.join('tests', file))], 'tests.tap'); + const stats = Object.fromEntries([...output.matchAll(/^# (tests|pass|fail|cancelled|skipped|todo) (\d+)\s*$/gm)].map(match => [match[1], Number(match[2])])); + assert.ok(stats.tests > 0); assert.equal(stats.pass, stats.tests); for (const key of ['fail', 'cancelled', 'skipped', 'todo']) assert.equal(stats[key], 0); + const result = { success: true, version: evidence.version, testedAt: new Date().toISOString(), sourceRoot, offlineInstall: true, + buildMatchedFiles: Object.keys(expected).length, tests: stats, credentialsHandling: 'Only build/runtime environment paths are inherited; no model configuration or credentials are used.' }; + fs.writeFileSync(resultFile, JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2)); +} catch (error) { + fs.writeFileSync(resultFile, JSON.stringify({ success: false, version: evidence.version, stage, error: error.message, sourceRoot }, null, 2)); + throw error; +} diff --git a/src/client/App.tsx b/src/client/App.tsx index 57847973..376ce387 100644 --- a/src/client/App.tsx +++ b/src/client/App.tsx @@ -11,7 +11,7 @@ const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v export default function App() { const [token, setAccess] = useState(''); - const [version, setVersion] = useState('1.1.0'); + const [version, setVersion] = useState('1.2.0'); const [diagnosticsOpen, setDiagnosticsOpen] = useState(false); const [diagnostics, setDiagnostics] = useState(null); const [diagnosticsBusy, setDiagnosticsBusy] = useState(false); @@ -71,7 +71,8 @@ export default function App() { const reportRequest = useRef(0); const sessionCreation = useRef | null>(null); const selectedProject = projects.find(project => project.id === projectId); - const isRunning = !!session && (activeStates.includes(session.status) || session.execution?.checks.some(job => ['queued', 'running'].includes(job.status)) === true); + const isRunning = !!session && (activeStates.includes(session.status) || session.execution?.checks.some(job => ['queued', 'running'].includes(job.status)) === true + || session.execution?.deliveries?.some(job => ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(job.status)) === true); const anyRunning = isRunning || briefs.some(item => activeStates.includes(item.status)); const pending = session?.changes.filter(change => ['pending', 'conflict'].includes(change.status)) || []; const selectedChange = session?.changes.find(change => change.id === changeId) || pending[0] || session?.changes.at(-1); @@ -101,6 +102,7 @@ export default function App() { function notify(message: string) { setToast(message); } function failure(error: unknown) { notify(error instanceof Error ? error.message : String(error)); } function selectSession(id: string) { + if (selectedSessionRef.current === id) return; selectedSessionRef.current = id; setSessionId(id); setSession(null); localStorage.setItem('awb-session', id); setChangeId(''); setEventId(''); } @@ -140,7 +142,9 @@ export default function App() { if (window.innerWidth <= 620) setSidebarOpen(false); } async function chooseSession(id: string) { - selectSession(id); + if (selectedSessionRef.current === id) { + try { acceptSession(await api('/sessions/' + id)); } catch (error) { failure(error); } + } else selectSession(id); if (window.innerWidth <= 620) setSidebarOpen(false); } async function newSession() { diff --git a/src/client/DeliveryPanel.css b/src/client/DeliveryPanel.css new file mode 100644 index 00000000..433e5e94 --- /dev/null +++ b/src/client/DeliveryPanel.css @@ -0,0 +1,56 @@ +.git-delivery .record-footnote { display: block; } +.delivery-route { display: flex; align-items: center; gap: 5px; flex-wrap: wrap; font-size: 10px; margin: 13px 0 16px; color: var(--muted); } +.delivery-route span { border: 1px solid var(--line); border-radius: 4px; padding: 5px 7px; } +.delivery-route .done { background: #edf7ef; border-color: #b8d6c4; color: #277958; } +.delivery-route i { font-style: normal; } +.delivery-message { margin: 10px 0; font-size: 11px; } +.delivery-message textarea { resize: vertical; min-height: 58px; max-height: 150px; width: 100%; font-size: 11px; line-height: 1.7; padding: 9px; border: 1px solid var(--line); border-radius: 5px; background: white; } +.delivery-author { font-size: 11px; margin: 10px 0 15px; } +.delivery-author summary { cursor: pointer; color: var(--teal); } +.delivery-author p { color: var(--muted); font-size: 10px; line-height: 1.8; margin: 8px 0; } +.delivery-author .form-field { font-size: 11px; margin: 8px 0; } +.delivery-author input { padding: 7px 9px; font-size: 11px; } +.delivery-job { font-size: 11px; line-height: 1.8; padding: 14px 0; border-top: 1px solid var(--line); margin-top: 15px; } +.delivery-job .record-heading { flex-wrap: wrap; margin-bottom: 5px; } +.delivery-job time { color: var(--muted); font-size: 10px; } +.delivery-job > p { margin: 7px 0; overflow-wrap: anywhere; } +.delivery-current { display: flex; align-items: center; gap: 6px; color: var(--teal); } +.delivery-commit { display: flex; align-items: flex-start; gap: 6px; background: #edf3f1; padding: 8px; border-radius: 4px; margin-top: 8px; color: var(--teal); } +.delivery-commit svg { flex: none; margin-top: 3px; } +.delivery-commit code { overflow-wrap: anywhere; font-size: 10px; } +.delivery-paths { padding-left: 14px; margin: 10px 0; color: var(--muted); } +.delivery-paths li { overflow-wrap: anywhere; } +.delivery-preserved { display: flex; align-items: flex-start; gap: 6px; color: #277958; } +.delivery-preserved svg, .delivery-warning svg { flex: none; margin-top: 3px; } +.delivery-report-actions { display: flex; gap: 4px 10px; flex-wrap: wrap; margin-top: 8px; } +.delivery-report-actions .text-button { padding: 3px 0; } +.delivery-attention { padding: 12px; border: 1px solid #e7d8b8; background: #fffaf0; border-radius: 5px; } +.delivery-warning { display: flex; align-items: flex-start; gap: 6px; color: #805d22; font-size: 11px; line-height: 1.8; } +.delivery-report-summary { border-top: 1px solid var(--line); padding-top: 16px; margin-top: 15px; } +.delivery-report-summary > .text-button { display: flex; margin-top: 8px; padding-left: 0; } +.delivery-confirm { flex: 1; min-height: 0; overflow: auto; font-size: 12px; } +.delivery-confirm-overview { display: flex; flex-direction: column; gap: 5px; border-left: 2px solid #7da89c; padding-left: 11px; margin-bottom: 16px; line-height: 1.7; } +.delivery-confirm-overview span { color: var(--muted); font-size: 11px; } +.delivery-confirm-message { white-space: pre-wrap; } +.delivery-checks { list-style: none; padding: 0; margin: 17px 0; font-size: 11px; } +.delivery-checks li { display: flex; align-items: flex-start; gap: 7px; margin-top: 9px; color: #277958; flex-wrap: wrap; } +.delivery-checks strong { font-family: "Cascadia Code", Consolas, monospace; font-size: 11px; } +.delivery-checks span { color: var(--muted); } +.delivery-policy { background: #faf7ef; color: #805d22; border-left: 2px solid #bd9654; padding: 10px 12px; font-size: 11px; line-height: 1.8; margin: 14px 0; } +.delivery-diffs details { border: 1px solid var(--line); border-radius: 5px; margin: 9px 0; overflow: hidden; } +.delivery-diffs summary { padding: 11px; background: #edf3f1; cursor: pointer; font-size: 11px; line-height: 1.6; } +.delivery-diffs summary span { overflow-wrap: anywhere; } +.delivery-diffs summary small { float: right; color: var(--muted); margin-left: 9px; font-size: 10px; } +.delivery-diffs p { font-size: 11px; line-height: 1.8; margin: 10px 12px; overflow-wrap: anywhere; } +.delivery-diffs pre { font-size: 11px; line-height: 1.7; overflow: auto; max-height: 340px; padding: 12px; background: #fcfdfc; } +.delivery-file-hash { display: block; padding: 9px 12px; font-size: 10px; color: var(--muted); overflow-wrap: anywhere; border-top: 1px solid var(--line); } +.status-preparing, .status-prepared, .status-publishing, .status-committed, .status-reporting { background: #edf3f1; color: var(--teal); } +@media (max-width: 620px) { + .delivery-confirm .record-fields { grid-template-columns: 76px minmax(0, 1fr); } + .delivery-confirm-overview strong { font-size: 12px; } + .delivery-checks li { column-gap: 5px; } + .delivery-checks span { width: 100%; padding-left: 18px; } + .delivery-diffs summary small { float: none; display: block; margin: 4px 0 0 13px; } + .delivery-report-actions { column-gap: 12px; } +} +@media (prefers-reduced-motion: reduce) { .delivery-current .spin { animation: none; } } diff --git a/src/client/DeliveryPanel.tsx b/src/client/DeliveryPanel.tsx new file mode 100644 index 00000000..f0e0f8b5 --- /dev/null +++ b/src/client/DeliveryPanel.tsx @@ -0,0 +1,122 @@ +import { useEffect, useRef, useState } from 'react'; +import { ArrowDownToLine, Check, FileCheck2, FileText, GitCommitHorizontal, LoaderCircle, RefreshCw, ShieldQuestion } from 'lucide-react'; +import { api, downloadArtifact } from './api'; +import { Modal, Status } from './components'; +import type { DeliveryPlan, Session } from './types'; +import './DeliveryPanel.css'; + +const active = ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting']; +const stageLabel: Record = { queued: '正在核对提交基线', preparing: '正在准备已审核文件', prepared: '文件快照已准备', publishing: '正在生成本地提交', committed: '正在核对实际提交', reporting: '正在生成交付报告' }; +const date = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : '执行中'; + +export function DeliveryPanel({ session, busy, onSession, onError, openArtifact }: { + session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void; +}) { + const task = session.execution?.task; + const jobs = session.execution?.deliveries ?? []; + const [message, setMessage] = useState(''); + const [authorName, setAuthorName] = useState(''); + const [authorEmail, setAuthorEmail] = useState(''); + const [planning, setPlanning] = useState(false); + const [confirm, setConfirm] = useState(null); + const [submitting, setSubmitting] = useState(false); + const [reporting, setReporting] = useState(false); + const [reconciling, setReconciling] = useState(''); + const [downloading, setDownloading] = useState(false); + const identity = useRef(0); + const inFlight = useRef(false); + const running = jobs.some(job => active.includes(job.status)); + 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 reports = session.execution?.artifacts.filter(artifact => artifact.kind === 'delivery-report-markdown') ?? []; + const latestReport = reports.at(-1); + + useEffect(() => { + identity.current++; setConfirm(null); setPlanning(false); setSubmitting(false); setReporting(false); setReconciling(''); + setMessage(task ? '完成:' + task.goal.replace(/\s+/g, ' ').slice(0, 90) : ''); setAuthorName(''); setAuthorEmail(''); + inFlight.current = false; + }, [session.id, task?.id]); + + async function prepare() { + if (inFlight.current) return; + inFlight.current = true; setPlanning(true); const request = identity.current; + try { + const result = await api('/sessions/' + session.id + '/delivery-plans', { message, ...(authorName.trim() ? { authorName: authorName.trim() } : {}), ...(authorEmail.trim() ? { authorEmail: authorEmail.trim() } : {}) }); + if (request !== identity.current) return; + onSession(result); setConfirm(result.execution?.deliveryPlans?.at(-1) ?? null); + } catch (error) { if (request === identity.current) onError(error); } + finally { if (request === identity.current) { inFlight.current = false; setPlanning(false); } } + } + async function commit() { + if (!confirm || inFlight.current) return; + inFlight.current = true; setSubmitting(true); const request = identity.current; + try { + const result = await api('/sessions/' + session.id + '/delivery-jobs', { planId: confirm.id }); + if (request === identity.current) { onSession(result); setConfirm(null); } + } catch (error) { if (request === identity.current) onError(error); } + finally { if (request === identity.current) { inFlight.current = false; setSubmitting(false); } } + } + async function report() { + if (inFlight.current) return; + inFlight.current = true; setReporting(true); const request = identity.current; + try { + const result = await api('/sessions/' + session.id + '/delivery-reports', {}); + if (request !== identity.current) return; + onSession(result); + const artifact = result.execution?.artifacts.filter(value => value.kind === 'delivery-report-markdown').at(-1); + if (artifact) openArtifact(artifact.id); + } catch (error) { if (request === identity.current) onError(error); } + finally { if (request === identity.current) { inFlight.current = false; setReporting(false); } } + } + async function reconcile(jobId: string) { + if (inFlight.current) return; + inFlight.current = true; setReconciling(jobId); const request = identity.current; + try { + const result = await api('/sessions/' + session.id + '/delivery-jobs/' + jobId + '/reconcile', {}); + if (request === identity.current) onSession(result); + } catch (error) { if (request === identity.current) onError(error); } + finally { if (request === identity.current) { inFlight.current = false; setReconciling(''); } } + } + async function download(id: string, extension: string) { + setDownloading(true); + try { await downloadArtifact(session.id, id, 'Agent-Workbench-delivery-' + (task?.id.slice(0, 8) ?? session.id.slice(0, 8)) + extension); } + catch (error) { onError(error); } finally { setDownloading(false); } + } + + return
+

审核提交与交付

+

核对当前任务已应用的文件和实际测试,预览后生成本地提交。其他项目改动保留。

+
文件已审查→实际检查→ job.status === 'completed') ? 'done' : ''}>本地提交
+