feat(runtime): observe turn evidence without changing execution controls

This commit is contained in:
Agent Workbench Dev
2026-11-04 11:26:47 +08:00
parent 785dd0c54d
commit 6fe04042c5
291 changed files with 66740 additions and 3 deletions
+1
View File
@@ -251,3 +251,4 @@ docs/working-memory-u-release-identity.json -text
docs/tianshu-research-evidence/** -text
docs/requirements-review-a-evidence/** binary
docs/turn-progress-b-evidence/** binary
+1
View File
@@ -48,3 +48,4 @@
!/docs/live-delivery-t-evidence/**/*.log
!/docs/requirements-review-a-evidence/**/*.log
!/docs/turn-progress-b-evidence/**/*.log
+1 -1
View File
@@ -1,6 +1,6 @@
# Agent Workbench项目执行规范
当前接续已获用户授权开发要求与证据复核、单轮shadow观察。研究原未提交内容已验证并提交ce3afb2f;要求复核A已开发、相关53/53/网页7组/Electron3组及构建通过,见docs/REQUIREMENTS-REVIEW-A.md,独立发行/安装/正式升级未完成,正式仍1.24.8/原Provider。下一B只记录外显事实,不改变停止/权限/预算;真实模型预算0,保留V网络partial、T/R/P/O原失败、重复读取和Purge未知,不续跑旧样本、不委派、不推送、不读取/重存Key。下方“当前新增研究只读”属于研究时点。
当前接续要求复核A与单轮shadow观察B已完成开发切片及阶段回顾。研究原未提交内容已验证并提交ce3afb2f;A提交785dd0c5,相关53/53/网页7组/Electron3组及构建通过,见docs/REQUIREMENTS-REVIEW-A.md;B相关68/68及补强最终31/31、网页9组/Electron9组和构建通过,见docs/TURN-PROGRESS-B.md。B只记录外显事实和原收据,不改变提示/停止/权限/预算。独立发行/安装/正式升级未完成,正式仍1.24.8/PID36552/原Provider,不代表1.25已交付。真实模型预算0,保留V网络partial、T/R/P/O原失败、重复读取和Purge未知,不续跑旧样本、不委派、不推送、不读取/重存Key。下方“当前新增研究只读”等为研究时点。
V按一次诊断partial在预检前结束,真实请求0;原正式状态精确保持,46份证据离线通过,见docs/QA-LIVE-DELIVERY-V.md。当前用户新增Tianshu-harness深度源码研究:固定2d0b22e,只读机制/原理/逻辑与本产品差异,不运行第三方安装服务或导入其配置,不改正式Provider/Key,不委派、不推送;真实交付另冻新样本,不续跑V/T/R/P/O。下方U“下一V”和V执行中段落为历史状态。
+2
View File
@@ -2,6 +2,8 @@
状态:分切片开发中。要求来源、逐项修订和实际证据复核的首个开发切片见[要求复核 A](REQUIREMENTS-REVIEW-A.md),已做相关及实际入口验证;自动草案提取、完整范围约定与诊断闭环继续排期。尚未独立发行/安装/正式升级,正式仍1.24.8,不代表1.25已交付。
单轮外显事实 shadow 开发切片见[单轮观察 B](TURN-PROGRESS-B.md)。记录分页、重复候选、失败和所属等待,保留原收据;相关68项及后续最终31项、实际网页9组/Electron9组和构建通过。观察不改变模型提示、停止、权限或预算,不证明真实模型交付或Purge收益。A/B独立发行与安装仍是后续工作。
1.24增加的是当前文件与来源的核对。文件SHA、采用原因和检查通过仍不能单独证明所有业务要求已满足。下一阶段把任务要求、实际成果及尚未验证事项联系起来,让用户知道“完成了哪些、依据是什么、哪里还需要体验”。
## A:保留真实失败与要求来源
+30
View File
@@ -0,0 +1,30 @@
# 单轮进展观察 B:开发切片回顾
本阶段在现有 Runtime、Task/Run、工具原结果和交付报告中增加单轮外显事实观察,已完成开发与实际入口验证。它只记录 shadow,不修改停止、权限、预算、模型提示或私有思考处理。尚未独立发行、实际安装或正式升级,正式服务仍为 1.24.8;A 与 B 的开发验证不能写成 1.25 已交付。研究时冻结的 Tianshu 采用计划及 A 原证据保持原字节。
每个 Run 先记录已有事实基线,再按原工具实际返回的文件 SHA、原范围内 UTF-16 字符覆盖、实际应用文件、原检查结果、要求证明、用户消息实例、失败和所属等待分类。分页取得新字符和新 SHA 是新依据,同 SHA 已覆盖范围只标为重复候选;模型改写总结不增加工程成果。只读研究取得原文件依据也是有效工作,最终总结轮显示未见新外显事实不代表研究无效,也不触发催促或停止。
记录分为 baseline、waiting、evidence_growth、new_failure_evidence、user_boundary、repeated_failure_candidate、repeated_read_candidate、no_observed_change 和 unknown_bounded。错误保留参数无效、权限/审批拒绝、工具或环境、结果待核对,以及原模型诊断的网络、上游服务、鉴权、限流与额度类别。新失败和读取增长可在同轮同时记录,不用一个总分掩盖原因。HTTP 502 夹具仍由原 Provider 重试三次并保存原响应与 unknown 消费;shadow 记录其所属模型轮的失败,不新增请求,也不把它改成 no_progress。
容量明确有界:32 个来源版本、每来源 24 个区间、96 个事实签名、48 个失败签名、40 条观察、每条 64 个工具引用。原范围按原工具坐标比较,不把不同起始行或不同文件版本合并。达到容量后保留未知,不把没记住的范围判为重复;较早观察收据仍留在原工件。每个 Run 有自己的基线和范围,不跨项目、Task 或 Run 累加。
观察从已持久化工具结果工件读取原字节,核对项目/会话/Task/Run/Step,并保留原调用、参数 SHA 和结果 SHA。原模型失败另绑定原诊断事件及可用的 HTTP/SSE 响应工件。不可变观察收据与 Run 摘要、原工具和原失败在报告中重新对账,来源改变就显示待核对;这些核对不是交付通过条件。观察写入失败只留下缺口说明,不能打断原工具或消费预算;后续成功记录保持摘要和收据一一对应。
等待审批和所属检查作业启动时记录中间等待,结算时只消费一次同轮已完成工具。实际检查启动只加只读观察接点,执行、取消、审批和原日志路径保持。审查交接也作为等待;观察字段不进入请求上下文,不增加提示。当前接点是本地 Runtime 的模型循环,外部引擎内部每一轮、所有第三方工具的语义和自动干预阈值未独立验证。
界面整合在原任务侧栏的运行记录,展开“单轮观察 · 仅记录”可查看增长、候选重复、等待和失败类别,并打开原收据。历史 Run 保留独立观察;刷新仍是原 Task/Run。390px 的收据按钮至少 44px 高,内容可换行;没有新增手机写入权限或新的执行控制台。DeliveryReporter 的 JSON/Markdown 使用同份观察和原收据核对结果,部分观察未保存会明确说明。
验证与回顾:
- 首专项 11 项中 9 通过、2 失败,保留原日志。两处均为夹具误用:不存在的 approve 应为实际 decide;普通 HTTP 失败的原 stopReason 是 null,诊断保留在 lastFailure。修正测试,没有为它们修改原停止行为。界面轮号按从 1 起始的原 Step 修正。
- 补强后专项 12/12;相关八文件 68/68,覆盖要求证据、读取/工作记忆、无进展和原执行路径。补实际长检查接点及参数来源绑定后的最终四文件 31/31,其中 B 专项 15 项。实际应用文件、计数检查与当前要求证明覆盖了已有事实基线后的增长。
- 最终编译宿主的实际 Edge 九组、实际 Electron 九组通过:原三轮分页/重复页、原收据、刷新、390px、审批等待/拒绝、历史 Run、报告及原 502。TypeScript 与完整构建通过。最终桌面、窄屏、审批拒绝和 502 截图已目视检查,沿用原工作台字体、颜色与任务结构。它们是本机协议夹具,不是模型自主交付评测。
- 代码复核发现并修正了等待记录提前消费同轮读取、收据写失败使摘要与收据错位,以及长检查启动缺少观察接点。对应实际运行、故障注入、重开、容量、跨域及来源篡改检查通过。固定案例的人工分类复核见封存的 case-review.json;未从小样本计算总体准确率或收益。
真实模型请求为 0。正式服务只读健康检查仍为 1.24.8/PID 36552;本阶段未操作正式配置、Provider 或 Key,也未重启服务、委派或推送。V 网络诊断 partial、T/R/P/O 原失败、重复读取和真实自主工程交付未通过的事实保留;Purge 收益仍未验证,不续跑旧样本。
后续先完成 A/B 的独立源码、不可变发行、实际安装和保留状态正式升级及体验验收,再按计划推进工具 surface/前缀观测。自动草案提取、完整范围约定与诊断闭环仍继续排期。真实模型与 Purge 另冻新样本和预算;不能把此处 shadow 记录或本机夹具通过当成干预有效、网络修复或自主交付收益。
证据见 `turn-progress-b-evidence/`,270 份/7,729,650 字节,含 13 项当前源码对照、原首失败、六轮入口验证及最终原工件。首封 265 份清单与原源码保留在 first-seal/manifest.json 和 source/;回顾后只将部分观察缺失的提示移到 Markdown 表格之前,修正稿、直接格式验证与再次构建另存。最终离线复核两组实际入口的 10 份快照、32 条观察、14 次原工具结果引用和 50 份原工件通过,不重放执行。
`node scripts/verify-turn-progress-evidence.mjs docs/turn-progress-b-evidence` 离线核对原字节、实际输入/结果来源、覆盖增量和固定分类,不重放工具、检查或模型;加 `--index --source-ref <本切片提交>` 可核对索引与 Git 源码。
@@ -0,0 +1,62 @@
{
"scope": "Fixed public-fact cases manually reviewed against original assertions; no population accuracy or model benefit claim.",
"cases": [
{
"case": "normal_exploration",
"expected": "new observed content is evidence growth",
"evidence": "logs/shadow-source-final.tap",
"assertion": "fixed normal exploration, pagination, SHA changes and repeated ranges"
},
{
"case": "pagination_and_repetition",
"expected": "10 new + 10 new + repeated candidate, original step_limit",
"evidence": "ui/web-final/pages-original.json"
},
{
"case": "read_only_research",
"expected": "reading is useful; summary wording is not additional engineering evidence; no shadow interruption",
"evidence": "logs/shadow-source-final.tap",
"assertion": "read-only research is valid work"
},
{
"case": "long_check",
"expected": "approved actual running job stays waiting, then counted result",
"evidence": "logs/shadow-source-final.tap",
"assertion": "actual approved long check"
},
{
"case": "failure_repair_evidence",
"expected": "applied file, actual counted check and current requirement proof grow after baseline",
"evidence": "logs/shadow-source-final.tap",
"assertion": "real applied files, counted checks and current requirement proofs"
},
{
"case": "permission_denial",
"expected": "waiting then original permission failure; earlier same-turn read consumed once",
"evidence": "ui/electron-final/approval-denied.json"
},
{
"case": "broken_tool_or_network",
"expected": "new failure is evidence; original failure categories remain distinct",
"evidence": "logs/shadow-source-final.tap",
"assertion": "new permissions, network and broken tools"
},
{
"case": "invalid_input_repetition",
"expected": "repeat candidate, no new early stop; original four-request step_limit",
"evidence": "logs/shadow-source-final.tap",
"assertion": "actual invalid tool calls repeat under the original step budget"
},
{
"case": "bounded_unknown",
"expected": "unretained facts stay unknown; old receipts retained and scope cannot mix",
"evidence": "logs/shadow-source-final.tap",
"assertion": "receipt retention stays aligned at the cap"
}
],
"limitations": [
"No real model delivery sample.",
"No intervention thresholds or global false-positive/false-negative rate.",
"No Purge comparison or network recovery claim."
]
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,20 @@
> local-agent-workbench@1.24.8 build
> tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs
vite v7.3.7 building client environment for production...
transforming...
✓ 1764 modules transformed.
rendering chunks...
computing gzip size...
dist-client/index.html 0.60 kB │ gzip: 0.41 kB
dist-client/.vite/manifest.json 0.65 kB │ gzip: 0.25 kB
dist-client/mobile.html 0.84 kB │ gzip: 0.47 kB
dist-client/assets/mobile-joLHctQw.css 12.39 kB │ gzip: 3.22 kB
dist-client/assets/desktop-DD401Tkz.css 175.22 kB │ gzip: 33.14 kB
dist-client/assets/mobile-DdtBN08G.js 26.97 kB │ gzip: 9.31 kB
dist-client/assets/approval-presentation-QyCkfhWb.js 227.03 kB │ gzip: 71.74 kB
dist-client/assets/desktop-BOCTXESM.js 428.16 kB │ gzip: 121.34 kB
✓ built in 1.27s
Mobile shell built: 3 allowed assets; API and project data are never cached.
Server bundle built.
@@ -0,0 +1,20 @@
> local-agent-workbench@1.24.8 build
> tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs
vite v7.3.7 building client environment for production...
transforming...
✓ 1764 modules transformed.
rendering chunks...
computing gzip size...
dist-client/index.html 0.60 kB │ gzip: 0.41 kB
dist-client/.vite/manifest.json 0.65 kB │ gzip: 0.25 kB
dist-client/mobile.html 0.84 kB │ gzip: 0.47 kB
dist-client/assets/mobile-joLHctQw.css 12.39 kB │ gzip: 3.22 kB
dist-client/assets/desktop-DD401Tkz.css 175.22 kB │ gzip: 33.14 kB
dist-client/assets/mobile-DdtBN08G.js 26.97 kB │ gzip: 9.31 kB
dist-client/assets/approval-presentation-QyCkfhWb.js 227.03 kB │ gzip: 71.74 kB
dist-client/assets/desktop-BOCTXESM.js 428.16 kB │ gzip: 121.34 kB
✓ built in 1.24s
Mobile shell built: 3 allowed assets; API and project data are never cached.
Server bundle built.
@@ -0,0 +1,20 @@
> local-agent-workbench@1.24.8 build
> tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs
vite v7.3.7 building client environment for production...
transforming...
✓ 1764 modules transformed.
rendering chunks...
computing gzip size...
dist-client/index.html 0.60 kB │ gzip: 0.41 kB
dist-client/.vite/manifest.json 0.65 kB │ gzip: 0.24 kB
dist-client/mobile.html 0.84 kB │ gzip: 0.47 kB
dist-client/assets/mobile-joLHctQw.css 12.39 kB │ gzip: 3.22 kB
dist-client/assets/desktop-CKYR4gCQ.css 175.15 kB │ gzip: 33.13 kB
dist-client/assets/mobile-DdtBN08G.js 26.97 kB │ gzip: 9.31 kB
dist-client/assets/approval-presentation-QyCkfhWb.js 227.03 kB │ gzip: 71.74 kB
dist-client/assets/desktop-Cs9Z2tE3.js 427.62 kB │ gzip: 121.10 kB
✓ built in 1.32s
Mobile shell built: 3 allowed assets; API and project data are never cached.
Server bundle built.
@@ -0,0 +1,20 @@
> local-agent-workbench@1.24.8 build
> tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs
vite v7.3.7 building client environment for production...
transforming...
✓ 1764 modules transformed.
rendering chunks...
computing gzip size...
dist-client/index.html 0.60 kB │ gzip: 0.41 kB
dist-client/.vite/manifest.json 0.65 kB │ gzip: 0.25 kB
dist-client/mobile.html 0.84 kB │ gzip: 0.47 kB
dist-client/assets/mobile-joLHctQw.css 12.39 kB │ gzip: 3.22 kB
dist-client/assets/desktop-DD401Tkz.css 175.22 kB │ gzip: 33.14 kB
dist-client/assets/mobile-DdtBN08G.js 26.97 kB │ gzip: 9.31 kB
dist-client/assets/approval-presentation-QyCkfhWb.js 227.03 kB │ gzip: 71.74 kB
dist-client/assets/desktop-BOCTXESM.js 428.16 kB │ gzip: 121.34 kB
✓ built in 1.23s
Mobile shell built: 3 allowed assets; API and project data are never cached.
Server bundle built.
@@ -0,0 +1,20 @@
> local-agent-workbench@1.24.8 build
> tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs
vite v7.3.7 building client environment for production...
transforming...
✓ 1764 modules transformed.
rendering chunks...
computing gzip size...
dist-client/index.html 0.60 kB │ gzip: 0.41 kB
dist-client/.vite/manifest.json 0.65 kB │ gzip: 0.25 kB
dist-client/mobile.html 0.84 kB │ gzip: 0.47 kB
dist-client/assets/mobile-joLHctQw.css 12.39 kB │ gzip: 3.22 kB
dist-client/assets/desktop-CKYR4gCQ.css 175.15 kB │ gzip: 33.13 kB
dist-client/assets/mobile-DdtBN08G.js 26.97 kB │ gzip: 9.31 kB
dist-client/assets/approval-presentation-QyCkfhWb.js 227.03 kB │ gzip: 71.74 kB
dist-client/assets/desktop-B3qeS1IX.js 427.63 kB │ gzip: 121.10 kB
✓ built in 1.25s
Mobile shell built: 3 allowed assets; API and project data are never cached.
Server bundle built.
@@ -0,0 +1,20 @@
> local-agent-workbench@1.24.8 build
> tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs
vite v7.3.7 building client environment for production...
transforming...
✓ 1764 modules transformed.
rendering chunks...
computing gzip size...
dist-client/index.html 0.60 kB │ gzip: 0.41 kB
dist-client/.vite/manifest.json 0.65 kB │ gzip: 0.25 kB
dist-client/mobile.html 0.84 kB │ gzip: 0.47 kB
dist-client/assets/mobile-joLHctQw.css 12.39 kB │ gzip: 3.22 kB
dist-client/assets/desktop-DD401Tkz.css 175.22 kB │ gzip: 33.14 kB
dist-client/assets/mobile-DdtBN08G.js 26.97 kB │ gzip: 9.31 kB
dist-client/assets/approval-presentation-QyCkfhWb.js 227.03 kB │ gzip: 71.74 kB
dist-client/assets/desktop-BOCTXESM.js 428.16 kB │ gzip: 121.34 kB
✓ built in 1.23s
Mobile shell built: 3 allowed assets; API and project data are never cached.
Server bundle built.
@@ -0,0 +1,13 @@
{
"officialVersion": "1.24.8",
"pid": 36552,
"processStartedAt": "2026-10-31T06:30:34.3598842Z",
"health": {
"app": "agent-workbench",
"version": "1.24.8",
"pid": 36552,
"ready": true,
"uptimeMs": 334149445
},
"scope": "read-only public health and original process existence; no config, credentials, model calls or service restart"
}
@@ -0,0 +1,63 @@
## 单轮观察(仅记录)
外显事实分类不改变停止、权限或预算;不是自主交付收益证明。
427163b7-0d45-48fb-8567-cced8bac67e7:部分观察未能记录,原执行结果保留。
| Run / 轮次 | 观察 | 新读取字符 | 重复读取 | 新失败 / 重复失败 | 原收据核对 |
| --- | --- | --- | --- | --- | --- |
| 427163b7-0d45-48fb-8567-cced8bac67e7 / baseline | baseline | 0 | 0 | 0 / 0 | 原字节已核对 |
| 427163b7-0d45-48fb-8567-cced8bac67e7 / 1 | evidence_growth | 10 | 0 | 0 / 0 | 原字节已核对 |
| 427163b7-0d45-48fb-8567-cced8bac67e7 / 2 | evidence_growth | 10 | 0 | 0 / 0 | 原字节已核对 |
| 427163b7-0d45-48fb-8567-cced8bac67e7 / 3 | repeated_read_candidate | 0 | 1 | 0 / 0 | 原字节已核对 |
| 2faa6142-661b-4518-8571-18841fbec6f5 / baseline | baseline | 0 | 0 | 0 / 0 | 原字节已核对 |
| 2faa6142-661b-4518-8571-18841fbec6f5 / 1 | waiting | 0 | 0 | 0 / 0 | 原字节已核对 |
| 2faa6142-661b-4518-8571-18841fbec6f5 / 1 | evidence_growth | 10 | 0 | 1 / 0 | 原字节已核对 |
| 2faa6142-661b-4518-8571-18841fbec6f5 / 2 | no_observed_change | 0 | 0 | 0 / 0 | 原字节已核对 |
## 实际检查
| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |
| --- | --- | --- | --- | --- |
## Git交付
尚无内置Git提交记录。
## 模型与用量
Run型号为启动配置;每次实际发送与返回型号见下表。型号标识或登记映射不认证底层模型权重。
| Run | 启动型号 | 状态 | 已报告tokens |
| --- | --- | --- | --- |
| 427163b7-0d45-48fb-8567-cced8bac67e7 | owned-shadow-ui | paused | 504 |
| 2faa6142-661b-4518-8571-18841fbec6f5 | owned-shadow-ui | completed | 336 |
| 尝试 | 请求型号 | 上游报告型号 | 核对结果 | 原响应 SHA256 |
| --- | --- | --- | --- | --- |
| 0eec312a-cb27-49f6-b93f-e0a48c26ce75 | owned-shadow-ui | 未记录 | 上游未报告型号 | 6bf86234841f0a8e301a03a01511b25e7b9462a951a63da98ba41cc399979257 |
| 380a8b5c-9432-4c16-b27e-1846bc07f1ba | owned-shadow-ui | 未记录 | 上游未报告型号 | 766649c120a7ff239291c671bb33614d92930d7b11bb1e0ba200762021573482 |
| 1f5bbaf8-349b-489f-9577-bcf55cb79a72 | owned-shadow-ui | 未记录 | 上游未报告型号 | 0b95de8795765e496951221843b56799b1a7869cdead9a80cf46a39983e710ca |
| 8c8ff00c-3c48-4ce3-b056-4de318d28c88 | owned-shadow-ui | 未记录 | 上游未报告型号 | 7559c0ea5e206ebbca81c12dcf83cf367f1ce4aaf041f9fd66da19f3b5af4ed5 |
| 5eb360f0-2346-4fa8-b982-22ae16cd511c | owned-shadow-ui | 未记录 | 上游未报告型号 | 1533d54eb3cfa022035842742f6595b3885675db8019909517d655c95b8e8510 |
累计已报告:840 tokens;未报告请求:0。费用:未知。
## 请求上下文
| 请求 | 状态 | 输入估算 | 已报告输入 | 省略组 | 正文SHA256校验 |
| --- | --- | --- | --- | --- | --- |
| 56f63544-e7b0-432b-8327-6f709001b568 | completed | 7274 | 123 | 0 | 7533c0ce3cd4fc8a69bb9503920272eabca501f84d1bb5fb1744d8966c33d3ce |
| 66e9089b-33ad-49f4-8d46-0d83cbfd84e4 | completed | 7941 | 123 | 0 | 0373a57bbb310ed2b281557b8ef99596ad6a19aa3e3d40e36e263091ecabcb80 |
| 62df1fc6-1de6-49d1-822d-8da8ad2cda9f | completed | 8409 | 123 | 0 | d9243876d3f82510ba5f23d4aea627cb915f6b4ea634cda269a507b2aaa07024 |
| c6f53e6a-28ec-491a-b569-9ea845746a6a | completed | 8772 | 123 | 0 | 3fb1308fc910a96d11da013ae15370de799edf9e53c386c3394f5c8ef58da4ac |
| 8374706e-be33-4fd0-8b3d-ad4e960831a6 | completed | 9445 | 123 | 0 | 37de3f171cb511c54ecbb5051b1c98ef1e81e91b4fd485dca8e5c0ba41a48cb6 |
## 尚待确认
- 本切片验证已选工程检查和提交范围;业务需求验收另行记录。
- 提交为本地普通提交,不执行仓库hooks和GPG签名。
- 请求输入为本地UTF-8估算;服务实际分词和用量另行记录。
- 未配置模型单价,费用未知。
@@ -0,0 +1,10 @@
PASS actual runtime pages grow then repeat under the original three-round limit
PASS original observation receipt opens with the actual tool-result provenance
PASS refresh restores the same Task, Run and persisted shadow observations
PASS 390px keeps observation facts and original receipt actions reachable without page overflow
PASS an actual pending approval stays waiting and does not consume the earlier same-turn read twice
PASS refusing the original approval preserves the permission failure and the original tool pairs
PASS selecting historical and current Runs keeps their independent observations
PASS delivery report uses both Runs and independently verifies the original observation receipts
PASS original HTTP 502 remains a model failure and is not relabeled as no progress
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-2f18aa50-365f-4f47-b8f6-e46868bb5f69","success":true,"passed":["actual runtime pages grow then repeat under the original three-round limit","original observation receipt opens with the actual tool-result provenance","refresh restores the same Task, Run and persisted shadow observations","390px keeps observation facts and original receipt actions reachable without page overflow","an actual pending approval stays waiting and does not consume the earlier same-turn read twice","refusing the original approval preserves the permission failure and the original tool pairs","selecting historical and current Runs keeps their independent observations","delivery report uses both Runs and independently verifies the original observation receipts","original HTTP 502 remains a model failure and is not relabeled as no progress"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-2f18aa50-365f-4f47-b8f6-e46868bb5f69\\desktop-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-2f18aa50-365f-4f47-b8f6-e46868bb5f69\\narrow-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-2f18aa50-365f-4f47-b8f6-e46868bb5f69\\waiting-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-2f18aa50-365f-4f47-b8f6-e46868bb5f69\\denied-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-2f18aa50-365f-4f47-b8f6-e46868bb5f69\\historical-run.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-2f18aa50-365f-4f47-b8f6-e46868bb5f69\\network-original-failure.png"],"snapshots":["pages-original.json","approval-waiting.json","approval-denied.json","report-original.json","network-original.json"],"actualElectron":true,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
@@ -0,0 +1,10 @@
PASS actual runtime pages grow then repeat under the original three-round limit
PASS original observation receipt opens with the actual tool-result provenance
PASS refresh restores the same Task, Run and persisted shadow observations
PASS 390px keeps observation facts and original receipt actions reachable without page overflow
PASS an actual pending approval stays waiting and does not consume the earlier same-turn read twice
PASS refusing the original approval preserves the permission failure and the original tool pairs
PASS selecting historical and current Runs keeps their independent observations
PASS delivery report uses both Runs and independently verifies the original observation receipts
PASS original HTTP 502 remains a model failure and is not relabeled as no progress
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-f623d3bc-981e-4dcd-9eac-fd39d1513eb3","success":true,"passed":["actual runtime pages grow then repeat under the original three-round limit","original observation receipt opens with the actual tool-result provenance","refresh restores the same Task, Run and persisted shadow observations","390px keeps observation facts and original receipt actions reachable without page overflow","an actual pending approval stays waiting and does not consume the earlier same-turn read twice","refusing the original approval preserves the permission failure and the original tool pairs","selecting historical and current Runs keeps their independent observations","delivery report uses both Runs and independently verifies the original observation receipts","original HTTP 502 remains a model failure and is not relabeled as no progress"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-f623d3bc-981e-4dcd-9eac-fd39d1513eb3\\desktop-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-f623d3bc-981e-4dcd-9eac-fd39d1513eb3\\narrow-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-f623d3bc-981e-4dcd-9eac-fd39d1513eb3\\waiting-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-f623d3bc-981e-4dcd-9eac-fd39d1513eb3\\denied-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-f623d3bc-981e-4dcd-9eac-fd39d1513eb3\\historical-run.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-f623d3bc-981e-4dcd-9eac-fd39d1513eb3\\network-original-failure.png"],"snapshots":["pages-original.json","approval-waiting.json","approval-denied.json","report-original.json","network-original.json"],"actualElectron":true,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
@@ -0,0 +1,10 @@
PASS actual runtime pages grow then repeat under the original three-round limit
PASS original observation receipt opens with the actual tool-result provenance
PASS refresh restores the same Task, Run and persisted shadow observations
PASS 390px keeps observation facts and original receipt actions reachable without page overflow
PASS an actual pending approval stays waiting and does not consume the earlier same-turn read twice
PASS refusing the original approval preserves the permission failure and the original tool pairs
PASS selecting historical and current Runs keeps their independent observations
PASS delivery report uses both Runs and independently verifies the original observation receipts
PASS original HTTP 502 remains a model failure and is not relabeled as no progress
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070","success":true,"passed":["actual runtime pages grow then repeat under the original three-round limit","original observation receipt opens with the actual tool-result provenance","refresh restores the same Task, Run and persisted shadow observations","390px keeps observation facts and original receipt actions reachable without page overflow","an actual pending approval stays waiting and does not consume the earlier same-turn read twice","refusing the original approval preserves the permission failure and the original tool pairs","selecting historical and current Runs keeps their independent observations","delivery report uses both Runs and independently verifies the original observation receipts","original HTTP 502 remains a model failure and is not relabeled as no progress"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\desktop-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\narrow-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\waiting-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\denied-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\historical-run.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\network-original-failure.png"],"snapshots":["pages-original.json","approval-waiting.json","approval-denied.json","report-original.json","network-original.json"],"actualElectron":true,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
@@ -0,0 +1 @@
{"ok":true,"runs":2,"snapshots":10,"receipts":32,"toolResults":14,"originalArtifacts":50,"realModelRequests":0,"replayedOperations":0}
@@ -0,0 +1,39 @@
✔ reviewed application invalidates old checks, names current SHA and advances through a new approved check to Git preview (6667.5453ms)
✔ skip-tests, foreign task, unknown operations, diagnostic and parent review retain their boundaries (2901.1047ms)
✔ before the first change, real baseline failures persist across later reads; passed baselines and changed sources cannot certify delivery (7112.0927ms)
✔ unchanged proposals cannot hide repeated original-log reads or identical session inspections (4736.891ms)
✔ reusing a verified proof never resets identical-state detection or creates a new proof (4437.3073ms)
✔ coverage merges adjacent pages, separates changed sources and never claims old Run coverage in a continuation (0.7417ms)
✔ a stop from the event loop interrupts immediate model replies before later tools (1406.8527ms)
✔ a stop after the first tool preserves a complete interrupted multi-call protocol group (1840.1754ms)
✔ the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands (4333.6527ms)
✔ denial prevents command execution and produces a paired denied result (2375.5393ms)
✔ stopping during approval interrupts pending calls without executing or replaying them (1987.9152ms)
✔ stopping a running fixture command terminates its own process tree and retains uncertain state (1792.9307ms)
✔ command output decodes split UTF-8 and excludes the workbench key from child environment (954.5634ms)
✔ model-list testing uses a tentative key without changing the saved connection and redacts service errors (6.6624ms)
✔ truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities (3270.6865ms)
✔ request projection keeps exact tool pairs and complete recent user instructions while preserving disk history (1113.6142ms)
✔ fixed normal exploration, pagination, SHA changes and repeated ranges are external observations, not a score (1.4002ms)
✔ read-only research is valid work; model summaries and unchanged timestamped listings do not become engineering evidence (0.3877ms)
✔ new permissions, network and broken tools are failure evidence; repeated invalid inputs remain candidates (0.3839ms)
✔ waiting for original long checks, review and approvals stays waiting across repeated observations (0.5272ms)
✔ baseline facts, real repairs, current-source check results and requirement evidence have distinct growth (0.2151ms)
✔ bounded memory keeps unknown instead of claiming an unretained range is repeated; Task/Run instances cannot mix (12.2109ms)
✔ actual runtime records growing pages then a repeated page without changing model rounds, stop rules or original tool pairs (5627.8164ms)
✔ actual invalid tool calls repeat under the original step budget; observation never adds an early stop (4379.6453ms)
✔ actual command approval is observed as waiting and denial stays a permission failure (2514.2761ms)
✔ network errors remain model failures with shadow failure evidence, never a fabricated no-progress cause (3649.2277ms)
✔ observer receipt failure cannot change tool results, model budget or completion (1623.0641ms)
✔ a later receipt recovers after an observation write failure without misaligning retained source receipts (2269.483ms)
✔ real applied files, counted checks and current requirement proofs grow after an existing-facts baseline (3560.0974ms)
✔ receipt retention stays aligned at the cap and a foreign step cannot enter the Run (1747.8179ms)
✔ an actual approved long check records its owned running job as waiting before the original counted result (5061.4597ms)
ℹ tests 31
ℹ suites 0
ℹ pass 31
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 47431.1358
@@ -0,0 +1,50 @@
✔ fixed normal exploration, pagination, SHA changes and repeated ranges are external observations, not a score (1.2557ms)
✔ read-only research is valid work; model summaries and unchanged timestamped listings do not become engineering evidence (0.3686ms)
✔ new permissions, network and broken tools are failure evidence; repeated invalid inputs remain candidates (0.4135ms)
✔ waiting for original long checks, review and approvals stays waiting across repeated observations (0.6149ms)
✔ baseline facts, real repairs, current-source check results and requirement evidence have distinct growth (0.2471ms)
✔ bounded memory keeps unknown instead of claiming an unretained range is repeated; Task/Run instances cannot mix (11.8045ms)
✔ actual runtime records growing pages then a repeated page without changing model rounds, stop rules or original tool pairs (2872.456ms)
✔ actual invalid tool calls repeat under the original step budget; observation never adds an early stop (2823.8118ms)
✖ actual command approval is observed as waiting and denial stays a permission failure (1426.9854ms)
✖ network errors remain model failures with shadow failure evidence, never a fabricated no-progress cause (3388.8116ms)
✔ observer receipt failure cannot change tool results, model budget or completion (1576.6635ms)
ℹ tests 11
ℹ suites 0
ℹ pass 9
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 12291.8808
✖ failing tests:
test at tests\turn-progress.test.mjs:112:1
✖ actual command approval is observed as waiting and denial stays a permission failure (1426.9854ms)
TypeError [Error]: runtime.approve is not a function
at TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/turn-progress.test.mjs:119:11)
at runNextTicks (node:internal/process/task_queues:65:5)
at process.processTimers (node:internal/timers:615:9)
at async Test.run (node:internal/test_runner/test:1409:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:974:7)
test at tests\turn-progress.test.mjs:123:1
✖ network errors remain model failures with shadow failure evidence, never a fabricated no-progress cause (3388.8116ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ null
- 'model_error'
at TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/turn-progress.test.mjs:128:61)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1409:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:974:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: null,
expected: 'model_error',
operator: 'strictEqual',
diff: 'simple'
}
@@ -0,0 +1,76 @@
✔ reviewed application invalidates old checks, names current SHA and advances through a new approved check to Git preview (14934.2695ms)
✔ skip-tests, foreign task, unknown operations, diagnostic and parent review retain their boundaries (5998.3429ms)
✔ before the first change, real baseline failures persist across later reads; passed baselines and changed sources cannot certify delivery (8726.5505ms)
✔ unchanged proposals cannot hide repeated original-log reads or identical session inspections (13890.2694ms)
✔ reusing a verified proof never resets identical-state detection or creates a new proof (11430.2849ms)
✔ coverage merges adjacent pages, separates changed sources and never claims old Run coverage in a continuation (0.8967ms)
✔ continuations distinguish unread source, later original line ranges and already returned result wrappers (919.8288ms)
✔ pure-file batch returns unused small-page space while mixed and historical allocation stays conservative (0.3083ms)
✔ observed upstream high input pauses before a new request, preserves reported usage and distinguishes the limiting ledger (1033.2274ms)
✔ chat-completions: complete actual Unicode/CRLF pages and small source survive the next bounded wire request (3208.6141ms)
✔ responses: complete actual Unicode/CRLF pages and small source survive the next bounded wire request (2108.9623ms)
✔ anthropic-messages: complete actual Unicode/CRLF pages and small source survive the next bounded wire request (2380.3449ms)
✔ requirements HTTP binds selection, enforces optimistic revisions, restores original proofs and leaves provider history untouched (5124.8945ms)
✔ research evidence binds actual original bytes; model completion is not user acceptance (1525.6296ms)
✔ same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision (1845.1698ms)
✔ foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs (2178.0677ms)
✔ source changes invalidate prior proofs and cannot certify a read that was already stale at binding (1707.8169ms)
✔ missing or tampered artifacts never become evidence and original failures remain after recovery (1191.2175ms)
✔ checks omitted by explicit agreement are reported as not executed and never passed (811.3584ms)
✔ user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted (994.31ms)
✔ existing multi-file results keep provenance and invalidate only evidence whose files changed (1310.6476ms)
✔ unrelated additions preserve the checked file facts but remain visible as unreviewed user sources (1414.4197ms)
✔ actual Git preview and publication recheck changed requirement bindings without touching HEAD or the owner index (6774.0966ms)
✔ no-test file application and manual completion keep pending user requirements for explicit review (1547.9085ms)
✔ revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements (878.6389ms)
✔ requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit (2695.488ms)
✔ a stop from the event loop interrupts immediate model replies before later tools (1460.0563ms)
✔ a stop after the first tool preserves a complete interrupted multi-call protocol group (1828.7444ms)
✔ the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands (5278.646ms)
✔ denial prevents command execution and produces a paired denied result (1923.9518ms)
✔ stopping during approval interrupts pending calls without executing or replaying them (1951.3856ms)
✔ stopping a running fixture command terminates its own process tree and retains uncertain state (2086.0807ms)
✔ command output decodes split UTF-8 and excludes the workbench key from child environment (1010.3875ms)
✔ model-list testing uses a tentative key without changing the saved connection and redacts service errors (6.5565ms)
✔ truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities (2133.6342ms)
✔ request projection keeps exact tool pairs and complete recent user instructions while preserving disk history (1064.535ms)
✔ fixed normal exploration, pagination, SHA changes and repeated ranges are external observations, not a score (1.3157ms)
✔ read-only research is valid work; model summaries and unchanged timestamped listings do not become engineering evidence (0.3887ms)
✔ new permissions, network and broken tools are failure evidence; repeated invalid inputs remain candidates (0.3723ms)
✔ waiting for original long checks, review and approvals stays waiting across repeated observations (0.4818ms)
✔ baseline facts, real repairs, current-source check results and requirement evidence have distinct growth (0.2454ms)
✔ bounded memory keeps unknown instead of claiming an unretained range is repeated; Task/Run instances cannot mix (12.1744ms)
✔ actual runtime records growing pages then a repeated page without changing model rounds, stop rules or original tool pairs (5054.6617ms)
✔ actual invalid tool calls repeat under the original step budget; observation never adds an early stop (4684.7063ms)
✔ actual command approval is observed as waiting and denial stays a permission failure (3097.2297ms)
✔ network errors remain model failures with shadow failure evidence, never a fabricated no-progress cause (4430.238ms)
✔ observer receipt failure cannot change tool results, model budget or completion (2315.3024ms)
✔ a later receipt recovers after an observation write failure without misaligning retained source receipts (3580.1383ms)
✔ real applied files, counted checks and current requirement proofs grow after an existing-facts baseline (4019.495ms)
✔ receipt retention stays aligned at the cap and a foreign step cannot enter the Run (3120.7675ms)
✔ all actually returned same-version fragments reach the bounded request, including overlap and Unicode, with independent original provenance (5030.7216ms)
✔ unread gaps and different range origins remain separate; partial sending names the precise missing already-observed range (923.3792ms)
✔ same-SHA conflicting overlaps and invalid coordinates fail closed, while a new SHA never inherits old fragments (1424.9027ms)
✔ versioned old views keep the original single-page semantics and verification (1119.7532ms)
✔ small code and actual failed command stay visible when their original multi-tool group cannot fit (1274.8968ms)
✔ mixed group retains six distinct small file observations with exact multilingual text and bounded request bytes (1891.5719ms)
✔ working observations are bound to the current Task and stop treating a pre-application file revision as current evidence (2336.5661ms)
✔ a sealed observation rejects changed or missing original result artifacts instead of recreating evidence (1473.7606ms)
✔ a real passed-check observation is excluded after a source edit invalidates the check, while its historical sent evidence remains valid (4656.689ms)
✔ budgeted file pages reconstruct UTF-8 text including long single lines and surrogate boundaries (4.6712ms)
✔ actual HTTP multi-tool reads survive an oversized runtime snapshot and the sealed evidence survives reopening (9768.7867ms)
✔ actual HTTP file pagination advances over a long file with each returned page visible in the next request (6083.3053ms)
✔ later mixed history pages cannot displace the actual module sources and complete requirements (4348.3735ms)
✔ a later narrow page of the same file revision cannot evict the wider actual observation (2772.2176ms)
✔ six small source files stay complete across metadata turns even when mandatory evidence exceeds the soft target (2776.0626ms)
✔ historical read-artifact navigation points to the original artifact and next page, never its result wrapper (978.529ms)
✔ a 1.6.1 full-provenance sent view remains verifiable after introducing the compact view (977.3426ms)
✔ actual HTTP requests keep four observed modules after a later large history read and preserve all source bytes (9659.4196ms)
ℹ tests 68
ℹ suites 0
ℹ pass 68
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 117743.4888
@@ -0,0 +1,20 @@
✔ fixed normal exploration, pagination, SHA changes and repeated ranges are external observations, not a score (1.3485ms)
✔ read-only research is valid work; model summaries and unchanged timestamped listings do not become engineering evidence (0.371ms)
✔ new permissions, network and broken tools are failure evidence; repeated invalid inputs remain candidates (0.3971ms)
✔ waiting for original long checks, review and approvals stays waiting across repeated observations (0.4962ms)
✔ baseline facts, real repairs, current-source check results and requirement evidence have distinct growth (0.2112ms)
✔ bounded memory keeps unknown instead of claiming an unretained range is repeated; Task/Run instances cannot mix (12.5194ms)
✔ actual runtime records growing pages then a repeated page without changing model rounds, stop rules or original tool pairs (3100.7065ms)
✔ actual invalid tool calls repeat under the original step budget; observation never adds an early stop (2435.2265ms)
✔ actual command approval is observed as waiting and denial stays a permission failure (1991.3118ms)
✔ network errors remain model failures with shadow failure evidence, never a fabricated no-progress cause (3501.8394ms)
✔ observer receipt failure cannot change tool results, model budget or completion (1567.6045ms)
✔ a later receipt recovers after an observation write failure without misaligning retained source receipts (2294.3541ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 15107.0841
@@ -0,0 +1,39 @@
✔ reviewed application invalidates old checks, names current SHA and advances through a new approved check to Git preview (6436.7556ms)
✔ skip-tests, foreign task, unknown operations, diagnostic and parent review retain their boundaries (2805.0293ms)
✔ before the first change, real baseline failures persist across later reads; passed baselines and changed sources cannot certify delivery (6966.6314ms)
✔ unchanged proposals cannot hide repeated original-log reads or identical session inspections (4015.6677ms)
✔ reusing a verified proof never resets identical-state detection or creates a new proof (4313.6945ms)
✔ coverage merges adjacent pages, separates changed sources and never claims old Run coverage in a continuation (0.9172ms)
✔ a stop from the event loop interrupts immediate model replies before later tools (1307.251ms)
✔ a stop after the first tool preserves a complete interrupted multi-call protocol group (1865.0502ms)
✔ the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands (4135.5443ms)
✔ denial prevents command execution and produces a paired denied result (1980.3627ms)
✔ stopping during approval interrupts pending calls without executing or replaying them (1713.6922ms)
✔ stopping a running fixture command terminates its own process tree and retains uncertain state (2117.3526ms)
✔ command output decodes split UTF-8 and excludes the workbench key from child environment (998.1406ms)
✔ model-list testing uses a tentative key without changing the saved connection and redacts service errors (6.9138ms)
✔ truncated or repeated model calls fail before execution; tool input validation rejects unknown capabilities (3401.3907ms)
✔ request projection keeps exact tool pairs and complete recent user instructions while preserving disk history (1322.2172ms)
✔ fixed normal exploration, pagination, SHA changes and repeated ranges are external observations, not a score (1.3034ms)
✔ read-only research is valid work; model summaries and unchanged timestamped listings do not become engineering evidence (0.3724ms)
✔ new permissions, network and broken tools are failure evidence; repeated invalid inputs remain candidates (0.4028ms)
✔ waiting for original long checks, review and approvals stays waiting across repeated observations (0.4942ms)
✔ baseline facts, real repairs, current-source check results and requirement evidence have distinct growth (0.2202ms)
✔ bounded memory keeps unknown instead of claiming an unretained range is repeated; Task/Run instances cannot mix (11.7753ms)
✔ actual runtime records growing pages then a repeated page without changing model rounds, stop rules or original tool pairs (5246.9917ms)
✔ actual invalid tool calls repeat under the original step budget; observation never adds an early stop (4955.2993ms)
✔ actual command approval is observed as waiting and denial stays a permission failure (2182.819ms)
✔ network errors remain model failures with shadow failure evidence, never a fabricated no-progress cause (3442.7454ms)
✔ observer receipt failure cannot change tool results, model budget or completion (1530.7152ms)
✔ a later receipt recovers after an observation write failure without misaligning retained source receipts (2445.7101ms)
✔ real applied files, counted checks and current requirement proofs grow after an existing-facts baseline (3353.5978ms)
✔ receipt retention stays aligned at the cap and a foreign step cannot enter the Run (1858.1785ms)
✔ an actual approved long check records its owned running job as waiting before the original counted result (4352.9278ms)
ℹ tests 31
ℹ suites 0
ℹ pass 31
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 45887.3567
@@ -0,0 +1,10 @@
PASS actual runtime pages grow then repeat under the original three-round limit
PASS original observation receipt opens with the actual tool-result provenance
PASS refresh restores the same Task, Run and persisted shadow observations
PASS 390px keeps observation facts and original receipt actions reachable without page overflow
PASS an actual pending approval stays waiting and does not consume the earlier same-turn read twice
PASS refusing the original approval preserves the permission failure and the original tool pairs
PASS selecting historical and current Runs keeps their independent observations
PASS delivery report uses both Runs and independently verifies the original observation receipts
PASS original HTTP 502 remains a model failure and is not relabeled as no progress
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-56799224-bfc5-4c99-a2bf-2b4eb1557b55","success":true,"passed":["actual runtime pages grow then repeat under the original three-round limit","original observation receipt opens with the actual tool-result provenance","refresh restores the same Task, Run and persisted shadow observations","390px keeps observation facts and original receipt actions reachable without page overflow","an actual pending approval stays waiting and does not consume the earlier same-turn read twice","refusing the original approval preserves the permission failure and the original tool pairs","selecting historical and current Runs keeps their independent observations","delivery report uses both Runs and independently verifies the original observation receipts","original HTTP 502 remains a model failure and is not relabeled as no progress"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-56799224-bfc5-4c99-a2bf-2b4eb1557b55\\desktop-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-56799224-bfc5-4c99-a2bf-2b4eb1557b55\\narrow-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-56799224-bfc5-4c99-a2bf-2b4eb1557b55\\waiting-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-56799224-bfc5-4c99-a2bf-2b4eb1557b55\\denied-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-56799224-bfc5-4c99-a2bf-2b4eb1557b55\\historical-run.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-56799224-bfc5-4c99-a2bf-2b4eb1557b55\\network-original-failure.png"],"snapshots":["pages-original.json","approval-waiting.json","approval-denied.json","report-original.json","network-original.json"],"actualElectron":false,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
@@ -0,0 +1,10 @@
PASS actual runtime pages grow then repeat under the original three-round limit
PASS original observation receipt opens with the actual tool-result provenance
PASS refresh restores the same Task, Run and persisted shadow observations
PASS 390px keeps observation facts and original receipt actions reachable without page overflow
PASS an actual pending approval stays waiting and does not consume the earlier same-turn read twice
PASS refusing the original approval preserves the permission failure and the original tool pairs
PASS selecting historical and current Runs keeps their independent observations
PASS delivery report uses both Runs and independently verifies the original observation receipts
PASS original HTTP 502 remains a model failure and is not relabeled as no progress
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-2cb00fda-8b93-4cb5-ba9f-a54e2a38014e","success":true,"passed":["actual runtime pages grow then repeat under the original three-round limit","original observation receipt opens with the actual tool-result provenance","refresh restores the same Task, Run and persisted shadow observations","390px keeps observation facts and original receipt actions reachable without page overflow","an actual pending approval stays waiting and does not consume the earlier same-turn read twice","refusing the original approval preserves the permission failure and the original tool pairs","selecting historical and current Runs keeps their independent observations","delivery report uses both Runs and independently verifies the original observation receipts","original HTTP 502 remains a model failure and is not relabeled as no progress"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-2cb00fda-8b93-4cb5-ba9f-a54e2a38014e\\desktop-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-2cb00fda-8b93-4cb5-ba9f-a54e2a38014e\\narrow-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-2cb00fda-8b93-4cb5-ba9f-a54e2a38014e\\waiting-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-2cb00fda-8b93-4cb5-ba9f-a54e2a38014e\\denied-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-2cb00fda-8b93-4cb5-ba9f-a54e2a38014e\\historical-run.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-2cb00fda-8b93-4cb5-ba9f-a54e2a38014e\\network-original-failure.png"],"snapshots":["pages-original.json","approval-waiting.json","approval-denied.json","report-original.json","network-original.json"],"actualElectron":false,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
@@ -0,0 +1,10 @@
PASS actual runtime pages grow then repeat under the original three-round limit
PASS original observation receipt opens with the actual tool-result provenance
PASS refresh restores the same Task, Run and persisted shadow observations
PASS 390px keeps observation facts and original receipt actions reachable without page overflow
PASS an actual pending approval stays waiting and does not consume the earlier same-turn read twice
PASS refusing the original approval preserves the permission failure and the original tool pairs
PASS selecting historical and current Runs keeps their independent observations
PASS delivery report uses both Runs and independently verifies the original observation receipts
PASS original HTTP 502 remains a model failure and is not relabeled as no progress
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-0091d935-2e0b-4ecd-9cc2-11123008ecc7","success":true,"passed":["actual runtime pages grow then repeat under the original three-round limit","original observation receipt opens with the actual tool-result provenance","refresh restores the same Task, Run and persisted shadow observations","390px keeps observation facts and original receipt actions reachable without page overflow","an actual pending approval stays waiting and does not consume the earlier same-turn read twice","refusing the original approval preserves the permission failure and the original tool pairs","selecting historical and current Runs keeps their independent observations","delivery report uses both Runs and independently verifies the original observation receipts","original HTTP 502 remains a model failure and is not relabeled as no progress"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-0091d935-2e0b-4ecd-9cc2-11123008ecc7\\desktop-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-0091d935-2e0b-4ecd-9cc2-11123008ecc7\\narrow-pages.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-0091d935-2e0b-4ecd-9cc2-11123008ecc7\\waiting-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-0091d935-2e0b-4ecd-9cc2-11123008ecc7\\denied-approval.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-0091d935-2e0b-4ecd-9cc2-11123008ecc7\\historical-run.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-ui-0091d935-2e0b-4ecd-9cc2-11123008ecc7\\network-original-failure.png"],"snapshots":["pages-original.json","approval-waiting.json","approval-denied.json","report-original.json","network-original.json"],"actualElectron":false,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,299 @@
import { verifyNodeBinding } from './environment/environment-inspector.mjs';
import { verifyEnvironmentPreparation } from './environment/environment-evidence.mjs';
import { inspectProject } from './project-inspector.mjs';
import { ChangeSetManager } from './workspaces/change-sets.mjs';
import { verifyPlanEvidence } from './context/request-plan.mjs';
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
import { projectWorkspaceIdentity, unresolvedWorkspaces } from '../shared/contracts/workspaces.mjs';
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 { RequirementReview } from './tasks/requirement-review.mjs';
import { inspectTurnProgress } from './context/turn-progress-recorder.mjs';
import { FileResults } from './tasks/file-results.mjs';
import { taskContract } from '../shared/contracts/task-control.mjs';
import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
existing_verified: '当前成果已核对,无新增修改', needs_requirements: '用户要求仍有待复核事项', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
export function verifiedCheck(store, session, inspection) {
const task = store.core.task.get(session.taskId);
const job = store.core.check_job.get(task?.verification.checkJobId);
if (!job || job.sessionId !== session.id || job.taskId !== task.id || job.projectId !== session.projectId
|| job.status !== 'passed' || job.stale || !inspection.scope.complete) return null;
const same = job.sourceFingerprint ? job.sourceFingerprint === inspection.sourceFingerprint : job.fingerprint === inspection.fingerprint;
if (!same || !job.results.length || job.results.some(result => result.status !== 'passed' || result.exitCode !== 0)
|| !job.results.some(result => result.kind === 'test' && result.tests?.passed > 0 && result.tests.passed === result.tests.total && !result.tests.failed && !result.tests.skipped && !result.tests.cancelled)) return null;
try { verifyNodeBinding(store.project(session.projectId),job.environment); verifyEnvironmentPreparation(store,session.projectId,job.environment); } catch { return null; }
for (const result of job.results) {
if (!result.logArtifactId) return null;
try {
const artifact = store.owned('artifact', result.logArtifactId, session.id);
if (artifact.taskId !== task.id || artifact.kind !== 'check-log') return null;
store.artifactStore.read(artifact);
verifyPythonCheckEvidence(store, session, job, result);
} catch { return null; }
}
return job;
}
export class DeliveryReporter {
constructor(store, { redact = String } = {}) { this.store = store; this.redact = redact; }
async create(session, { job = null, inspection = null } = {}) {
const taskId = session.taskId, runId = session.runId;
const task = this.store.owned('task', taskId, session.id);
const run = this.store.owned('run', runId, session.id);
const project = this.store.project(session.projectId);
await verifyWorkspaceProject(this.store, project);
inspection ??= await inspectProject(project);
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)
.map(value => ({ id: value.id, tool: value.tool, status: value.state }));
requiresVerification.push(...unresolvedWorkspaces(this.store, project.id).map(value => ({ id: value.id, tool: 'workspace', status: value.status })));
const unresolved = jobs.filter(value => value.requiresVerification || value.status === 'unknown');
const checkJobs = [...this.store.core.check_job.values()].filter(value => value.taskId === taskId);
const pythonEvidence = new Map();
for (const checkJob of checkJobs) if (!checkJob.stale && checkJob.sourceFingerprint === inspection.sourceFingerprint) {
for (const result of checkJob.results.filter(value => value.engine === 'python' && value.status === 'passed')) {
try { verifyPythonCheckEvidence(this.store, session, checkJob, result); pythonEvidence.set(result.id, { verified: true }); }
catch (error) {
pythonEvidence.set(result.id, { verified: false, error: error.message });
requiresVerification.push({ id: result.id, tool: 'python_check', status: 'evidence_unverified' });
}
}
}
const sets = [...this.store.core.change_set.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
const changeSets = sets.map(set => {
let snapshotVerified = true, snapshotError = null;
try { new ChangeSetManager(this.store).snapshots(session, set); } catch (error) { snapshotVerified = false; snapshotError = error.message; }
return { id: set.id, taskId: set.taskId, runId: set.runId, status: set.status, fingerprint: set.fingerprint,
paths: set.files.map(file => file.path), snapshotVerified, snapshotError, requiresVerification: !!set.requiresVerification,
summary: set.summary, verifiedAt: set.verifiedAt ?? null, finishedAt: set.finishedAt ?? null };
});
requiresVerification.push(...changeSets.filter(set => set.requiresVerification || !set.snapshotVerified)
.map(set => ({ id: set.id, tool: 'change_set', status: set.status })));
const commits = jobs.filter(value => value.status === 'completed' && value.commit && value.sourceFingerprint === inspection.sourceFingerprint);
const contextCache = new Map();
const contextPlans = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === taskId).map(plan => {
let evidenceVerified = true, evidenceError = null;
try {
verifyPlanEvidence(this.store, session, plan, contextCache);
} catch (error) { evidenceVerified = false; evidenceError = error.message; }
return { id: plan.id, runId: plan.runId, stepId: plan.stepId, status: plan.status, requestSha256: plan.requestSha256, requestBytes: plan.requestBytes,
requestArtifactId: plan.requestArtifactId, planArtifactId: plan.artifactId, estimatedInputTokens: plan.estimatedInputTokens,
beforeInputTokens: plan.beforeInputTokens, beforeBytes: plan.beforeBytes, estimateMethod: plan.estimateMethod, budget: plan.budget,
archivedGroups: plan.archivedGroups, retainedMessages: plan.retainedMessages, actualUsage: plan.actualUsage, requestAttempts: plan.requestAttempts,
historyIndexArtifactId: plan.historyIndexArtifactId, historyIndexSha256: plan.historyIndexSha256,
workingSetArtifactId: plan.workingSetArtifactId ?? null, workingSetSha256: plan.workingSetSha256 ?? null,
workingSetEntries: plan.workingSetEntries ?? 0, workingSetViewVersion: plan.workingSetViewVersion ?? 1,
workingRetentionTokens: plan.workingRetentionTokens ?? 0,
latestToolsArtifactId: plan.latestToolsArtifactId ?? null, latestToolsSha256: plan.latestToolsSha256 ?? null,
latestToolsEntries: plan.latestToolsEntries ?? 0, evidenceVerified, evidenceError };
});
requiresVerification.push(...contextPlans.filter(plan => !plan.evidenceVerified).map(plan => ({ id: plan.id, tool: 'model_context', status: 'evidence_unverified' })));
const deliveryReview = pendingDeliveryReview(this.store, session);
const browserVerification = await currentBrowserVerification(this.store, session, inspection);
const planner = new TaskPlanManager(this.store), taskPlan = await planner.inspect(session, { inspection, candidates: false });
const requirements = await new RequirementReview(this.store, { planner }).inspect(session, { inspection });
const taskPlanHistory = [...this.store.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
try { planner.planFor(session, value.id); evidenceVerified = true; } catch (error) { evidenceError = error.message; }
return { id: value.id, runId: value.runId, revision: value.revision, parentPlanId: value.parentPlanId, steps: value.steps,
requirementsSha256: value.requirementsSha256, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256, evidenceVerified, evidenceError };
});
const taskProofs = [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ id: value.id, runId: value.runId, planId: value.planId, stepKey: value.stepKey, status: value.status, evidenceId: value.evidenceId,
outcome: value.outcome, error: value.error, createdAt: value.createdAt, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256 }));
const browserChecks = [...this.store.core.browser_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
if (value.resultArtifactId) { try { verifyBrowserJob(this.store, session, value); evidenceVerified = true; } catch (error) { evidenceError = error.message; } }
if (value.requiresVerification || value.resultArtifactId && !evidenceVerified) requiresVerification.push({ id: value.id, tool: 'browser_check', status: 'evidence_unverified' });
return { id: value.id, taskId: value.taskId, runId: value.runId, planId: value.planId, status: value.status, summary: value.summary,
sourceFingerprint: value.sourceFingerprint, buildSha256: value.buildSha256, assertions: value.assertions, screenshots: value.screenshots,
resultArtifactId: value.resultArtifactId ?? null, resultSha256: value.resultSha256 ?? null, cleanup: value.cleanup ?? null,
requiresVerification: !!value.requiresVerification, evidenceVerified, evidenceError, acknowledgedAt: value.acknowledgedAt ?? null };
});
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('核对页面结果期间任务已切换,请重新生成报告。'), { status: 409 });
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'
: requirements.configured && !requirements.all_resolved ? 'needs_requirements'
: 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: requirements.status, note: '源码和检查证据不代替业务需求验收。' },
requirements,
turnObservations: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ runId: value.id, ...inspectTurnProgress(this.store, session, value) })),
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,
consumption: structuredClone(value.consumption ?? []),
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })),
usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null },
changes: changes.map(value => ({ id: value.id, path: value.path, status: value.status, reason: value.reason, baseSha256: value.baseSha256,
sha256: value.sha256, changeSetId: value.changeSetId ?? null, appliedAt: value.appliedAt ?? null, additions: value.additions, deletions: value.deletions })),
changeSets,
...(deliveryReview ? { deliveryReview: { planId: deliveryReview.id, status: 'pending', paths: deliveryReview.paths } } : {}),
contextPlans,
browserVerification, browserChecks,
taskPlan, taskPlanHistory, taskProofs,
checks: checkJobs.map(value => ({ id: value.id, status: value.status, planId: value.planId,
...(value.environment ? { environment:value.environment } : {}),
contractArtifactId: this.store.core.check_plan.get(value.planId)?.contractArtifactId ?? null,
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
sourceFingerprint: value.sourceFingerprint ?? null, startedAt: value.startedAt, finishedAt: value.finishedAt,
results: value.results.map(result => ({ ...result, logExcerpt: undefined,
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null,
...(result.engine === 'python' ? { pythonEvidence: pythonEvidence.get(result.id) ?? { verified: false, state: 'historical_or_not_passed' } } : {}) })) })),
verifiedCheckJobId: check?.id ?? null,
deliveries: jobs.map(value => ({ id: value.id, status: value.status, commit: value.commit ?? null, expectedCommit: value.expectedCommit ?? null,
parent: value.parent, sourceFingerprint: value.sourceFingerprint, paths: value.paths, summary: value.summary, requiresVerification: !!value.requiresVerification,
workspacePreserved: value.workspacePreserved ?? null, indexPreserved: value.indexPreserved ?? null, finishedAt: value.finishedAt })),
requiresVerification,
limitations: ['本切片验证已选工程检查和提交范围;业务需求验收另行记录。', '提交为本地普通提交,不执行仓库hooks和GPG签名。', '请求输入为本地UTF-8估算;服务实际分词和用量另行记录。', '未配置模型单价,费用未知。'],
};
const safe = JSON.parse(this.redact(JSON.stringify(report)));
const markdown = renderDeliveryMarkdown(safe);
const jsonArtifact = this.store.artifactStore.write(session, run, safe, { kind: 'delivery-report' });
const markdownArtifact = this.store.artifactStore.write(session, run, markdown, { kind: 'delivery-report-markdown', mediaType: 'text/markdown' });
this.store.core.artifact.set(jsonArtifact.id, jsonArtifact); this.store.core.artifact.set(markdownArtifact.id, markdownArtifact);
if (job) { job.reportArtifactId = jsonArtifact.id; job.reportMarkdownArtifactId = markdownArtifact.id; }
this.store.save(session, { type: 'delivery.report', detail: { status, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id } });
return { report: safe, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id };
}
}
export function renderDeliveryMarkdown(report) {
const lines = ['# 项目交付报告', '', '**' + report.statusLabel + '**', '', '生成时间:' + report.generatedAt, '',
'项目:' + report.project.name, '项目目录:' + report.project.root, 'Task:' + report.task.id, '',
'## 任务与范围', '', report.task.goal, '',
'源码指纹:' + report.source.fingerprint, '当前Git HEAD:' + (report.source.gitHead ?? '未启用'),
'分支:' + (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.requirements) {
lines.push('', '## 用户要求与证据', '', report.requirements.note, '', '复核状态:' + report.requirements.status,
'', '| 要求 / 条件 | 用户原文来源 | 修订 | 复核状态 | 原证据 / 下一步 |', '| --- | --- | --- | --- | --- |');
for (const item of report.requirements.items) lines.push('| ' + [item.title + ' / ' + item.criterion,
item.source.kind + ':' + item.source.id + ' [' + item.source.start + ',' + item.source.end + ') ' + item.source.quote,
item.revision, item.status, item.error ?? item.user_note ?? item.proof_artifact_id ?? (item.status === 'not_requested' ? '按约定未执行,非测试通过' : '选择实际证据或完成用户验收')].map(escapeCell).join(' | ') + ' |');
if (report.requirements.unreviewed_sources?.length) lines.push('', '尚未审阅的用户来源:' + report.requirements.unreviewed_sources.join('、'));
if (report.requirements.error) lines.push('', report.requirements.error);
}
if (report.turnObservations?.some(row => row.recorded || row.error)) {
lines.push('', '## 单轮观察(仅记录)', '', '外显事实分类不改变停止、权限或预算;不是自主交付收益证明。');
for (const run of report.turnObservations) if (run.error) lines.push('', escapeCell(run.runId + ':' + (typeof run.error === 'string' ? run.error : '观察未能记录,原执行结果保留。')), '');
lines.push('', '| Run / 轮次 | 观察 | 新读取字符 | 重复读取 | 新失败 / 重复失败 | 原收据核对 |', '| --- | --- | --- | --- | --- | --- |');
for (const run of report.turnObservations) for (const turn of run.turns) lines.push('| ' + [run.runId + ' / ' + (turn.stepIndex ?? turn.phase),
turn.classification, turn.delta.read_characters, turn.delta.repeated_reads, turn.delta.new_failures + ' / ' + turn.delta.repeated_failures,
run.evidence_verified ? '原字节已核对' : run.error].map(escapeCell).join(' | ') + ' |');
}
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
'| 步骤 / 通过条件 | 状态 | 前置依赖 | 原证据 |', '| --- | --- | --- | --- |');
for (const step of report.taskPlan.steps) lines.push('| ' + [step.title + ' / ' + step.criterion, step.status,
step.depends_on.join(', ') || '无', step.evidence?.id ?? '尚未核验'].map(escapeCell).join(' | ') + ' |', ...(step.error ? ['', step.error, ''] : []));
if (report.taskPlan.error) lines.push('', report.taskPlan.error);
lines.push('', '任务计划固定实际操作范围;业务语义验收另行记录。', '', '### 原计划与核验工件', '');
for (const plan of report.taskPlanHistory ?? []) lines.push('计划 ' + plan.revision + ':' + plan.contractArtifactId + ' · SHA256 ' + plan.contractSha256);
for (const proof of report.taskProofs ?? []) lines.push('步骤 ' + proof.stepKey + ' · ' + proof.status + ':' + proof.contractArtifactId + ' · SHA256 ' + proof.contractSha256);
}
if (report.workspace?.kind === 'managed-worktree') lines.push('', '## 独立开发工作区', '', '工作区:' + report.workspace.workspaceId,
'来源项目:' + report.workspace.sourceProjectId, '来源目录:' + report.workspace.sourceRoot,
'起始提交:' + report.workspace.baseCommit, '独立分支:' + report.workspace.branch,
'交付保存在此分支;合并回来源项目需要另行审查。');
if (report.changeSets?.length) {
lines.push('', '## 多文件变更集', '', '| 批次 | 实际状态 | 快照 | 审查指纹 |', '| --- | --- | --- | --- |');
for (const set of report.changeSets) lines.push('| ' + [set.id, set.status, set.snapshotVerified ? 'SHA256校验通过' : '需要核对', set.fingerprint].map(escapeCell).join(' | ') + ' |',
'', set.summary ?? '', '');
}
lines.push('', '## 实际检查', '', '| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |', '| --- | --- | --- | --- | --- |');
for (const job of report.checks) for (const result of job.results) lines.push('| ' + [job.id.slice(0, 8) + ' / ' + result.command,
job.stale ? '源码已变化 / ' + result.status : result.status, result.exitCode ?? '未知', result.tests ? result.tests.passed + '/' + result.tests.total : '不适用或未知', result.logSha256 ?? '未知'].map(escapeCell).join(' | ') + ' |');
const environments=report.checks.filter(job=>job.environment);
if(environments.length){
lines.push('','### 实际依赖环境','','| 检查记录 | Node / npm | 声明与运行时输入 | 实际依赖字节 | 准备记录 |','| --- | --- | --- | --- | --- |');
for(const job of environments)lines.push('| '+[job.id,job.environment.runtime.node.version+' / '+(job.environment.runtime.npm?.version??'未知'),job.environment.dependencyInputs,job.environment.installed.sha256??'没有依赖目录',job.environment.preparation?.jobId??'已有环境,无所属准备凭据'].map(escapeCell).join(' | ')+' |');
lines.push('','环境准备只记录安装;以上工程检查结果另行判定。');
}
const pythonResults = report.checks.flatMap(job => job.results.filter(result => result.python));
if (pythonResults.length) {
lines.push('', '### Python实际执行', '', '| 检查 | 解释器 | 版本 | 结构化结果SHA256 |', '| --- | --- | --- | --- |');
for (const result of pythonResults) lines.push('| ' + [result.command, result.python.runtime.executable, result.python.runtime.version, result.metricsSha256 ?? '未返回'].map(escapeCell).join(' | ') + ' |',
'', '运行器SHA256:' + result.python.runner.sha256, '封存输入SHA256:' + result.python.inputSha256,
...(result.compilation ? ['语法编译:' + result.compilation.compiled + '/' + result.compilation.total + ' 个源码文件。'] : []));
}
if (report.browserChecks?.length || report.browserVerification?.required) {
lines.push('', '## 实际页面验收', '', '当前页面验收:' + report.browserVerification.status, '', '| 浏览器Job | 状态 | 实际断言 | 原结果SHA256 |', '| --- | --- | --- | --- |');
for (const check of report.browserChecks ?? []) {
lines.push('| ' + [check.id, check.status, check.assertions.passed + '/' + check.assertions.total, check.evidenceVerified ? check.resultSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
for (const image of check.screenshots) lines.push('', '截图 ' + image.label + ' · ' + image.width + '×' + image.height + ' · SHA256 ' + image.sha256);
}
lines.push('', '浏览器页面属于工程输入;观察或截图不代替断言,源码或构建变化后需要重新检查。', '');
}
lines.push('', '## Git交付', '');
if (report.deliveryReview) lines.push('Git提交预览已保存,等待确认。计划:' + report.deliveryReview.planId, '');
if (!report.deliveries.length) lines.push('尚无内置Git提交记录。');
for (const delivery of report.deliveries) lines.push('- ' + delivery.status + ' · ' + (delivery.commit ?? '实际结果未确认') + ' · ' + delivery.paths.join(', '),
' ' + (delivery.summary ?? ''));
lines.push('', '## 模型与用量', '', 'Run型号为启动配置;每次实际发送与返回型号见下表。型号标识或登记映射不认证底层模型权重。', '', '| Run | 启动型号 | 状态 | 已报告tokens |', '| --- | --- | --- | --- |');
for (const run of report.runs) lines.push('| ' + [run.id, run.model?.mode === 'demo' ? '离线固定演示' : run.model?.model ?? '未记录',
run.status, run.usage?.totalTokens ?? 0].map(escapeCell).join(' | ') + ' |');
lines.push('', '| 尝试 | 请求型号 | 上游报告型号 | 核对结果 | 原响应 SHA256 |', '| --- | --- | --- | --- | --- |');
for (const run of report.runs) {
for (const receipt of run.consumption ?? []) {
const identity = receipt.modelIdentity;
lines.push('| ' + [receipt.attemptId, identity?.requestedModel ?? receipt.model ?? '未记录', identity?.reportedModels?.join(', ') || '未记录',
modelIdentityLabel(identity), identity?.responseSource?.sha256 ?? '未记录'].map(escapeCell).join(' | ') + ' |');
if (identity?.mapping) lines.push('', '用户登记的映射依据:' + escapeCell(identity.mapping.source));
}
if (!run.consumption?.length && run.usage?.requests) lines.push('', 'Run ' + run.id + ' 的历史记录未保存返回型号核对,不能从启动配置补推。');
}
lines.push('', '累计已报告:' + (report.usage.totalTokens ?? 0) + ' tokens;未报告请求:' + (report.usage.unknownRequests ?? 0) + '。费用:未知。', '', '## 尚待确认', '');
if (report.contextPlans?.length) {
const at = lines.length - 2;
const contextLines = ['', '## 请求上下文', '', '| 请求 | 状态 | 输入估算 | 已报告输入 | 省略组 | 正文SHA256校验 |', '| --- | --- | --- | --- | --- | --- |'];
for (const plan of report.contextPlans) contextLines.push('| ' + [plan.id, plan.status, plan.estimatedInputTokens,
plan.actualUsage?.prompt_tokens ?? '未返回', plan.archivedGroups, plan.evidenceVerified ? plan.requestSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
lines.splice(at, 0, ...contextLines, '');
}
for (const value of report.requiresVerification) lines.push('- ' + value.tool + ' · ' + value.id + ' · ' + value.status);
for (const note of report.limitations) lines.push('- ' + note);
return lines.join('\n') + '\n';
}
@@ -0,0 +1,56 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
const root = path.resolve('docs/turn-progress-b-evidence'), qa = path.resolve('.qa/requirements-progress');
assert.equal(fs.existsSync(root), false, 'Do not overwrite an existing stage seal.'); fs.mkdirSync(root);
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
const copy = (source, relative) => {
assert.equal(fs.lstatSync(source).isSymbolicLink(), false); const target = path.join(root, relative);
if (fs.statSync(source).isDirectory()) { fs.mkdirSync(target, { recursive: true }); for (const name of fs.readdirSync(source)) copy(path.join(source, name), relative + '/' + name); }
else { fs.mkdirSync(path.dirname(target), { recursive: true }); fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL); }
};
const sourceFiles = [
'src/core/context/turn-progress.mjs', 'src/core/context/turn-progress-recorder.mjs', 'src/core/delivery-report.mjs', 'src/server/runtime.mjs',
'src/client/TurnProgress.tsx', 'src/client/TaskPanel.tsx', 'src/client/TaskPanel.css', 'src/client/types.ts', 'tests/turn-progress.test.mjs',
'scripts/verify-turn-progress-ui.mjs', 'scripts/verify-turn-progress-evidence.mjs', 'scripts/verify-adoption-evidence.mjs', 'scripts/seal-turn-progress-evidence.mjs',
].map(file => { const snapshot = 'source/' + file; copy(path.resolve(file), snapshot); return { path: file, snapshot }; });
const testRuns = [
['shadow-first.tap', 11, 9, 2], ['shadow-second.tap', 12, 12, 0], ['shadow-related.tap', 68, 68, 0],
['shadow-final.tap', 31, 31, 0], ['shadow-source-final.tap', 31, 31, 0],
].map(([name, tests, passed, failed]) => { copy(path.join(qa, name), 'logs/' + name); return { path: 'logs/' + name, tests, passed, failed }; });
for (const name of ['build-shadow-first.log', 'build-shadow-second.log', 'build-shadow-final.log', 'build-shadow-check-wait.log', 'build-shadow-source-final.log', 'official-readonly-boundary.json']) copy(path.join(qa, name), 'logs/' + name);
const uiRuns = [], observedRuns = [];
for (const [name, folder, final] of [
['shadow-ui-first', 'web-first', false], ['shadow-electron-first', 'electron-first', false],
['shadow-ui-final', 'web-touch', false], ['shadow-electron-final', 'electron-touch', false],
['shadow-ui-source-final', 'web-final', true], ['shadow-electron-source-final', 'electron-final', true],
]) {
const log = fs.readFileSync(path.join(qa, name + '.log'), 'utf8'); copy(path.join(qa, name + '.log'), 'logs/' + name + '.log');
const result = JSON.parse(log.trim().split(/\r?\n/).at(-1)), source = path.resolve(result.directory), relative = 'ui/' + folder;
assert.ok(source.startsWith(qa + path.sep)); assert.equal(result.success, true); copy(source, relative);
uiRuns.push({ path: relative + '/result.json', success: true, passed: 9 }); if (final) observedRuns.push(relative);
}
const caseReview = {
scope: 'Fixed public-fact cases manually reviewed against original assertions; no population accuracy or model benefit claim.',
cases: [
{ case: 'normal_exploration', expected: 'new observed content is evidence growth', evidence: 'logs/shadow-source-final.tap', assertion: 'fixed normal exploration, pagination, SHA changes and repeated ranges' },
{ case: 'pagination_and_repetition', expected: '10 new + 10 new + repeated candidate, original step_limit', evidence: 'ui/web-final/pages-original.json' },
{ case: 'read_only_research', expected: 'reading is useful; summary wording is not additional engineering evidence; no shadow interruption', evidence: 'logs/shadow-source-final.tap', assertion: 'read-only research is valid work' },
{ case: 'long_check', expected: 'approved actual running job stays waiting, then counted result', evidence: 'logs/shadow-source-final.tap', assertion: 'actual approved long check' },
{ case: 'failure_repair_evidence', expected: 'applied file, actual counted check and current requirement proof grow after baseline', evidence: 'logs/shadow-source-final.tap', assertion: 'real applied files, counted checks and current requirement proofs' },
{ case: 'permission_denial', expected: 'waiting then original permission failure; earlier same-turn read consumed once', evidence: 'ui/electron-final/approval-denied.json' },
{ case: 'broken_tool_or_network', expected: 'new failure is evidence; original failure categories remain distinct', evidence: 'logs/shadow-source-final.tap', assertion: 'new permissions, network and broken tools' },
{ case: 'invalid_input_repetition', expected: 'repeat candidate, no new early stop; original four-request step_limit', evidence: 'logs/shadow-source-final.tap', assertion: 'actual invalid tool calls repeat under the original step budget' },
{ case: 'bounded_unknown', expected: 'unretained facts stay unknown; old receipts retained and scope cannot mix', evidence: 'logs/shadow-source-final.tap', assertion: 'receipt retention stays aligned at the cap' },
],
limitations: ['No real model delivery sample.', 'No intervention thresholds or global false-positive/false-negative rate.', 'No Purge comparison or network recovery claim.'],
};
fs.writeFileSync(path.join(root, 'case-review.json'), JSON.stringify(caseReview, null, 2));
const walk = directory => fs.readdirSync(directory, { withFileTypes: true }).flatMap(row => row.isDirectory() ? walk(path.join(directory, row.name)) : [path.join(directory, row.name)]);
const files = walk(root).map(file => { const bytes = fs.readFileSync(file); return { path: path.relative(root, file).replaceAll('\\', '/'), bytes: bytes.length, sha256: digest(bytes) }; }).sort((a, b) => a.path.localeCompare(b.path));
const manifest = { kind: 'adoption-stage-evidence', stage: 'turn-progress-b', status: 'development_slice_validated_not_released',
realModelRequests: 0, officialServiceChanged: false, sourceFiles, testRuns, uiRuns, observedRuns, files, bytes: files.reduce((sum, row) => sum + row.bytes, 0) };
fs.writeFileSync(path.join(root, 'manifest.json'), JSON.stringify(manifest, null, 2));
console.log(JSON.stringify({ root, files: files.length, bytes: manifest.bytes, sourceFiles: sourceFiles.length, uiRuns: uiRuns.length }));
@@ -0,0 +1,53 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
const [directory, ...options] = process.argv.slice(2);
if (!directory || options.some((value, index) => value !== '--index' && value !== '--source-ref' && options[index - 1] !== '--source-ref'))
throw new Error('Usage: node scripts/verify-adoption-evidence.mjs <sealed-directory> [--index] [--source-ref <commit|:>]');
const root = path.resolve(directory), gitRoot = process.cwd(), useIndex = options.includes('--index');
const sourceRef = options.includes('--source-ref') ? options[options.indexOf('--source-ref') + 1] : null;
if (sourceRef) assert.ok(sourceRef === ':' || /^[a-f0-9]{7,40}$/.test(sourceRef));
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
const git = object => execFileSync('git', ['show', object], { cwd: gitRoot, windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
const contained = rel => {
assert.ok(typeof rel === 'string' && rel && !rel.includes('\\') && !path.isAbsolute(rel) && !rel.split('/').some(part => !part || part === '..'));
const file = path.resolve(root, rel); assert.ok(file.startsWith(root + path.sep)); assert.ok(fs.lstatSync(file).isFile()); return file;
};
const manifestBytes = fs.readFileSync(path.join(root, 'manifest.json')), manifest = JSON.parse(manifestBytes);
assert.equal(manifest.kind, 'adoption-stage-evidence'); assert.equal(manifest.realModelRequests, 0); assert.equal(manifest.officialServiceChanged, false);
const names = new Set(); let bytes = 0;
for (const row of manifest.files) {
assert.ok(!names.has(row.path)); names.add(row.path); const data = fs.readFileSync(contained(row.path));
assert.equal(data.length, row.bytes, row.path); assert.equal(sha(data), row.sha256, row.path); bytes += data.length;
if (row.path.endsWith('.png')) assert.equal(data.subarray(0, 8).toString('hex'), '89504e470d0a1a0a');
if (useIndex) assert.equal(sha(git(':' + path.relative(gitRoot, path.join(root, row.path)).replaceAll('\\', '/'))), row.sha256);
}
assert.equal(bytes, manifest.bytes);
const walk = dir => fs.readdirSync(dir, { withFileTypes: true }).flatMap(row => {
const file = path.join(dir, row.name); assert.equal(fs.lstatSync(file).isSymbolicLink(), false);
return row.isDirectory() ? walk(file) : [path.relative(root, file).replaceAll('\\', '/')];
});
assert.deepEqual(walk(root).filter(name => name !== 'manifest.json').sort(), [...names].sort());
if (useIndex) assert.equal(sha(git(':' + path.relative(gitRoot, path.join(root, 'manifest.json')).replaceAll('\\', '/'))), sha(manifestBytes));
for (const check of manifest.testRuns ?? []) {
const log = fs.readFileSync(contained(check.path), 'utf8');
for (const [label, count] of Object.entries({ tests: check.tests, pass: check.passed, fail: check.failed }))
assert.match(log, new RegExp('(?:ℹ |# )' + label + ' ' + count + '(?:\\r?\\n|$)'));
}
for (const check of manifest.uiRuns ?? []) {
const result = JSON.parse(fs.readFileSync(contained(check.path), 'utf8'));
assert.equal(result.success, check.success); assert.equal(result.passed.length, check.passed); assert.equal(result.realModelRequests, 0);
}
if (sourceRef) for (const row of manifest.sourceFiles) {
assert.ok(names.has(row.snapshot)); assert.ok(row.path && !row.path.includes('..') && !path.isAbsolute(row.path));
const original = fs.readFileSync(contained(row.snapshot)); const recorded = git(sourceRef === ':' ? ':' + row.path : sourceRef + ':' + row.path);
// Source snapshots preserve original checkout bytes. The repository's text
// attributes store LF; accept only that declared text representation change.
const gitText = Buffer.from(original.toString('utf8').replaceAll('\r\n', '\n'));
assert.equal(sha(recorded), sha(original) === sha(recorded) ? sha(original) : sha(gitText), 'Source ref differs: ' + row.path);
}
console.log(JSON.stringify({ ok: true, stage: manifest.stage, files: names.size, bytes, testRuns: manifest.testRuns?.length ?? 0,
uiRuns: manifest.uiRuns?.length ?? 0, sourceFiles: manifest.sourceFiles.length, indexChecked: useIndex, sourceRef, realModelRequests: 0 }));
@@ -0,0 +1,68 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
const [directory, ...options] = process.argv.slice(2), root = path.resolve(directory ?? 'docs/turn-progress-b-evidence');
const digest = value => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest('hex');
const read = relative => { const file = path.resolve(root, relative); assert.ok(file.startsWith(root + path.sep)); return fs.readFileSync(file); };
const json = relative => JSON.parse(read(relative));
execFileSync(process.execPath, ['scripts/verify-adoption-evidence.mjs', root, ...options], { stdio: 'pipe' });
const manifest = json('manifest.json'); assert.equal(manifest.stage, 'turn-progress-b');
let snapshots = 0, receipts = 0, toolResults = 0, originalArtifacts = 0;
for (const directory of manifest.observedRuns) {
const result = json(directory + '/result.json'), index = new Map(json(directory + '/source-artifacts.json').map(row => [row.id, row]));
assert.equal(result.success, true); assert.equal(result.passed.length, 9); assert.equal(result.realModelRequests, 0);
const artifact = id => { const row = index.get(id); assert.ok(row, 'Missing original artifact: ' + id); const bytes = read(directory + '/' + row.path);
assert.equal(digest(bytes), row.sha256); assert.equal(bytes.length, row.bytes); return { row, bytes }; };
for (const id of index.keys()) { artifact(id); originalArtifacts++; }
const snapshot = name => json(directory + '/' + name + '.json');
for (const name of result.snapshots) {
const value = json(directory + '/' + name), { session, execution } = value, run = execution.run, shadow = run.progressShadow; snapshots++;
assert.deepEqual(shadow.scope, { projectId: session.projectId, sessionId: session.id, taskId: run.taskId, runId: run.id });
assert.equal(shadow.mode, 'shadow'); assert.equal(shadow.turns.length, run.progressShadowArtifactIds.length);
const ranges = new Map();
for (const [i, turn] of shadow.turns.entries()) {
const original = artifact(run.progressShadowArtifactIds[i]); assert.equal(original.row.kind, 'turn-progress-shadow');
assert.equal(digest(JSON.parse(original.bytes)), digest(turn)); assert.equal(turn.runId, run.id); assert.equal(turn.taskId, run.taskId); receipts++;
let growth = 0, repeated = 0;
for (const ref of turn.tools) {
if (ref.tool === 'model_request') {
const event = session.events.find(row => row.id === ref.source_event_id && row.runId === run.id);
assert.ok(event?.diagnostic); assert.equal(event.diagnostic.id, ref.id); assert.equal(digest(event.diagnostic), ref.diagnostic_sha256);
if (ref.result_artifact_id) assert.equal(artifact(ref.result_artifact_id).row.sha256, ref.result_sha256);
continue;
}
const event = session.events.find(row => row.invocationId === ref.id && row.runId === run.id && row.taskId === run.taskId);
assert.ok(event); assert.equal(event.tool, ref.tool); assert.equal(event.artifactId, ref.result_artifact_id);
const call = session.providerMessages.flatMap(row => row.tool_calls ?? []).find(row => row.id === event.toolCallId);
assert.ok(call); assert.equal(call.function.name, ref.tool); assert.equal(digest(String(call.function.arguments)), ref.args_sha256);
const source = artifact(ref.result_artifact_id); assert.equal(source.row.kind, 'tool-result'); assert.equal(source.row.sha256, ref.result_sha256); toolResults++;
const metadata = execution.artifacts.find(row => row.id === ref.result_artifact_id);
assert.ok(metadata); assert.equal(metadata.runId, run.id); assert.equal(metadata.taskId, run.taskId); assert.equal(metadata.projectId, session.projectId);
const result = JSON.parse(source.bytes);
if (ref.tool !== 'read_file' || typeof result.content !== 'string') continue;
const start = result.offset ?? 0, end = result.next_offset ?? start + result.content.length;
assert.equal(end - start, result.content.length);
const key = JSON.stringify([result.path, result.sha256, result.range_start_line ?? result.start_line ?? null, result.range_end_line ?? result.end_line ?? null]);
const covered = ranges.get(key) ?? new Set(); let added = 0;
for (let position = start; position < end; position++) if (!covered.has(position)) { covered.add(position); added++; }
ranges.set(key, covered); growth += added; if (!added) repeated++;
}
assert.equal(turn.delta.read_characters, growth); assert.equal(turn.delta.repeated_reads, repeated);
if (turn.phase === 'waiting') assert.equal(turn.classification, 'waiting');
}
}
const pages = snapshot('pages-original'), settled = pages.execution.run.progressShadow.turns.filter(row => row.phase === 'settled');
assert.equal(pages.execution.run.stopReason, 'step_limit'); assert.deepEqual(settled.map(row => [row.stepIndex, row.classification, row.delta.read_characters]),
[[1, 'evidence_growth', 10], [2, 'evidence_growth', 10], [3, 'repeated_read_candidate', 0]]);
const waiting = snapshot('approval-waiting'), denied = snapshot('approval-denied'), failure = snapshot('network-original');
assert.equal(waiting.session.status, 'awaiting_approval'); assert.equal(waiting.execution.run.progressShadow.turns.at(-1).waiting[0].kind, 'approval');
assert.equal(denied.session.taskId, pages.session.taskId); assert.notEqual(denied.execution.run.id, pages.execution.run.id);
assert.equal(denied.session.approvals.at(-1).status, 'denied'); assert.equal(denied.execution.run.progressShadow.turns.find(row => row.phase === 'settled').delta.repeated_reads, 0);
assert.equal(failure.session.status, 'failed'); assert.equal(failure.session.lastFailure.httpStatus, 502); assert.equal(failure.execution.run.stopReason, null);
assert.equal(failure.execution.run.progressShadow.turns.at(-1).classification, 'new_failure_evidence');
const report = json(directory + '/report.json'); assert.equal(report.turnObservations.length, 2); assert.ok(report.turnObservations.every(row => row.evidence_verified));
}
console.log(JSON.stringify({ ok: true, runs: manifest.observedRuns.length, snapshots, receipts, toolResults, originalArtifacts, realModelRequests: 0, replayedOperations: 0 }));
@@ -0,0 +1,151 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { chromium, _electron } from 'playwright';
import { fixture, compatibleFixture, launchWorkbench, until, call, completion } from '../tests/helpers.mjs';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
// Existing UI-verifier convention: a real browser/Electron, isolated data and a
// localhost model protocol fixture. No configured provider or real key is used.
const desktop = process.argv.includes('--desktop');
const directory = path.resolve('.qa/requirements-progress', (desktop ? 'shadow-electron-' : 'shadow-ui-') + randomUUID());
fs.mkdirSync(directory, { recursive: true });
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t);
let scenario = 'pages', requests = 0;
const model = await compatibleFixture(t, () => {
const request = ++requests;
if (scenario === 'network') return { status: 502, body: { error: { message: 'Owned shadow gateway failure, original response retained' } } };
if (scenario === 'approval') return { body: request === 1 ? completion([
call('read-before-approval', 'read_file', { path: 'README.md', limit: 10 }),
call('owned-command', 'run_command', { command: 'node --version', reason: '所属只读环境检查,需原审批' }),
]) : completion([], '原审批已拒绝,说明与原工具结果保留。') };
return { body: completion([call('page-' + request, 'read_file', { path: 'README.md', offset: request === 1 ? 0 : 10, limit: 10 })]) };
});
f.session.title = '单轮观察分页原任务'; f.store.save(f.session);
const networkSession = f.store.createSession(f.project.id); networkSession.title = '单轮观察原网络失败'; f.store.save(networkSession);
f.store.saveConfig({ mode: 'compatible', model: 'owned-shadow-ui', baseUrl: model.baseUrl, maxSteps: 3 }); f.store.close();
const passed = [], screenshots = [], errors = [], snapshots = [], sourceArtifacts = new Map(); let browser, application, controller, host, page, window, result;
const mark = name => { passed.push(name); console.log('PASS ' + name); };
const panel = () => page.getByLabel('单轮观察', { exact: true });
async function visiblePanel() {
if (!await page.getByLabel('选择运行记录', { exact: true }).isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await panel().waitFor();
if (!await panel().evaluate(element => element.open)) await panel().locator('summary').click();
}
async function select(session) {
if (!await page.getByLabel('当前项目').isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await page.getByLabel('当前项目').selectOption(f.project.id);
await page.locator('.session-list button').filter({ hasText: session.title }).click();
}
async function resize(width, height) {
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); }
else await page.setViewportSize({ width, height });
}
async function shot(name) {
await panel().scrollIntoViewIfNeeded(); const file = path.join(directory, name + '.png');
await page.screenshot({ path: file, scale: 'css' }); screenshots.push(file);
}
async function state(session = f.session) { return host.api('/sessions/' + session.id); }
async function originalArtifact(artifact, session) {
let content = '', offset = 0, page;
do { page = await host.api('/artifacts/' + artifact.id + '?session=' + session.id + '&offset=' + offset + '&limit=16000'); content += page.content; offset += page.content.length; }
while (page.truncated && page.content.length);
const bytes = Buffer.from(content); assert.equal(createHash('sha256').update(bytes).digest('hex'), artifact.sha256);
assert.equal(bytes.length, artifact.bytes); return content;
}
async function saved(name, session = f.session) {
const snapshot = await host.api('/sessions/' + session.id + '/export');
for (const artifact of snapshot.execution.artifacts.filter(row => ['turn-progress-shadow', 'tool-result', 'model-http-response', 'model-stream-response', 'delivery-report', 'delivery-report-markdown'].includes(row.kind))) {
if (sourceArtifacts.has(artifact.id)) continue;
const content = await originalArtifact(artifact, session), relative = 'artifacts/' + artifact.id + '.txt';
fs.mkdirSync(path.join(directory, 'artifacts'), { recursive: true }); fs.writeFileSync(path.join(directory, relative), content);
sourceArtifacts.set(artifact.id, { id: artifact.id, kind: artifact.kind, sha256: artifact.sha256, bytes: artifact.bytes, path: relative });
}
fs.writeFileSync(path.join(directory, name + '.json'), JSON.stringify(snapshot, null, 2)); snapshots.push(name + '.json'); return snapshot;
}
try {
if (desktop) {
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve));
const port = socket.address().port; await new Promise(resolve => socket.close(resolve)); assert.notEqual(port, 4318);
controller = new HostController({ appRoot: process.cwd(), dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 });
await controller.start(); host = { url: controller.url, bootstrap: await controller.api('/bootstrap'),
api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
const executable = desktopExecutableIdentity(process.cwd()).path;
application = await _electron.launch({ executablePath: executable,
args: [...(executable.toLowerCase().endsWith('agentworkbench.exe') ? [] : [path.resolve('dist-desktop/main.cjs')]), '--app-root', process.cwd(), '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'],
cwd: process.cwd(), env: projectEnvironment(), timeout: 60000 });
page = await application.firstWindow(); window = await application.browserWindow(page);
await window.evaluate(win => { win.showInactive(); win.setContentSize(1440, 1080); }); await until(() => page.evaluate(() => innerWidth === 1440));
assert.equal(await page.evaluate(() => typeof globalThis.process), 'undefined');
} else {
host = await launchWorkbench(t, f.data); assert.notEqual(new URL(host.url).port, '4318');
browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage({ viewport: { width: 1440, height: 1080 } }); await page.goto(host.url);
}
assert.equal(host.bootstrap.config.hasKey, false); page.on('pageerror', error => errors.push(error.message));
await page.locator('.connection.connected').waitFor(); await select(f.session);
await host.api('/sessions/' + f.session.id + '/messages', { content: '只研究README.md原说明,不修改文件;本机固定分页观察夹具。' });
await until(async () => (await state()).status === 'paused', 25000);
const first = await state(), firstRun = first.execution.run;
assert.equal(requests, 3); assert.equal(firstRun.stopReason, 'step_limit'); await visiblePanel();
await until(async () => (await panel().textContent()).includes('重复读取候选'));
assert.match(await panel().textContent(), /第 1 轮 · 新增外显证据/); assert.match(await panel().textContent(), /第 3 轮 · 重复读取候选/);
assert.equal(firstRun.progressShadow.turns[1].delta.read_characters, 10); assert.equal(firstRun.progressShadow.turns[2].delta.read_characters, 10);
await shot('desktop-pages'); await saved('pages-original'); mark('actual runtime pages grow then repeat under the original three-round limit');
await panel().locator('li').nth(1).getByRole('button', { name: '查看原观察收据', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '执行结果工件', exact: true }); await dialog.waitFor();
assert.match(await dialog.textContent(), /evidence_growth/); assert.match(await dialog.textContent(), /result_artifact_id/);
await dialog.getByRole('button', { name: '关闭窗口', exact: true }).click(); mark('original observation receipt opens with the actual tool-result provenance');
await page.reload(); await page.locator('.connection.connected').waitFor(); await visiblePanel();
assert.equal(await page.getByLabel('选择运行记录').inputValue(), firstRun.id); assert.match(await panel().textContent(), /重复读取候选/);
mark('refresh restores the same Task, Run and persisted shadow observations');
await resize(390, 844); await visiblePanel();
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), true);
assert.ok((await panel().getByRole('button', { name: '查看原观察收据', exact: true }).first().boundingBox()).height >= 44);
await shot('narrow-pages'); mark('390px keeps observation facts and original receipt actions reachable without page overflow');
await resize(1440, 1080); scenario = 'approval'; requests = 0;
await host.api('/sessions/' + f.session.id + '/resume', { content: '继续核对所属环境;命令只经原审批执行。' });
await until(async () => (await state()).status === 'awaiting_approval', 25000); await visiblePanel();
await until(async () => (await panel().textContent()).includes('等待所属操作')); await shot('waiting-approval');
const waiting = await state(); assert.equal(waiting.execution.run.progressShadow.turns.at(-1).classification, 'waiting');
await saved('approval-waiting'); mark('an actual pending approval stays waiting and does not consume the earlier same-turn read twice');
await page.getByRole('button', { name: '拒绝执行', exact: true }).click();
await until(async () => (await state()).status === 'completed', 25000); const second = await state();
assert.equal(requests, 2); assert.equal(second.taskId, first.taskId); assert.notEqual(second.execution.run.id, firstRun.id);
assert.equal(second.execution.run.progressShadow.turns.find(row => row.phase === 'settled').delta.repeated_reads, 0);
await until(async () => (await panel().textContent()).includes('新失败 1')); await shot('denied-approval');
assert.match(await panel().textContent(), /失败类别:权限或审批拒绝/);
await saved('approval-denied'); mark('refusing the original approval preserves the permission failure and the original tool pairs');
await page.getByLabel('选择运行记录').selectOption(firstRun.id);
await until(async () => (await panel().textContent()).includes('第 3 轮 · 重复读取候选'));
await shot('historical-run'); await page.getByLabel('选择运行记录').selectOption(second.execution.run.id);
await until(async () => !(await panel().textContent()).includes('第 3 轮')); mark('selecting historical and current Runs keeps their independent observations');
await host.api('/sessions/' + f.session.id + '/delivery-reports', {});
const reportExport = await saved('report-original');
const reportArtifact = reportExport.execution.artifacts.filter(row => row.kind === 'delivery-report').at(-1);
const report = JSON.parse(await originalArtifact(reportArtifact, f.session));
assert.equal(report.turnObservations.length, 2); assert.ok(report.turnObservations.every(row => row.evidence_verified));
fs.writeFileSync(path.join(directory, 'report.json'), JSON.stringify(report, null, 2)); mark('delivery report uses both Runs and independently verifies the original observation receipts');
scenario = 'network'; requests = 0; await select(networkSession);
await host.api('/sessions/' + networkSession.id + '/messages', { content: '读取原工程,保存失败来源;本机502夹具。' });
await until(async () => (await state(networkSession)).status === 'failed', 25000); await visiblePanel();
await until(async () => (await panel().textContent()).includes('新增失败证据'));
assert.match(await panel().textContent(), /失败类别:上游服务/);
const failure = await state(networkSession); assert.equal(failure.lastFailure.httpStatus, 502); assert.equal(failure.execution.run.stopReason, null);
await shot('network-original-failure'); await saved('network-original', networkSession);
mark('original HTTP 502 remains a model failure and is not relabeled as no progress'); assert.deepEqual(errors, []);
result = { success: true, passed, errors, screenshots, snapshots, actualElectron: desktop, installationValidated: false, realModelRequests: 0, officialServiceTouched: false };
} catch (error) {
if (page) { try { await page.screenshot({ path: path.join(directory, 'failure.png') }); fs.writeFileSync(path.join(directory, 'failure-dom.txt'), await page.locator('body').innerText()); } catch {} }
result = { success: false, passed, errors, screenshots, snapshots, error: error.stack, actualElectron: desktop, realModelRequests: 0, officialServiceTouched: false };
} finally {
if (application) await application.close(); if (browser) await browser.close();
if (controller && await controller.health()) await controller.stop();
for (const dispose of disposers.reverse()) await dispose();
fs.writeFileSync(path.join(directory, 'source-artifacts.json'), JSON.stringify([...sourceArtifacts.values()], null, 2));
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
@@ -0,0 +1,98 @@
.task-record { flex: 1; min-height: 0; overflow: auto; padding: 4px 18px 20px; }
.task-record-section { padding: 18px 0; border-bottom: 1px solid var(--line); }
.record-heading { display: flex; gap: 7px; align-items: center; margin-bottom: 12px; color: var(--teal); }
.record-heading h3 { font-size: 12px; font-weight: 600; flex: 1; }
.record-heading > span:not(.status) { margin-left: auto; font-size: 11px; color: var(--muted); }
.record-heading > code { margin-left: auto; font-size: 11px; color: var(--muted); }
.task-goal { line-height: 1.85; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
.record-id { display: inline-block; font-size: 10px; color: var(--muted); margin-top: 9px; }
.task-instructions { margin-top: 14px; font-size: 11px; }
.task-instructions summary { cursor: pointer; color: var(--teal); }
.task-instructions p { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.8; padding: 8px 0; }
.record-empty, .record-footnote { display: flex; gap: 7px; align-items: flex-start; color: var(--muted); font-size: 11px; line-height: 1.85; margin: 9px 0; }
.verification-note { display: flex; gap: 10px; padding: 14px 12px; margin-top: 15px; background: #faf4e8; border: 1px solid #e7d8b8; border-radius: 7px; color: #805d22; }
.verification-note strong { font-size: 12px; }
.verification-note p { font-size: 11px; line-height: 1.8; margin-top: 6px; }
.verification-note code { display: block; font-size: 10px; margin-top: 5px; }
.run-picker { display: flex; flex-direction: column; gap: 7px; color: var(--muted); font-size: 11px; }
.run-picker select { border: 1px solid var(--line); background: #fff; border-radius: 5px; padding: 8px; width: 100%; min-width: 0; font-size: 11px; }
.run-status { display: flex; justify-content: space-between; align-items: center; margin: 13px 0; }
.run-status > code { font-size: 10px; color: var(--muted); }
.record-fields { display: grid; grid-template-columns: 90px minmax(0, 1fr); gap: 9px 10px; font-size: 11px; line-height: 1.7; margin: 0; }
.record-fields dt { color: var(--muted); }
.record-fields dd { margin: 0; overflow-wrap: anywhere; }
.record-fields small { color: var(--muted); font-size: 10px; }
.record-endpoint { font-family: "Cascadia Code", Consolas, monospace; font-size: 10px; }
.run-stop { padding: 9px; margin-top: 11px; font-size: 11px; line-height: 1.7; border-left: 2px solid #bd9654; background: #faf7ef; }
.check-plan { margin-top: 14px; border-left: 2px solid #7da89c; padding-left: 12px; font-size: 11px; line-height: 1.8; }
.check-selection { border: 1px solid var(--line); border-radius: 6px; margin: 12px 0; padding: 8px 10px; min-width: 0; }
.check-selection legend { color: var(--muted); padding: 0 4px; }
.check-selection label { display: flex; align-items: center; gap: 7px; padding: 4px 0; cursor: pointer; overflow-wrap: anywhere; }
.check-selection input { accent-color: #35776b; width: 14px; height: 14px; flex: 0 0 auto; }
.check-selection p { margin: 7px 0; color: var(--muted); }
.check-baseline { display: flex; gap: 5px; align-items: flex-start; color: var(--muted); margin-top: 7px; overflow-wrap: anywhere; }
.check-baseline svg { margin-top: 4px; }
.check-plan ul { padding: 0; margin: 12px 0; list-style: none; }
.check-plan li { display: flex; flex-direction: column; gap: 4px; margin: 10px 0; }
.check-plan li code { color: var(--teal); background: #edf3f1; padding: 5px 8px; border-radius: 4px; font-size: 11px; overflow-wrap: anywhere; }
.check-job { padding: 13px 0 0; margin-top: 15px; border-top: 1px solid var(--line); font-size: 11px; line-height: 1.7; }
.check-job .record-heading { margin-bottom: 6px; flex-wrap: wrap; }
.check-job > time { color: var(--muted); font-size: 10px; }
.check-job > p { margin: 7px 0; }
.check-current { display: flex; align-items: center; gap: 6px; color: var(--teal); }
.check-result { border: 1px solid var(--line); border-radius: 6px; padding: 9px; margin-top: 10px; }
.check-result > div { display: flex; gap: 5px; align-items: center; justify-content: space-between; }
.check-result > p { margin-top: 6px; color: var(--muted); }
.check-result .text-button { margin-top: 6px; padding-left: 0; }
.artifact-list { display: flex; flex-direction: column; gap: 5px; }
.artifact-list button { width: 100%; display: flex; justify-content: space-between; align-items: center; text-align: left; border: 1px solid var(--line); border-radius: 5px; padding: 9px; font-size: 11px; }
.artifact-list button:hover { background: #edf3f1; }
.artifact-list code { display: block; color: var(--muted); font-size: 10px; margin-top: 4px; }
.artifact-list small { color: var(--muted); font-size: 10px; }
.artifact-preview { min-height: 100px; min-width: 0; max-width: 100%; overflow: auto; flex: 1; padding: 15px; background: #edf3f1; border: 1px solid var(--line); border-radius: 5px; font-size: 11px; line-height: 1.8; }
.modal-heading > div { min-width: 0; }
.modal-heading p { overflow-wrap: anywhere; }
.artifact-pagination { display: flex; align-items: center; justify-content: flex-end; gap: 8px; padding-top: 13px; font-size: 11px; flex-wrap: wrap; }
.artifact-pagination > span { margin-right: auto; color: var(--muted); }
.check-confirm { flex: 1; min-height: 0; overflow: auto; font-size: 12px; }
.check-confirm > div { margin-bottom: 14px; }
.check-confirm pre { margin: 6px 0 0; padding: 10px; background: #edf3f1; border: 1px solid var(--line); border-radius: 5px; font-size: 11px; }
.check-confirm p { color: var(--muted); line-height: 1.8; }
.check-python-runtime { margin: 9px 0; padding: 9px 11px; border-left: 2px solid #84a597; background: #f6f9f7; font-size: 11px; line-height: 1.6; }
.check-python-runtime strong, .check-python-runtime code { display: block; }
.check-python-runtime code { margin-top: 3px; font-size: 10px; color: var(--muted); overflow-wrap: anywhere; }
.status-unknown, .status-unverified, .status-stale { color: #805d22; background: #faf4e8; }
.status-passed { color: #277958; background: #edf7ef; }
.status-queued, .status-validating, .status-not_configured, .status-cancelled { color: #626c7c; background: #eef0f4; }
.tool-unknown .tool-symbol { color: #805d22; background: #faf4e8; }
.context-meter { height: 5px; margin: 15px 0; border-radius: 9px; overflow: hidden; background: #e8eeeb; }
.context-meter i { display: block; height: 100%; background: #56877b; border-radius: inherit; }
.context-sha { display: block; font-size: 10px; color: var(--muted); margin-top: 4px; overflow-wrap: anywhere; }
.context-actions { display: flex; flex-wrap: wrap; gap: 4px 12px; }
.context-actions .text-button { padding-left: 0; }
.context-history-list { flex: 1; min-height: 0; overflow: auto; padding: 1px; }
.context-history-group { padding: 13px; margin-bottom: 10px; border: 1px solid var(--line); border-radius: 6px; font-size: 11px; line-height: 1.8; }
.context-history-group > div:first-child { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 14px; }
.context-history-group strong { font-weight: 600; overflow-wrap: anywhere; }
.context-history-group small { color: var(--muted); font-size: 10px; }
.context-history-group > .text-button { padding-left: 0; margin-top: 6px; }
.context-history-tool { display: flex; flex-wrap: wrap; align-items: center; gap: 3px 10px; padding: 6px 0; }
.context-history-tool code { font-size: 10px; color: var(--muted); overflow-wrap: anywhere; }
.context-history-tool small { flex-basis: 100%; overflow-wrap: anywhere; }
.context-unknown { padding: 1px 6px; border-radius: 4px; color: #805d22; background: #faf4e8; font-size: 10px; }
@media (max-width: 1120px) { .inspector-tabs > button:not(.icon-button) { padding-left: 7px; padding-right: 7px; gap: 4px; } .task-record { padding-left: 13px; padding-right: 13px; } }
@media (max-width: 620px) { .toolbar-actions { gap: 1px; } .toolbar-actions .icon-button { width: 24px; } .task-record { padding: 4px 16px 20px; } .record-fields { grid-template-columns: 83px minmax(0, 1fr); } .artifact-pagination .button { height: 32px; } }
.checkpoint-card { margin-top: 12px; padding: 12px; background: var(--panel, #fff); border: 1px solid var(--border, #cbd5df); border-radius: 6px; min-width: 0; }
.checkpoint-card strong { display: block; font-size: 12px; }
.checkpoint-card p, .checkpoint-card code { display: block; margin-top: 6px; font-size: 11px; color: var(--muted); line-height: 1.7; overflow-wrap: anywhere; }
.checkpoint-assessment { margin-top: 12px; padding: 12px; border: 1px solid #b9c9da; background: #f3f7fb; border-radius: 6px; font-size: 12px; line-height: 1.8; }
.checkpoint-assessment ul { margin: 8px 0; padding-left: 18px; overflow-wrap: anywhere; }
.checkpoint-assessment .button, .task-checkpoints > .button { margin-top: 8px; height: auto; min-height: 36px; white-space: normal; }
@media (max-width: 620px) { .task-checkpoints .button, .task-checkpoints .text-button { min-height: 44px; } }
.turn-progress { margin-top: 14px; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.turn-progress summary { cursor: pointer; color: #154b4a; font-weight: 600; }
.turn-progress ol { list-style: none; padding: 0; margin: 10px 0; }
.turn-progress li { border-top: 1px solid #dce7e2; padding: 10px 0; }
.turn-progress li strong { font-size: 12px; }
.turn-progress li p { margin: 4px 0; }
@media (max-width: 620px) { .turn-progress .text-button { min-height: 44px; } }
@@ -0,0 +1,181 @@
import { ModelIdentityDetails } from './ModelIdentityDetails';
import { useEffect, useRef, useState } from 'react';
import { Check, ClipboardCheck, FileText, GitBranch, LoaderCircle, Play, RefreshCw, ShieldQuestion } from 'lucide-react';
import type { ArtifactPreview, CheckPlan, Project, PythonRuntimeIdentity, Run, Session } from './types';
import { api } from './api';
import { Modal, Status } from './components';
import { DeliveryPanel } from './DeliveryPanel';
import { RequestContextPanel } from './RequestContextPanel';
import { WorkspacePanel } from './WorkspacePanel';
import { BrowserPanel } from './BrowserPanel';
import { TaskPlanPanel } from './TaskPlanPanel';
import { RequirementPanel } from './RequirementPanel';
import { TurnProgress } from './TurnProgress';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
import { EnvironmentPanel } from './EnvironmentPanel';
import { PreviewPanel } from './PreviewPanel';
import { FileResultsPanel } from './FileResultsPanel';
const stopReasons: Record<string, string> = { model_identity: '模型返回型号需要核对', no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
stopReasons.git_review = 'Git预览已保存,等待审查与确认';
stopReasons.change_set_review = '完整文件批次已封存,等待审查与应用';
stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保留';
stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续';
stopReasons.diagnostic_answered = '诊断答复已完成;原任务的目标与交付状态保持';
stopReasons.verification_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' }) : '执行中';
stopReasons.requirements_incomplete = '用户要求仍有待复核、失效或未审阅来源';
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> }) {
const execution = session.execution, task = execution?.task;
const [runId, setRunId] = useState('');
const [historicalRun, setHistoricalRun] = useState<Run | null>(null);
const [preview, setPreview] = useState<ArtifactPreview | null>(null);
const [previewBusy, setPreviewBusy] = useState(false);
const [planning, setPlanning] = useState(false);
const [confirmPlan, setConfirmPlan] = useState<CheckPlan | null>(null);
const [selectedChecks, setSelectedChecks] = useState<string[]>([]);
const [starting, setStarting] = useState(false);
const artifactRequest = useRef(0);
const actionScope = useRef(0);
const id = runId || execution?.run?.id || '';
const run = id === execution?.run?.id ? execution.run : historicalRun;
const plans = execution?.plans ?? [];
const latestPlan = plans.filter(plan => plan.taskId === task?.id).at(-1);
const checkChoices = latestPlan ? [...(latestPlan.project.packageManager === 'npm' ? latestPlan.project.scripts ?? [] : []), ...(latestPlan.project.python?.checks ?? [])] : [];
const checksChanged = !!latestPlan && JSON.stringify(selectedChecks.slice().sort()) !== JSON.stringify(latestPlan.checks.map(check => check.name).sort());
const jobs = execution?.checks ?? [];
const checkRunning = jobs.some(job => ['queued', 'running'].includes(job.status));
useEffect(() => { setSelectedChecks(latestPlan?.checks.map(check => check.name) ?? []); }, [latestPlan?.id]);
useEffect(() => { setRunId(''); setHistoricalRun(null); setPreview(null); setPreviewBusy(false); setConfirmPlan(null); setPlanning(false); setStarting(false); artifactRequest.current++; actionScope.current++;
return () => { artifactRequest.current++; actionScope.current++; };
}, [session.id, task?.id]);
useEffect(() => {
if (!id || id === execution?.run?.id) return;
let alive = true; setHistoricalRun(null);
api<Run>('/sessions/' + session.id + '/runs/' + id).then(value => { if (alive) setHistoricalRun(value); }).catch(error => { if (alive) onError(error); });
return () => { alive = false; };
}, [session.id, id, execution?.run?.id]);
async function openArtifact(artifactId: string, offset = 0) {
const request = ++artifactRequest.current; setPreviewBusy(true);
try {
const value = await api<ArtifactPreview>('/artifacts/' + artifactId + '?session=' + session.id + '&offset=' + offset + '&limit=16000');
if (artifactRequest.current === request) setPreview(value);
} catch (error) { if (artifactRequest.current === request) onError(error); }
finally { if (artifactRequest.current === request) setPreviewBusy(false); }
}
async function planChecks(names?: string[]) {
const scope = actionScope.current;
setPlanning(true);
try { const value = await api<Session>('/sessions/' + session.id + '/check-plans', names ? { names } : {}); if (actionScope.current === scope) onSession(value); }
catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setPlanning(false); }
}
async function runChecks() {
if (!confirmPlan) return; setStarting(true);
const scope = actionScope.current;
try { const value = await api<Session>('/sessions/' + session.id + '/check-jobs', { planId: confirmPlan.id }); if (actionScope.current === scope) { onSession(value); setConfirmPlan(null); } }
catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setStarting(false); }
}
async function stopCheck(jobId: string) {
const scope = actionScope.current;
try { const value = await api<Session>('/sessions/' + session.id + '/check-jobs/' + jobId + '/stop', {}); if (actionScope.current === scope) onSession(value); }
catch (error) { if (actionScope.current === scope) onError(error); }
}
return <div className="task-record" aria-label="任务记录">
<WorkspacePanel project={project} session={session} busy={busy} onRefresh={onWorkspaceRefresh} onNavigate={onWorkspaceNavigate} onError={onError} />
<section className="task-record-section">
<div className="record-heading"><ClipboardCheck size={15} /><h3>任务目标</h3>{task && <Status value={task.status} />}</div>
{task ? <><p className="task-goal">{task.contract?.goal || task.goal}</p><code className="record-id" title={task.id}>{task.id.slice(0, 8)} · 任务</code>
{task.contract?.checks === 'skip' && <p className="record-footnote">检查约定:按用户要求不自动测试。</p>}
{task.contract?.inheritedFromTaskId && <p className="record-footnote">原目标续接自 {task.contract.inheritedFromTaskId.slice(0, 8)},历史记录保留。</p>}
{task.delivery?.status === 'files_applied' && <div role="status"><strong>文件已应用</strong>{task.delivery.paths.map(path => <p key={path}><code>{path}</code></p>)}{task.delivery.checks === 'not_requested' && <p className="record-footnote">已按原要求交付文件,未运行测试。</p>}</div>}
{!!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 && <RequirementPanel 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}
{task && !!execution?.mcpJobs?.length && <McpJobHistory session={session} jobs={execution.mcpJobs} busy={busy} onSession={onSession} onError={onError} />}
{task && <section className="task-record-section">
<div className="record-heading"><h3>运行记录</h3><span>{execution?.runs.filter(item => item.taskId === task.id).length} 次</span></div>
<label className="run-picker">选择一次运行<select aria-label="选择运行记录" value={id} onChange={event => setRunId(event.target.value)}>{execution?.runs.filter(item => item.taskId === task.id).map((item, index) => <option key={item.id} value={item.id}>第 {index + 1} 次 · {time(item.startedAt)}{item.resumeOf ? ' · 接续' : ''}</option>)}</select></label>
{run ? <><div className="run-status"><Status value={run.status} /><code title={run.id}>{run.id.slice(0, 8)}</code></div>
{run.status === 'needs_review' && task.delivery?.status === 'files_applied' && <p className="record-footnote">这次运行在文件审查前结束;文件此后已应用,当前交付状态见上方任务目标。</p>}
{run.purpose === 'diagnostic' && <p className="record-footnote">本次为只读诊断,运行结束仅表示答复完成;原任务状态另行保留。</p>}
<dl className="record-fields"><ActualModelFields run={run} session={session} />{run.workspaceIdentity && <><dt>执行目录</dt><dd className="record-endpoint">{run.workspaceIdentity.root}</dd>{run.workspaceIdentity.branch && <><dt>独立分支</dt><dd className="record-endpoint">{run.workspaceIdentity.branch}</dd></>}</>}<dt>开始 / 结束</dt><dd>{time(run.startedAt)}<br />{time(run.finishedAt)}</dd><dt>模型轮次 / 工具</dt><dd>{run.steps} / {run.toolCalls}</dd><dt>已报告用量</dt><dd>{number(run.usage?.totalTokens)} tokens<br /><small>输入 {number(run.usage?.inputTokens)} · 输出 {number(run.usage?.outputTokens)}</small></dd>
{!!run.usage?.unknownRequests && <><dt>未报告用量</dt><dd>{run.usage.unknownRequests} 次请求 · 估算 {number(run.usage.estimatedUnknownTokens)} tokens</dd></>}
<dt>本次预算</dt><dd>{number(run.budget?.maxTokens)} tokens · {Math.round((run.budget?.maxDurationMs ?? 0) / 60000)} 分钟 · {run.budget?.maxSteps} 轮</dd><dt>任务累计</dt><dd>{number(execution?.accountedTaskTokens)} / {number(task.budget.maxTokens)} tokens</dd>
</dl>{run.stopReason && <p className="run-stop">{stopReasons[run.stopReason] || run.stopReason}</p>}
<p className="record-footnote">用量按请求尝试累计,包含失败响应已报告的 tokens;未报告的请求单独估算。历史缺失不补造,tokens 不等于费用。</p>
<TurnProgress run={run} openArtifact={openArtifact} />
</> : <p className="record-empty"><LoaderCircle size={14} className="spin" />正在读取运行记录</p>}
</section>}
{run && <RequestContextPanel session={session} runId={run.id} onError={onError} openArtifact={openArtifact} />}
{task && <EnvironmentPanel project={project} session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <PreviewPanel onOpen={onOpenPreview} project={project} session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
<section className="task-record-section project-checks">
<div className="record-heading"><GitBranch size={15} /><h3>工程检查</h3><Status value={task?.verification.status || 'not_configured'} /></div>
{task?.verification.status === 'failed' && <p className="record-footnote" role="status">原工程检查有失败记录;文件应用或答复完成不代表检查通过。</p>}
{task?.contract?.checks === 'skip' && <p className="record-footnote">原任务无需测试。下方操作只在你明确选择并确认后执行。</p>}
<p className="record-footnote">检查对应当时的工程快照。先识别测试与执行环境,再确认检查;项目变化后重新检查。</p>
<button type="button" className="button secondary" disabled={!task || busy || planning || checkRunning} onClick={() => planChecks()}>{planning ? <LoaderCircle size={14} className="spin" /> : <RefreshCw size={14} />}{latestPlan ? '重新识别检查计划' : '识别工程与检查'}</button>
{latestPlan && <div className="check-plan"><p><strong>{latestPlan.project.name}</strong> · {latestPlan.project.languages.join(' / ') || '待识别'}</p><p className="check-baseline"><GitBranch size={12} />{latestPlan.project.git.available ? `${latestPlan.project.git.branch || 'detached'} · ${latestPlan.project.git.head?.slice(0, 8) || '尚无提交'}${latestPlan.project.git.dirty ? ' · 有未提交改动' : ' · 工作区干净'}` : '项目尚未启用 Git'}</p>
{latestPlan.environment&&<p className="record-footnote">环境:Node {latestPlan.environment.runtime.node.version} · npm {latestPlan.environment.runtime.npm?.version??'未找到'} · {latestPlan.environment.status==='ready'?'依赖已就绪':'依赖需要核对,请先查看上方工程环境'}{latestPlan.environment.preparation&&' · 引用依赖准备 '+latestPlan.environment.preparation.jobId.slice(0,8)}</p>}
{latestPlan.project.python?.status === 'invalid' && <p className="record-empty">{latestPlan.project.python.message}</p>}
{checkChoices.length > 0 && <fieldset className="check-selection" disabled={busy || planning || starting || checkRunning}>
<legend>选择检查范围</legend>
{checkChoices.map(check => <label key={check.name}><input type="checkbox" aria-label={'启用检查 ' + check.name} checked={selectedChecks.includes(check.name)} onChange={event => setSelectedChecks(current => event.target.checked ? [...current, check.name] : current.filter(name => name !== check.name))} /><span>{check.name}</span></label>)}
{checksChanged && <><p>按所选范围重新识别,确认后执行新计划。</p><button type="button" className="button secondary" disabled={!selectedChecks.length || selectedChecks.length > 6} onClick={() => planChecks(selectedChecks)}>重新识别所选检查</button></>}
</fieldset>}
{latestPlan.checks.length ? <><ul>{latestPlan.checks.map(check => <li key={check.id}><span>{check.name}</span><code>{check.command}</code></li>)}</ul>
{latestPlan.checks.find(check => check.python)?.python && <PythonRuntimeInfo runtime={latestPlan.checks.find(check => check.python)!.python!.runtime} />}
<button type="button" className="button primary" disabled={busy || starting || checkRunning || checksChanged} onClick={() => setConfirmPlan(latestPlan)}><Play size={14} />执行这些检查</button></> : <p className="record-empty">没有识别到可执行的检查。请配置项目测试或构建。</p>}
</div>}
{jobs.slice().reverse().map(job => <div key={job.id} className="check-job">
<div className="record-heading"><Status value={job.stale ? 'stale' : job.status} /><code title={job.id}>{job.id.slice(0, 8)}</code>{['queued', 'running'].includes(job.status) && <button type="button" className="text-button" onClick={() => stopCheck(job.id)}>停止检查</button>}</div>
<time>{time(job.startedAt)}</time>{job.currentCheck && <p className="check-current"><LoaderCircle size={12} className="spin" />正在执行 <code>{job.currentCheck.command}</code></p>}{job.summary && <p>{job.summary}</p>}
{job.results.map(result => <div key={result.id} className="check-result"><div><strong>{result.name}</strong><Status value={result.status} /></div>
<p>退出码 {result.exitCode === null ? '未返回' : result.exitCode} · {(result.durationMs / 1000).toFixed(1)} 秒{result.tests && ` · 测试 ${result.tests.passed}/${result.tests.total} 通过`}{!!result.tests?.failed && ` · 失败 ${result.tests.failed}`}{!!result.tests?.skipped && ` · 跳过 ${result.tests.skipped}`}{!!result.collectionErrors && ` · 收集错误 ${result.collectionErrors}`}</p>
{result.python && <PythonRuntimeInfo runtime={result.python.runtime} />}
{result.compilation && <p>语法编译 {result.compilation.compiled}/{result.compilation.total} 个源码文件</p>}
{result.reason && <p>{result.reason}</p>}
{result.logArtifactId && <button type="button" className="text-button" disabled={previewBusy} onClick={() => openArtifact(result.logArtifactId!)}><FileText size={13} />查看检查日志</button>}
{result.metricsArtifactId && <button type="button" className="text-button" disabled={previewBusy} onClick={() => openArtifact(result.metricsArtifactId!)}><ClipboardCheck size={13} />查看实际测试依据</button>}
</div>)}
</div>)}
</section>
{task && <BrowserPanel session={session} busy={busy} onSession={onSession} onError={onError} />}
{task && <DeliveryPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{!!execution?.artifacts.length && <section className="task-record-section"><div className="record-heading"><FileText size={15} /><h3>结果工件</h3><span>最近 {execution.artifacts.length} 项</span></div><div className="artifact-list">{execution.artifacts.filter(artifact => !artifact.mediaType?.startsWith('image/')).slice().reverse().map(artifact => <button type="button" key={artifact.id} disabled={previewBusy} onClick={() => openArtifact(artifact.id)}><span>{artifact.kind === 'browser-result' ? '原页面执行记录' : artifact.kind === 'browser-plan' ? '页面检查计划' : artifact.kind === 'browser-binding' ? '页面结果来源' : artifact.kind === 'check-log' ? '检查日志' : artifact.kind === 'check-metrics' ? '实际检查统计' : artifact.kind === 'check-input' ? '检查源码与目标' : artifact.kind === 'check-plan' ? '检查计划' : artifact.kind === 'project-inspection' ? '工程识别' : artifact.kind === 'delivery-report' ? '交付报告 · JSON' : artifact.kind === 'delivery-report-markdown' ? '交付报告 · Markdown' : artifact.kind === 'delivery-diff' ? '提交差异' : artifact.kind === 'model-request' ? '模型请求正文' : artifact.kind === 'context-plan' ? '请求计划' : artifact.kind === 'context-history-index' ? '完整历史索引' : artifact.kind === 'context-latest-tools' ? '最新工具反馈' : artifact.kind.startsWith('context-group') ? '完整历史记录' : '工具结果'}<code>{artifact.sha256.slice(0, 10)}</code></span><small>{number(artifact.bytes)} B</small></button>)}</div></section>}
{confirmPlan && <Modal title="执行工程检查" description="以下检查在当前项目执行,保存实际执行环境、退出码和结果。" onClose={() => setConfirmPlan(null)}><div className="check-confirm">{confirmPlan.checks.map(check => <div key={check.id}><strong>{check.command}</strong><pre>{check.script}{check.lifecycle?.length ? '\n\n' + check.lifecycle.map(item => item.name + ': ' + item.script).join('\n') : ''}</pre>{check.python && <PythonRuntimeInfo runtime={check.python.runtime} />}</div>)}<p>{confirmPlan.project.name}</p></div><div className="modal-actions"><button type="button" className="button secondary" disabled={starting} onClick={() => setConfirmPlan(null)}>取消</button><button type="button" className="button primary" disabled={starting} onClick={runChecks}><Check size={14} />确认执行检查</button></div></Modal>}
{preview && <Modal title="执行结果工件" description={`SHA256 ${preview.sha256}`} wide onClose={() => { artifactRequest.current++; setPreview(null); setPreviewBusy(false); }}><pre className="artifact-preview">{preview.content}</pre><div className="artifact-pagination"><span>字符 {number(preview.offset)}–{number(preview.offset + preview.content.length)} / {number(preview.totalCharacters)}</span><button type="button" className="button secondary" disabled={previewBusy || preview.offset === 0} onClick={() => openArtifact(preview.id, Math.max(0, preview.offset - 16000))}>上一段</button><button type="button" className="button secondary" disabled={previewBusy || !preview.truncated} onClick={() => openArtifact(preview.id, preview.offset + preview.content.length)}>下一段</button></div></Modal>}
</div>;
}
function ActualModelFields({ run, session }: { run: Run; session: Session }) {
const receipts = run.consumption ?? [];
const events = session.events.filter(event => event.runId === run.id && event.actualModel && event.connectionId);
const observed = receipts.length ? receipts.map(receipt => ({ id: receipt.connectionId, name: receipt.connectionName, model: receipt.model, endpoint: receipt.endpoint, identity: receipt.modelIdentity }))
: events.map(event => { const member = run.model.routing?.members?.find(member => member.id === event.connectionId); return { id: event.connectionId, name: member?.name, model: event.actualModel!, endpoint: member?.baseUrl, identity: undefined }; });
const routes = observed.filter((value, index) => observed.findIndex(candidate => candidate.id === value.id && candidate.model === value.model && candidate.endpoint === value.endpoint && JSON.stringify(candidate.identity) === JSON.stringify(value.identity)) === index);
return <><dt>启动选择</dt><dd>{run.model?.verified === false ? '历史配置未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model.routing?.name || run.model.model || '未记录'}</dd>
<dt>实际调用</dt><dd>{routes.length ? routes.map((route, index) => <div key={index}><span>{route.name ? route.name + ' · ' : ''}{route.model}</span><ModelIdentityDetails identity={route.identity} requestedModel={route.model} />{route.endpoint && <small className="record-endpoint"><br />{route.endpoint}</small>}</div>) : run.model.mode === 'demo' ? '未调用模型服务' : '尚无可核对的实际连接记录'}</dd>
{!receipts.length && run.model.mode !== 'demo' && <><dt>启动接口</dt><dd className="record-endpoint">{run.model.baseUrl || '未记录'}<br /><small>启动配置不代表实际池成员</small></dd></>}
{!!receipts.length && <><dt>用量凭据</dt><dd>{receipts.length} 次请求尝试 · {receipts.filter(receipt => receipt.usageStatus === 'reported').length} 次已报告</dd></>}
</>;
}
function PythonRuntimeInfo({ runtime }: { runtime: PythonRuntimeIdentity }) {
return <div className="check-python-runtime"><strong>Python {runtime.version || (runtime.status === 'deferred' ? '执行时核对版本' : '尚未找到')}</strong>
<code>{runtime.logicalExecutable || runtime.executable || '请安装Python或配置项目虚拟环境'}</code>{runtime.message && <p>{runtime.message}</p>}</div>;
}
@@ -0,0 +1,25 @@
import type { Run } from './types';
const labels: Record<string, string> = { baseline: '本次运行基线', waiting: '等待所属操作', evidence_growth: '新增外显证据', new_failure_evidence: '新增失败证据',
user_boundary: '用户边界变化', repeated_failure_candidate: '重复失败候选', repeated_read_candidate: '重复读取候选', no_observed_change: '未见新外显事实', unknown_bounded: '观察容量已满,保留未知' };
const failureLabels: Record<string, string> = { invalid_input: '参数无效', permission: '权限或审批拒绝', requires_verification: '结果待核对', network: '网络连接', service: '上游服务',
authentication: '身份验证', rate_limit: '请求限流', quota: '服务额度', tool_or_environment: '工具或环境', unknown: '尚未分类' };
export function TurnProgress({ run, openArtifact }: { run: Run; openArtifact: (id: string) => void }) {
if (!run.progressShadow && !run.progressShadowError) return null;
const shadow = run.progressShadow;
return <details className="turn-progress" aria-label="单轮观察">
<summary>单轮观察 · 仅记录{shadow ? ` · 已保留 ${shadow.turns.filter(row => row.phase === 'settled').length} 轮` : ''}</summary>
<p className="record-footnote">依据实际工具、文件范围、失败和证据变化分类;观察不改变停止、权限或预算。</p>
{run.progressShadowError && <p className="plan-problem">部分观察未能记录,原工具结果保留。</p>}
{shadow?.truncated && <p className="record-footnote">观察已达保留上限;较早收据仍在原工件中,未保留范围不推定为重复。</p>}
<ol>{shadow?.turns.map((turn, index) => <li key={`${turn.stepId}/${turn.phase}/${index}`}>
<strong>{turn.stepIndex === null ? '基线' : `第 ${turn.stepIndex} 轮`} · {labels[turn.classification] ?? turn.classification}</strong>
<p>新增读取 {turn.delta.read_characters} 字符 · 重复读取 {turn.delta.repeated_reads} 次{turn.delta.changed_files ? ` · 改动文件 ${turn.delta.changed_files}` : ''}{turn.delta.check_results ? ` · 检查结果 ${turn.delta.check_results}` : ''}{turn.delta.requirement_evidence ? ` · 要求证据 ${turn.delta.requirement_evidence}` : ''}</p>
{!!(turn.delta.new_failures || turn.delta.repeated_failures) && <p>新失败 {turn.delta.new_failures} · 重复失败 {turn.delta.repeated_failures}</p>}
{turn.reasons.some(reason => /^(new|repeated)_failure:/.test(reason)) && <p>失败类别:{[...new Set(turn.reasons.filter(reason => /^(new|repeated)_failure:/.test(reason)).map(reason => {
const kind = reason.split(':')[1]; return failureLabels[kind] ?? kind;
}))].join('、')}</p>}
{!!turn.waiting.length && <p>等待 {turn.waiting.map(row => ({ approval: '审批', check_job: '检查作业', review: '审查' }[row.kind] ?? row.kind)).join('、')}</p>}
{run.progressShadowArtifactIds?.[index] && <button className="text-button" onClick={() => openArtifact(run.progressShadowArtifactIds![index])}>查看原观察收据</button>}
</li>)}</ol>
</details>;
}
@@ -0,0 +1,369 @@
export interface Config {
mode: 'demo' | 'compatible'; baseUrl: string; model: string;
contextLimit: number; maxSteps: number; maxOutputTokens: number; hasKey: boolean;
maxRunDurationMs: number; maxRunTokens: number; maxTaskTokens: number;
modelResponseTimeoutMs?: number; modelStreamIdleTimeoutMs?: number;
}
export interface EnvironmentFile { path:string;sha256:string;bytes:number }
export interface DependencyTree { status:string;files:number;bytes:number;sha256:string|null;message?:string }
export interface NodeEnvironmentRuntime {status:string;node:EnvironmentFile&{version:string};npm:(EnvironmentFile&{version:string;manifest:EnvironmentFile})|null}
export interface NodeEnvironmentBinding {kind:'node';identity:string;dependencyInputs:string;status:string;installed:DependencyTree;declarations:EnvironmentFile[];runtime:NodeEnvironmentRuntime}
export interface EnvironmentDiagnostic {id:string;taskId:string;runId:string;artifactId:string;artifactSha256:string;inspectedAt:string;status:string;
node:(NodeEnvironmentBinding&{manager:string;lockVersion:number|null;packageCount:number;missing:string[];mismatched:string[];sources:string[];issues:string[];preparable:boolean})|null;
python:{status:string;framework?:string;runtime:{version:string|null;logicalExecutable:string|null};pytest:{version:string|null};message:string}|null}
export interface EnvironmentPlan {id:string;taskId:string;runId:string;status:string;root:string;registry:string;scripts:'skip'|'allow';offline:boolean;packageCount:number;timeoutMs:number;fingerprint:string;
invocation:{executable:string;args:string[]};lifecycle:{name:string;script:string}[];installScriptPackages:string[]}
export interface EnvironmentJob {id:string;taskId:string;runId:string;planFingerprint:string;status:string;summary?:string;finishedAt?:string;requiresVerification:boolean;
logExcerpt?:string;logArtifactId?:string;after?:NodeEnvironmentBinding;result?:{exitCode:number|null;durationMs:number;truncated?:boolean};reconciliation?:{artifactId:string;sha256:string}}
export interface PreviewPlan {id:string;taskId:string;runId:string;root:string;url:string;port:number;fingerprint:string;status:string;nodeIdentity:string;script:string;timeoutMs:number;invocation:{executable:string;args:string[]}}
export interface PreviewJob {id:string;taskId:string;runId:string;planId:string;planFingerprint:string;status:string;url:string;port:number;summary?:string;logExcerpt?:string;logArtifactId?:string;requiresVerification?:boolean;reconciliation?:{at:string;result:string};process?:{pid:number;treeTermination?:string};readiness?:{observedAt:string;sha256:string}}
export interface ExecutionSnapshot {environmentDiagnostics?:EnvironmentDiagnostic[];environmentPlans?:EnvironmentPlan[];environmentJobs?:EnvironmentJob[];previewPlans?:PreviewPlan[];previewJobs?:PreviewJob[]}
export interface BrowsingTab {id:string;sessionId:string;projectId:string;taskId:string;runId:string;profileId:string;status:string;url:string;title?:string;origins:string[];interact:boolean;persistent:boolean;revision?:string;observationId?:string;previewOrigin?:string;error?:string}
export interface BrowsingObservation {id:string;tabId:string;revision:string;url:string;title:string;text:string;createdAt:string;scope:{complete:boolean};controls:{ref:string;tag:string;type:string;label:string;disabled:boolean;restricted?:boolean;href?:string}[];screenshotArtifactId:string;screenshotSha256:string;artifactId:string}
export interface BrowsingAction {id:string;tabId:string;kind:string;status:string;createdAt:string;input:{action?:string;ref?:string;value?:string;url?:string};error?:string;artifactId?:string;downloadArtifactId?:string;downloadSha256?:string;reconciliation?:{at:string}}
export interface BrowsingSnapshot {available:boolean;tabs:BrowsingTab[];observations:BrowsingObservation[];actions:BrowsingAction[];profiles:{id:string;origins:string[];status:string}[]}
export interface ExecutionSnapshot {browsingTabs?:BrowsingTab[];browsingActions?:BrowsingAction[]}
export interface CheckPlan {environment?:NodeEnvironmentBinding|null}
export interface CheckJob {environment?:NodeEnvironmentBinding|null}
export interface Approval {environmentPlanId?:string}
export interface Approval {browsingTabId?:string;mcpRegistrationId?:string}
export interface Approval {environmentSummary?:Pick<EnvironmentPlan,'root'|'registry'|'scripts'|'offline'|'timeoutMs'|'lifecycle'|'installScriptPackages'>}
export interface NodeEnvironmentBinding {preparation?:{jobId:string;planId:string;sessionId:string;logArtifactId:string;logSha256:string}|null}
export interface ModelSelection { type: 'legacy' | 'connection' | 'pool'; id: string; name: string }
export interface WorkspaceOrigin { id: string; sourceProjectId: string; sourceSessionId: string; sourceRoot: string; sourceWorkspaceId: string | null; baseCommit: string; branch: string; commonGitDir: string; gitDir: string; fingerprint: string }
export interface WorkspaceIdentity { kind: 'local-project' | 'managed-worktree'; projectId: string; root: string; workspaceId?: string; sourceProjectId?: string; sourceSessionId?: string; sourceRoot?: string; sourceWorkspaceId?: string | null; baseCommit?: string; branch?: string; commonGitDir?: string; gitDir?: string; fingerprint?: string }
export interface Project { id: string; root: string; name: string; addedAt: string; workspace?: WorkspaceOrigin }
export interface WorkspaceRecord {
id: string; projectId: string; sessionId: string; taskId: string | null; runId: string | null; label: string; root: string; branch: string;
childProjectId: string; childSessionId: string; status: string; phase: string; fingerprint: string;
createdAt: string; updatedAt: string; finishedAt: string | null; creationAttempted: boolean; requiresVerification: boolean;
ownerPid: number | null; gitPid: number | null; summary: string;
source: { root: string; head: string; branch: string; dirty: boolean; changedPathCount: number; changedPaths: { status: string; path: string; originalPath?: string }[]; fingerprint: string; committedBytes: number; treeFiles: { mode: string; blob: string; bytes: number; path: string }[] };
observation?: { rootState: string; branchHead: string | null; workspaceHead: string | null; workspaceBranch: string | null; registered: boolean; clean: boolean; contentsVerified: boolean; sourcePreserved: boolean; ready: boolean; fingerprint: string; observedAt: string; problems: string[] } | null;
}
export interface SessionBrief { id: string; projectId: string; title: string; status: string; revision: number; updatedAt: string; changeCount: number }
export interface Message { id: string; role: string; content: string; createdAt: string; attachmentIds?: string[] }
export interface InputAttachment { id:string;name:string;status:string;mediaType:string;taskId:string|null;runId:string|null;sha256:string;bytes:number;sentSha256:string;sentBytes:number;width:number;height:number;sentWidth:number;sentHeight:number;orientation:number }
export interface BudgetPause { reason:string;requiredInputTokens?:number;contextLimit?:number;inputBudget?:number;outputReservation?:number;safetyTokens?:number;runRemainingTokens?:number|null;taskRemainingTokens?:number|null;imageReservationTokens?:number;breakdown?:Record<string,number> }
export interface Run { budgetPause?:BudgetPause }
export interface BudgetPause { originalInputTokens?:number;transportReservationTokens?:number }
export interface BudgetPause { limitingReason?:string;pauseKind?:string }
export interface BudgetPause { modelFailure?:RuntimeFailure }
export interface TokenBudgetCounter { maximumTokens:number;reportedTokens:number;unknownRequests:number;estimatedUnknownTokens:number;accountedTokens:number;remainingTokens:number|null;exceededTokens:number }
export interface BudgetPause { remainingTokens?:number;tokenReservation?:{schemaVersion:number;reservedTokens:number;routes:{sources:{runId:string;attemptId:string}[]}[]};tokenAccounting?:{schemaVersion:number;singleInFlightResponseMayExceed:boolean;run:TokenBudgetCounter;task:TokenBudgetCounter} }
export interface ToolEvent {
id: string; kind: string; label: string; phase: string; createdAt: string; tool?: string;
input?: Record<string, unknown>; output?: string; durationMs?: number; startedAt?: string; finishedAt?: string;
source?: string; attempts?: number; diagnostic?: RuntimeFailure; exitCode?: number;
taskId?: string; runId?: string; invocationId?: string; artifactId?: string;
connectionId?: string; actualModel?: string;
stream?: { status: string; protocol?: string; sequence?: number; bytes?: number; textCharacters?: number; textPreview?: string; toolFragments?: number };
}
export interface DiffPart { value: string; count: number; added?: boolean; removed?: boolean }
export interface Change {
taskId?: string | null; runId?: string | null;
changeSetId?: string; rolledBackAt?: string;
id: string; path: string; reason: string; status: string; baseExists: boolean; baseSha256: string | null;
baseContent: string; content: string; sha256: string; diff: DiffPart[]; additions: number; deletions: number;
createdAt: string; appliedAt?: string;
editKind?: 'exact-patch';
patch?: { edits: number; lineEnding: 'lf' | 'crlf' | 'mixed'; preservedBom: boolean; ranges: { startLine: number; endLine: number; anchorSha256: string; replacementSha256: string }[] };
}
export interface Approval { id: string; command: string; reason: string; cwd: string; shell?: string; status: string; createdAt: string; browserPlanId?: string; browserSummary?: { buildDirectory: string; buildSha256: string; viewport: { width: number; height: number }; steps: BrowserStep[] }; checkPlanId?: string; checkScripts?: { name: string; script: string; lifecycle: { name: string; script: string }[]; python?: { mode: string; runtime: PythonRuntimeIdentity } }[] }
export interface Session {
id: string; projectId: string; title: string; status: string; revision: number; updatedAt: string; createdAt: string;
messages: Message[]; events: ToolEvent[]; changes: Change[]; approvals: Approval[];
compactions: number; estimatedTokens: number; usage: { prompt_tokens?: number; completion_tokens?: number } | null;
archived: boolean; recoveryNotice?: string | null; executionMode?: string;
failure?: RuntimeFailure | null; lastFailure?: RuntimeFailure | null;
execution?: ExecutionSnapshot;
inputAttachments?: InputAttachment[];
}
export interface RuntimeFailure {
modelIdentity?: import('../shared/contracts/model-identity.mjs').ModelIdentity;
source: string; stage: string; kind: string; title: string; message: string; messageId?: string;
detail?: string; suggestion?: string; attempts?: number; httpStatus?: number; code?: string | null;
occurredAt?: string; retryable?: boolean; historical?: boolean; endpoint?: string; model?: string;
requestUrl?: string; responseUrl?: string | null; redirected?: boolean; redirectMode?: string;
origin?: 'upstream' | 'local'; route?: string; type?: string | null; wireAttemptId?: string; upstreamRequestId?: string | null; retryAfterMs?: number; retryDecision?: string; limitReason?: string | null;
upstream?: { schema: number; scope: string; httpStatus?: number; code?: string | null; type?: string | null; message?: string | null; param?: string | null;
requestId?: string | null; responseId?: string | null; eventType?: string | null; reason?: string | null; headers?: Record<string, string>; retryAfter?: string | null;
retryAfterMs?: number | null; retryAfterInvalid?: boolean; rawPreview?: string; previewTruncated?: boolean; shortenedFields?: string[];
artifactId?: string; artifactSha256?: string; artifactScope?: string; sessionId?: string;
capture?: { scope: string; receivedBytes: number; capturedBytes: number; storedBytes: number; retention?: string; complete: boolean; truncated: boolean; interrupted: boolean; redacted: boolean; sha256: string; capturedRange: number[] } };
}
export interface ExecutionEnvironment { platform: string; node: string; shell: string; encoding: string; shellSyntax: string }
export interface RuntimeDiagnostics {
version: string; environment: ExecutionEnvironment;
projectCache?: ProjectCacheStatus;
connection: { mode: string; endpoint: string; model: string; hasKey: boolean; lastRequest: { status?: string; attempts?: number; durationMs?: number } | null };
session: {
project: { name: string; root: string }; session: { id: string; status: string; revision: number };
lastFailure: RuntimeFailure | null;
changes: { id: string; path: string; status: string }[];
recentTools: { tool: string; phase: string; outputExcerpt: string; exitCode: number | null }[];
} | null;
}
export interface FileEntry { path: string; name: string; kind: string; bytes: number }
export interface OpenFile { path: string; content: string; sha256: string; bytes: number; bom?: boolean }
export interface Bootstrap { token: string; version: string; config: Config; modelSelection?: ModelSelection; projects: Project[]; sessions: SessionBrief[]; exampleProjectId: string | null; environment?: ExecutionEnvironment; eventCursor?: number; storage?: { engine: string; schemaVersion: number }; runtimeRoot?: string }
export interface ResearchDoc { id: string; title: string; description: string }
export type CodeQueryKind = 'all' | 'symbols' | 'imports' | 'files';
export interface ProjectCacheMetrics {
enabled: boolean; persistent: boolean; checkedAt: string; sourceVerified: boolean; origin: string; invalidation: string | null;
reusedFiles: number; rebuiltFiles: number; parsedFiles: number; invalidatedFiles: number; removedFiles: number;
verifiedFiles: number; verificationPasses: number; sourceBytesRead: number; parseMs: number; durationMs: number;
stored: boolean; storageReason: string; evictedProjects: number; diskProjects: number; diskBytes: number;
maximumProjects: number; maximumBytes: number; maximumEntryBytes: number; error: string | null;
}
export interface ProjectCacheStatus {
enabled: boolean; persistent: boolean; diskProjects: number; diskBytes: number; maximumProjects: number; maximumBytes: number;
maximumEntryBytes: number; error: string | null; memoryProjects?: number; memoryBytes?: number; pending?: number;
latest?: ProjectCacheMetrics | null; clearedAt?: string; removedProjects?: number;
}
export interface CodeIndexSummary {
schemaVersion: number; projectId: string; projectName: string; parser: string; generatedAt: string; sourceFingerprint: string; indexFingerprint: string;
coverage: { snapshotComplete: boolean; fileCount: number; symbolCount: number; importCount: number; astFiles: number; pythonCandidateFiles: number; unindexedFiles: number; truncated: boolean; maximumFileBytes: number; maximumSymbols: number };
refresh: { updatedFiles: number; reusedFiles: number; removedFiles: number };
sourceScope: { complete: boolean; scannedFiles: number; bytes: number; maximumFiles: number; maximumBytes: number; excludedFiles: number; note: string };
warnings: { path: string; sha256: string; status: string; message: string; line: number }[]; notes: string[];
cache?: ProjectCacheMetrics;
}
export interface CodeResult {
resultKind: 'symbol' | 'import' | 'file'; path: string; line: number; sha256: string; name: string; kind: string;
qualifiedName?: string; signature?: string; evidenceMethod: string; exported?: boolean; status?: string; target?: string | null;
}
export interface CodeQuery { query: string; kind: CodeQueryKind; results: CodeResult[]; totalMatches: number; truncated: boolean; index: CodeIndexSummary }
export interface ModelSnapshot { mode: string; model: string; baseUrl: string; verified?: boolean; contextLimit?: number; maxOutputTokens?: number; routing?: { type: string; name: string; members: { id: string; name: string; model: string; baseUrl: string }[] } }
export interface ModelConsumption { modelIdentity?: import('../shared/contracts/model-identity.mjs').ModelIdentity; attemptId: string; requestId: string | null; connectionId: string | null; connectionName: string | null; model: string; endpoint: string; protocol: string; usageStatus: string; outcome: string; usage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null; estimatedUnknownTokens: number }
export interface Usage { requests: number; inputTokens: number; outputTokens: number; totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
export interface RunBudget { maxSteps: number; maxDurationMs: number; maxTokens: number; maxTaskTokens: number }
export interface RunBrief { id: string; taskId: string; status: string; startedAt: string; finishedAt: string | null; steps: number; toolCalls: number; usage: Usage; stopReason: string | null; model: ModelSnapshot; budget: RunBudget; resumeOf: string | null; workspaceIdentity?: WorkspaceIdentity }
export interface Run extends RunBrief { engine: string; review?: { kind: string; planId: string; status: string; preparedAt?: string; resolvedAt?: string }; currentContextPlanId?: string; checkpoint: { completedToolIds: string[]; pendingToolIds: string[]; requiresVerification: string[] } }
export interface TurnObservation {
stepId: string | null; stepIndex: number | null; phase: string; classification: string; reasons: string[]; truncated: boolean;
delta: { read_characters: number; repeated_reads: number; changed_files: number; check_results: number; requirement_evidence: number; new_failures: number; repeated_failures: number };
waiting: { kind: string; id: string }[];
}
export interface Run { progressShadow?: { mode: 'shadow'; observations: number; truncated: boolean; turns: TurnObservation[] }; progressShadowArtifactIds?: string[]; progressShadowError?: { kind: string; phase: string } }
export interface RunBrief { purpose?: 'execution' | 'diagnostic'; source?: string; taskStatusBefore?: string; consumption?: ModelConsumption[] }
export interface TaskCheckpoint {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; createdAt: string;
status: string; artifactId: string; sha256: string; sourceFingerprint: string; requirementsSha256: string;
counts: { tools: number; completed: number; unknown: number; pendingChanges: number };
}
export interface TaskCheckpointView {
checkpoint: TaskCheckpoint; integrity: string; checkedAt: string; resumable: boolean; reasons: string[]; currentSourceFingerprint: string;
}
export interface ContextPlan {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; stepId: string; requestIndex?: number; status: string;
createdAt: string; finishedAt: string | null; requestSha256: string; requestBytes: number; requestArtifactId: string; artifactId: string;
estimatedInputTokens: number; beforeInputTokens: number; beforeBytes: number; estimateMethod: string;
originalMessages: number; retainedMessages: number; archivedGroups: number; historyIndexArtifactId: string | null; historyIndexSha256: string | null;
workingSetArtifactId?: string | null; workingSetSha256?: string | null; workingSetEntries?: number;
workingSetViewVersion?: number; workingRetentionTokens?: number;
latestToolsArtifactId?: string | null; latestToolsSha256?: string | null; latestToolsEntries?: number;
projectMemoryArtifactId?: string | null; projectMemorySha256?: string | null; projectMemoryEntries?: number;
skillCatalogArtifactId?: string | null; skillCatalogSha256?: string | null; skillCatalogEntries?: number;
actualUsage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null; requestAttempts: number; error?: string;
budget: { contextLimit: number; outputReservation: number; safetyTokens: number; inputBudget: number; targetInputTokens: number; runRemainingTokens: number | null; taskRemainingTokens: number | null };
}
export interface ContextHistoryGroup {
index: number; startMessage: number; endMessage: number; sha256: string; roles: string[];
tools?: { call_id: string; name: string; result: { status?: string; path?: string; requires_verification?: boolean }; recorded_state?: string; requires_verification?: boolean; result_artifact_id?: string }[];
archive: { artifact_id: string; sha256: string; bytes: number; chunks?: number };
}
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 }
export interface ProjectMemory { schemaVersion: number; id: string; projectId: string; sessionId: string; taskId: string | null; runId: string | null; title: string; content: string; tags: string[]; source: ProjectMemorySource; sourceFingerprint: string; status: 'current' | 'unverified' | 'expired' | 'archived'; createdAt: string; updatedAt: string; expiresAt: string | null; expiredAt?: string | null; expiredReason?: string | null; archivedAt?: string; origin: string }
export interface ProjectMemoryView { projectId: string; sourceFingerprint: string; inspectedAt: string; scope: { complete: boolean; scannedFiles: number; bytes: number; excludedFiles: number; maximumFiles: number; maximumBytes: number; note: string }; memories: ProjectMemory[]; summary: { current: number; unverified: number; expired: number; archived: number; total: number; invalidated: number }; rule: string }
export interface PythonRuntimeIdentity { status: string; logicalExecutable?: string | null; executable: string | null; version: string | null; sha256?: string; baseExecutable?: string; baseSha256?: string; message?: string; probe?: string }
export interface CheckResult { id: string; name: string; kind: string; command: string; status: string; exitCode: number | null; durationMs: number; tests: { total: number; passed: number; failed: number; skipped: number; cancelled: number } | null; logArtifactId?: string; reason?: string;
engine?: string; python?: { mode: string; runtime: PythonRuntimeIdentity; invocationId: string; inputSha256: string; runner: { path: string; sha256: string } };
compilation?: { total: number; compiled: number; failures: { path: string; line?: number; message: string }[] } | null; collectionErrors?: number | null;
metricsArtifactId?: string; metricsSha256?: string; inputArtifactId?: string; evidenceValidated?: boolean }
export interface CheckJob { id: string; taskId: string; runId: string; planId: string; status: string; startedAt: string; finishedAt: string | null; results: CheckResult[]; summary?: string; stale?: boolean; currentCheck?: { name: string; command: string; startedAt: string } | null; baseline?: { head: string | null; dirty: boolean; branch: string | null }; fingerprint?: string; sourceFingerprint?: string }
export interface CheckPlan { id: string; taskId: string; runId: string; status: string; fingerprint: string; createdAt: string; checks: { id: string; name: string; kind: string; command: string; script: string; lifecycle: { name: string; script: string }[]; python?: { mode: string; runtime: PythonRuntimeIdentity } }[]; project: { name: string; languages: string[]; packageManager: string; scripts?: { name: string; kind: string }[]; rules: { path: string; sha256: string; excerpt: string }[]; python?: { status: string; framework?: string; message?: string; checks?: { name: string; kind: string }[] }; scope: { complete: boolean; scannedFiles: number }; git: { available: boolean; head: string | null; dirty: boolean; branch: string | null; status: string } } }
export interface DeliveryPlan {
preparedBy?: 'agent' | 'user';
id: string; sessionId: string; projectId: string; taskId: string; runId: string; status: string; message: string;
author: { name: string; email: string; source: string }; baseline: { head: string; branch: string; reference: string };
paths: string[]; files: { path: string; changeIds: string[]; mode: string; sha256: string; additions: number; deletions: number; reason: string; diff: string }[];
checkJobId: string; checkSummary: { name: string; command: string; exitCode: number; tests: CheckResult['tests']; logArtifactId: string }[];
sourceFingerprint: string; diffArtifactId: string; policy: { note: string; hooks: string; signing: string };
}
export interface DeliveryJob {
id: string; sessionId: string; taskId: string; runId: string; planId: string; status: string; parent: string; branch: string; paths: string[];
commit: string | null; expectedCommit?: string | null; summary?: string; requiresVerification: boolean; startedAt: string; finishedAt: string | null;
reportArtifactId?: string; reportMarkdownArtifactId?: string; reportError?: string; indexPreserved?: boolean; workspacePreserved?: boolean;
}
export interface ChangeSet {
id: string; taskId: string; runId: string; sessionId: string; projectId: string; fingerprint: string;
status: string; requiresVerification: boolean; summary: string; createdAt: string; finishedAt?: string;
baseline: { available: boolean; head: string | null; branch: string | null }; observationFingerprint?: string;
files: { changeId: string; path: string; baseExists: boolean; baseSha256: string | null; sha256: string; bytes: number;
baseBytes: number; mode: number; reason: string; state: string; writeAttempted: boolean; restoreAttempted: boolean;
snapshotArtifactId: string; sourceRunId: string; restoreError?: string }[];
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' | '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 }
export interface TaskPlanStepView extends TaskPlanStep {
status: string; blockers: string[]; evidence_verified: boolean; proof_id: string | null; proof_artifact_id: string | null; error: string | null;
evidence: { id: string; runId: string; artifacts?: { id: string; kind: string; sha256: string }[] } | null;
last_rejection?: { id: string; message: string; at: string };
candidates?: { id: string; status: string; label: string; runId: string }[];
}
export interface TaskPlanView {
configured: boolean; task_id: string; plan_id?: string; revision: number; status: string; steps: TaskPlanStepView[]; all_verified: boolean;
verified_steps?: number; total_steps?: number; ready_steps?: string[]; remaining_steps?: string[]; requirements_current?: boolean;
contract_artifact_id?: string; contract_sha256?: string; checked_at?: string; error?: string;
}
export interface TaskPlanReply { session: Session; plan: TaskPlanView; verification?: { status: string; reused?: boolean; proof_id: string; message?: string } }
export interface RequirementSource { kind: 'goal' | 'instruction'; id: string; text: string; sha256: string; at: string | null }
export interface RequirementItem extends TaskPlanStep {
method: 'evidence' | 'user' | 'not_requested'; source: { kind: string; id: string; start: number; end: number; quote?: string; sourceSha256?: string; at?: string | null };
revision?: number; status?: string; error?: string | null; proof_id?: string | null; proof_artifact_id?: string | null; user_note?: string | null;
evidence?: TaskPlanStepView['evidence']; candidates?: TaskPlanStepView['candidates']; last_rejection?: { message: string } | null;
}
export interface RequirementView {
configured: boolean; task_id: string; revision: number; status: string; items: RequirementItem[]; sources: RequirementSource[];
all_resolved: boolean; unreviewed_sources?: string[]; error?: string; note: string; contract_artifact_id?: string;
history?: { id: string; key: string; revision: number; status: string; error: string | null; at: string; artifact_id: string }[];
}
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; mcpJobs?: McpJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface WorkerBudget { maxTokens: number; maxSteps: number; maxToolCalls: number }
export interface WorkerDefinition { id: string; label: string; goal: string; paths: string[]; budget: WorkerBudget; workspaceId: string; projectId: string; sessionId: string; taskId: string; engine?: ControlledEngineAvailability }
export interface WorkerRecord extends WorkerDefinition {
collaborationId: string; parentProjectId: string; parentSessionId: string; parentTaskId: string; parentRunId: string;
runId: string; currentRunId: string | null; runIds: string[]; baseCommit: string; fingerprint: string; status: string; requiresVerification: boolean;
startedAt: string | null; finishedAt: string | null; summary: string; result: { artifactId: string; sha256: string; checkJobId: string; paths: string[] } | null;
usage?: Usage & { accountedTokens: number; steps: number; toolCalls: number }; sessionStatus?: string;
}
export interface WorkerConflict { path: string; reason: string; workerIds: string[] }
export interface CollaborationGroup {
id: string; taskId: string; runId: string; projectId: string; sessionId: string; goal: string; fingerprint: string;
status: string; phase?: string; requiresVerification: boolean; summary: string; createdAt: string; startedAt: string | null; finishedAt: string | null; deadline: number | null;
model: { mode: string; model: string; baseUrl: string }; budget: WorkerBudget & { maxDurationMs: number };
source: { identity: { root: string; head: string; branch: string; indexSha256: string }; dirty: boolean; changedPaths: { path: string; status: string }[] };
children: WorkerDefinition[]; workers?: WorkerRecord[]; usage?: { accountedTokens: number; steps: number; toolCalls: number; requests?: number; unknownRequests: number };
collection: { artifactId: string; sha256: string; conflicts: WorkerConflict[]; paths: string[] } | null;
merge: { changeSetId?: string; fingerprint?: string; changeIds?: string[] } | null;
evidence?: { artifactId: string; sha256: string } | null;
}
export interface WorkerView { groups: CollaborationGroup[]; worker: WorkerRecord | null }
export interface CollaborationGroup { evaluation?: { batchId: string; sampleId: string } }
export interface WorkerDefinition { evaluation?: { batchId: string; sampleId: string; role: 'original' | 'candidate' } }
export interface EvaluationRole {
outcome: string; reason?: string; evidenceError?: string; workerStatus?: string; startedAt?: string; finishedAt?: string;
usage: { requests: number; totalTokens: number; unknownRequests?: number; estimatedUnknownTokens?: number; reported: boolean; cost?: number | null } | null;
attempts: { id: string; status: string; summary?: string; results: { name: string; command?: string; status?: string; exitCode?: number; durationMs?: number; tests?: CheckResult['tests']; logArtifactId: string; logSha256?: string }[] }[];
approvals?: { id: string; status: string; decidedAt?: string }[]; changes?: { id: string; path: string; status: string }[];
}
export interface EvaluationReport {
schemaVersion: number; batchId: string; sampleId: string; label: string; goal: string; criteria: string; source: { head: string };
inputVerified: boolean; inputError?: string; summary: { original: string; candidate: string }; original: EvaluationRole; candidate: EvaluationRole;
evidenceMode: string; note: string; sealedAt: string;
}
export interface EvaluationSample {
id: string; label: string; goal: string; criteria: string; paths: string[]; checks: string[]; status: string; groupId?: string; error?: string;
baselineAttemptedAt?: string; baselineJobId?: string; contractSha256?: string;
commands?: { name: string; command: string; script: string; lifecycle?: { name: string; script: string }[] }[];
report: { artifactId: string; sha256: string; summary: { original: string; candidate: string } } | null; workers?: WorkerRecord[];
}
export interface EvaluationBatch {
id: string; title: string; fingerprint: string; status: string; source: { head: string; branch: string }; model: ModelSnapshot;
message: string; evidenceMode: string; samples: EvaluationSample[]; budget: WorkerBudget & { maxDurationMs: number }; deadline: number | null;
adoption: { sampleId: string; status: string; delivery?: { commit: string } } | null;
summary: { samples: number; finished: number; candidate: Record<string, number>; scope: string };
}
export interface McpTool { name: string; description: string; inputSchema: Record<string, unknown>; unsupported?: string }
export interface McpRegistration {
id: string; projectId: string; name: string; launch: { executable: { path: string; sha256: string; bytes: number }; entry: { path: string; sha256: string; bytes: number } | null; args: string[]; environment: string; identityScope: string };
timeoutMs: number; configurationRevision: number; enabled: boolean; allowedTools: string[];
contract: { artifactId: string; sha256: string } | null; createdAt: string; updatedAt: string; status: string; reason: string; tools: McpTool[];
}
export interface McpJob {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; registrationId: string; configurationRevision: number;
invocationId?: string | null; reviewedAt?: string; reviewedBy?: string; evidenceSha256?: string;
operation: 'probe' | 'call'; status: string; startedAt: string; finishedAt: string | null; requiresVerification: boolean; dispatched: boolean; processStarted: boolean;
input?: { launch?: unknown; protocolVersion?: string; contractSha256?: string | null; call?: { tool: string; arguments: Record<string, unknown> }; timeoutMs?: number }; inputArtifactId?: string; inputSha256?: string; pid?: number;
reportArtifactId?: string; reportSha256?: string; cleanup?: { connectionId?: string; pid: number | null; rootExited: boolean; forced?: boolean; scope?: string; exit?: { code: number | null; signal: string | null } | null };
error?: { code: string; message: string } | null;
}
export interface EngineAvailability {
engineId: string; name: string; status: string; root: string | null; profile: string; expectedVersion: string; version?: string; message: string;
identitySha256?: string; node?: { path: string; version: string; sha256: string };
serverInfo?: { name: string; version: string }; limitations: string[];
capabilities: { connectionProbe: boolean; projectExecution: boolean; prompt: boolean; singleSessionCancel: boolean; cancellationUnit: string; tokenStreaming: boolean };
}
export interface EngineJob {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; engineId: string; scope: string;
installation: EngineAvailability; sdkSessionId: string; status: string; summary: string; requiresVerification: boolean;
startedAt: string; finishedAt: string | null; pid?: number; connectionId?: string;
readiness?: { pid: number; signal: string; readyAt: string }; serverInfo?: { name: string; version: string };
verification?: { verified: boolean; rootExited: boolean; modelRequests: number } | null;
reportArtifactId?: string; reportSha256?: string; contractSha256: string;
reportSummary?: { status: string; modelRequests: number | null; observedResponses: number; rootExited: boolean | null } | null;
}
export interface ControlledEngineAvailability extends EngineAvailability {
controlledStatus: string; controlledSha256?: string; scope: string; bridgeSha256?: string;
controlledCapabilities?: { text: boolean; nativeSessionResume: boolean; nativeModelCredentials: boolean; cancellationUnit: string };
strategy?: PurgePromptStrategy | PurgeOriginalStrategy;
}
export interface PurgeSourceAvailability {
status: string; root: string | null; message: string; version?: string; sourceSha256?: string;
defaultEnabled: boolean; defaultPrompt: string; supportedVersions: string[];
inputs?: { relative: string; path: string; bytes: number; sha256: string }[];
kind?: 'purge-prompt-experiment' | 'purge-original-restricted-v1'; runtimeSha256?: string; runtimeInputs?: number;
}
export interface PurgePromptStrategy {
kind: 'purge-prompt-experiment'; enabled: true; sha256: string; prompt: string; promptSha256: string;
source: { root: string; version: string; sourceSha256: string };
section: { name: string; order: number; interpolate: false; text: string; textSha256: string };
}
export interface PurgeOriginalStrategy {
kind: 'purge-original-restricted-v1'; enabled: true; sha256: string; prompt: string; promptSha256: string;
source: { root: string; version: string; sourceSha256: string };
runtime: { root: string; sha256: string; inputs: { path: string; sha256: string }[]; nativeAddons: { path: string; sha256: string }[] };
originalConfig: { autoRetry: false; autoContinue: false; hooksDenyBypass: false; postPrompt: string };
}
export interface EngineRunView {
id: string; projectId: string; sessionId: string; taskId: string; runId: string; workerId: string; collaborationId: string;
installation: ControlledEngineAvailability; sdkSessionId: string; status: string; requiresVerification: boolean; verified: boolean;
startedAt: string; finishedAt: string | null; error?: string | null; inputArtifactId: string; inputSha256: string;
reportArtifactId?: string; reportSha256?: string; modelRequests: number; toolRequests: number; notificationCount?: number;
nativeSummary: { status: string | null; pid: number | null; rootExited: boolean | null; treeConfirmed?: boolean | null; receipt: { messageId: string } | null; notifications: number };
review?: { source: string; evidenceSha256: string; reviewedAt: string; result: string };
}
export interface ReaAvailability { status: string; version?: string; declaredVersion?: string; message?: string; packageRoot?: string; protocolVersion?: string; operations?: { id: string; name: string; extensions: string[]; label: string }[] }
export interface ResearchTarget { id: string; taskId: string; runId: string; projectId: string; sessionId: string; path: string; sha256: string; bytes: number; extension: string; label: string; source: string; registeredAt: string }
export interface ResearchJob {
id: string; taskId: string; runId: string; targetId: string; targetSha256: string; operation: string; operationId: string;
status: string; summary: string; startedAt: string; finishedAt: string | null; evidenceId?: string; reusedFromJobId?: string;
evidenceBinding?: { verified: boolean; statistics?: Record<string, unknown>; limitations: string[]; scope: string } | null;
installation: ReaAvailability; before?: { path: string }; raw?: { id: string; documentSha256: string }; traceArtifactId?: string;
cleanup?: { rootExited: boolean }; requiresVerification: boolean;
}
export interface ResearchPage { content: string; offset: number; next_offset: number; total_characters: number; truncated: boolean; pointer?: string;
evidence_id?: string; target_sha256?: string; source_document_sha256: string; available_fields?: string[] }
export interface BrowserStep { action: 'fill' | 'select' | 'click' | 'assert_text' | 'assert_count' | 'assert_visible'; selector: string; value?: string; text?: string; count?: number; visible?: boolean; contains?: boolean }
export interface BrowserPlan { id: string; taskId: string; runId: string; status: string; fingerprint: string; sourceFingerprint: string; build: { directory: string; files: number; bytes: number; sha256: string }; path: string; viewport: { width: number; height: number }; steps: BrowserStep[] }
export interface BrowserJob { id: string; taskId: string; runId: string; planId: string; planFingerprint: string; sourceFingerprint: string; buildSha256: string; status: string; startedAt: string; finishedAt: string | null; summary: string; resultArtifactId?: string; resultSha256?: string; assertions: { total: number; passed: number; failed: number }; requiresVerification: boolean; cleanup?: { exited: boolean; pid: number | null }; steps: (BrowserStep & { status: string; error?: string; actual?: unknown })[]; screenshots: { artifactId: string; sha256: string; bytes: number; width: number; height: number; label: string }[] }
export interface EvaluationReport {environmentComparison?:{dependencyInputs:string;matched:boolean}}
@@ -0,0 +1,90 @@
import { observeTurn, toolProgressFacts } from './turn-progress.mjs';
import { planHash } from '../../shared/contracts/task-plans.mjs';
// Local, bounded observation. Original tools/jobs remain the evidence of record.
// Observer failure is recorded on the Run and cannot interrupt execution.
export function recordTurnProgress(store, session, run, step, phase = 'settled', failure = null) {
try {
if (run.taskId !== session.taskId || run.sessionId !== session.id || run.projectId !== session.projectId) throw new Error('Observer Task/Run ownership mismatch.');
if (step && (step.runId !== run.id || step.taskId !== run.taskId || step.sessionId !== session.id || step.projectId !== session.projectId))
throw new Error('Observer step ownership mismatch.');
const task = store.owned('task', run.taskId, session.id);
const owned = row => row.taskId === run.taskId && row.sessionId === session.id && row.projectId === session.projectId;
const tools = [];
// Waiting is an intermediate snapshot, not a second consumption of tools
// already completed earlier in this same turn. Settle them exactly once.
for (const id of phase === 'waiting' ? [] : step?.progressToolIds ?? []) {
const record = store.owned('tool', id, session.id);
if (!owned(record) || record.runId !== run.id || record.stepId !== step.id) throw new Error('Observer tool ownership mismatch.');
const artifact = store.owned('artifact', record.resultArtifactId, session.id);
if (!owned(artifact) || artifact.runId !== run.id || artifact.kind !== 'tool-result') throw new Error('Observer result ownership mismatch.');
tools.push(toolProgressFacts(record, JSON.parse(store.artifactStore.read(artifact)), artifact, record.progressFailureCategory));
}
if (failure) {
const event = session.events.findLast(row => row.runId === run.id && row.diagnostic?.id === failure.id);
tools.push({ id: failure.id ?? null, name: 'model_request',
sourceEventId: event?.id, diagnosticSha256: event ? planHash(event.diagnostic) : null,
artifactId: failure.upstream?.artifactId, resultSha256: failure.upstream?.artifactSha256,
failure: { category: failure.kind ?? 'unknown', signature: planHash({ kind: failure.kind, code: failure.code,
httpStatus: failure.httpStatus, stage: failure.stage, outcome: failure.outcome, message: failure.message }) } });
}
const waiting = session.approvals.filter(row => row.taskId === run.taskId && row.projectId === session.projectId && row.runId === run.id && row.status === 'pending').map(row => ({ kind: 'approval', id: row.id }));
for (const row of store.core.check_job.values()) if (owned(row) && ['queued', 'running'].includes(row.status)) waiting.push({ kind: 'check_job', id: row.id });
if (session.status === 'needs_review') waiting.push({ kind: 'review', id: run.id });
const facts = { projectId: session.projectId, sessionId: session.id, taskId: run.taskId, runId: run.id,
stepId: step?.id, stepIndex: step?.index, phase, tools, waiting,
changes: session.changes.filter(row => row.taskId === run.taskId && row.status === 'applied').map(row => [row.path, row.sha256]),
checks: [...store.core.check_job.values()].filter(row => owned(row) && !row.requiresVerification && !row.stale && ['passed', 'failed'].includes(row.status))
.map(row => [row.sourceFingerprint, row.status, row.results.map(result => [result.name, result.status, store.core.artifact.get(result.logArtifactId)?.sha256])]),
requirements: (task.requirementProofs ?? []).filter(row => row.status === 'verified' && task.requirementRevisions?.at(-1)?.items.some(item => item.key === row.key && planHash(item) === row.requirementSha256))
.map(row => [row.key, row.requirementSha256, row.sourceFingerprint, row.outcome ? planHash(row.outcome) : planHash(row.note)]),
userBoundaries: (task.instructions ?? []).filter(row => row.source !== 'review-action').map(row => [row.id, planHash(row.content)]) };
const result = observeTurn(run.progressShadow, facts);
// Persist only the individual public-fact observation as an immutable receipt.
const artifact = store.artifactStore.write(session, run, result.observation, { kind: 'turn-progress-shadow' });
store.core.artifact.set(artifact.id, artifact);
run.progressShadow = result.state;
run.progressShadowArtifactIds = [...(run.progressShadowArtifactIds ?? []), artifact.id].slice(-40);
store.save(session, { type: 'run.progress_shadow', detail: { runId: run.id, stepId: step?.id ?? null, classification: result.observation.classification, artifactId: artifact.id } });
return result.observation;
} catch {
run.progressShadowError = { kind: 'observation_unavailable', phase };
return null;
}
}
export function inspectTurnProgress(store, session, run) {
if (!run.progressShadow) return { mode: 'shadow', recorded: false, turns: [], evidence_verified: false, error: run.progressShadowError ?? null };
const view = { mode: 'shadow', recorded: true, observations: run.progressShadow.observations, truncated: run.progressShadow.truncated,
turns: structuredClone(run.progressShadow.turns), artifact_ids: run.progressShadowArtifactIds ?? [], evidence_verified: true,
error: run.progressShadowError ? '部分观察未能记录,保留的原收据单独核对;原执行结果保持。' : null };
try {
const owned = row => row.sessionId === session.id && row.projectId === session.projectId && row.taskId === run.taskId && row.runId === run.id;
if (view.turns.length !== view.artifact_ids.length) throw new Error('单轮观察与原收据数量不一致。');
for (let i = 0; i < view.turns.length; i++) {
const artifact = store.owned('artifact', view.artifact_ids[i], session.id);
if (!owned(artifact) || artifact.kind !== 'turn-progress-shadow') throw new Error('单轮观察原收据归属不一致。');
const original = JSON.parse(store.artifactStore.read(artifact));
if (planHash(original) !== planHash(view.turns[i])) throw new Error('单轮观察与原收据不一致。');
for (const ref of original.tools) {
if (ref.tool === 'model_request') {
const event = session.events.find(row => row.id === ref.source_event_id && row.runId === run.id);
if (!event?.diagnostic || event.diagnostic.id !== ref.id || planHash(event.diagnostic) !== ref.diagnostic_sha256)
throw new Error('单轮观察的原模型失败记录待核对。');
if (ref.result_artifact_id) {
const result = store.owned('artifact', ref.result_artifact_id, session.id);
if (!owned(result) || result.sha256 !== ref.result_sha256 || !['model-http-response', 'model-stream-response'].includes(result.kind))
throw new Error('单轮观察的原模型失败响应来源变化。');
store.artifactStore.read(result);
}
continue;
}
const record = store.owned('tool', ref.id, session.id), result = store.owned('artifact', ref.result_artifact_id, session.id);
if (!owned(record) || !owned(result) || record.tool !== ref.tool || record.argsSha256 !== ref.args_sha256 || result.kind !== 'tool-result'
|| record.resultArtifactId !== result.id || result.sha256 !== ref.result_sha256) throw new Error('单轮观察的工具或原结果来源变化。');
store.artifactStore.read(result);
}
}
} catch { view.evidence_verified = false; view.error = '单轮观察的原收据或工具结果待核对;不用于交付通过判定。'; }
return view;
}
@@ -0,0 +1,97 @@
import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const validRange = read => read && typeof read.key === 'string' && /^[a-f0-9]{64}$/.test(read.sha256)
&& Number.isSafeInteger(read.start) && Number.isSafeInteger(read.end) && read.start >= 0 && read.end > read.start;
const merge = ranges => ranges.sort((a, b) => a[0] - b[0]).reduce((result, range) => {
const last = result.at(-1); if (last && range[0] <= last[1]) last[1] = Math.max(last[1], range[1]); else result.push([...range]); return result;
}, []);
const size = ranges => ranges.reduce((sum, [start, end]) => sum + end - start, 0);
export const TURN_PROGRESS_LIMITS = Object.freeze({ sources: 32, ranges: 24, facts: 96, failures: 48, turns: 40, tools: 64 });
// External facts only. Neither message wording nor model reasoning is an input.
// Every result is shadow data, never a stop/permission/budget decision.
export function observeTurn(previous, facts) {
const scope = { projectId: facts.projectId, sessionId: facts.sessionId, taskId: facts.taskId, runId: facts.runId };
if (previous && hash(previous.scope) !== hash(scope)) throw new Error('Turn observation belongs to another Task/Run.');
const state = previous ? structuredClone(previous) : { schemaVersion: 1, mode: 'shadow', scope, reads: [], facts: [], failures: [], turns: [], observations: 0, truncated: false };
let uncertain = false;
const remember = (collection, signature, limit) => {
if (collection.includes(signature)) return false;
if (collection.length >= limit) { state.truncated = true; uncertain = true; return false; }
collection.push(signature); return true;
};
const delta = { read_characters: 0, new_sources: 0, repeated_reads: 0, changed_files: 0, check_results: 0, requirement_evidence: 0,
user_boundaries: 0, new_failures: 0, repeated_failures: 0, other_observations: 0 };
const reasons = [], refs = [];
const tools = facts.tools ?? [];
if (tools.length > TURN_PROGRESS_LIMITS.tools) { state.truncated = true; uncertain = true; }
for (const tool of tools.slice(0, TURN_PROGRESS_LIMITS.tools)) {
refs.push({ id: tool.id, tool: tool.name, args_sha256: tool.argsSha256 ?? null, result_artifact_id: tool.artifactId ?? null, result_sha256: tool.resultSha256 ?? null,
...(tool.sourceEventId ? { source_event_id: tool.sourceEventId, diagnostic_sha256: tool.diagnosticSha256 } : {}) });
if (tool.failure) {
const signature = hash([tool.name, tool.argsSha256, tool.failure.category, tool.failure.signature]);
if (remember(state.failures, signature, TURN_PROGRESS_LIMITS.failures)) { delta.new_failures++; reasons.push('new_failure:' + tool.failure.category); }
else if (!uncertain) { delta.repeated_failures++; reasons.push('repeated_failure:' + tool.failure.category); }
continue;
}
if (validRange(tool.read)) {
const read = tool.read, key = hash([read.key, read.sha256, read.unit]);
let entry = state.reads.find(value => value.key === key);
if (!entry) {
if (state.reads.length >= TURN_PROGRESS_LIMITS.sources) { state.truncated = true; uncertain = true; continue; }
entry = { key, sha256: read.sha256, unit: read.unit, ranges: [] }; state.reads.push(entry); delta.new_sources++;
}
const ranges = merge([...entry.ranges, [read.start, read.end]]), growth = size(ranges) - size(entry.ranges);
if (ranges.length > TURN_PROGRESS_LIMITS.ranges) { state.truncated = true; uncertain = true; continue; }
entry.ranges = ranges; delta.read_characters += growth;
if (!growth) delta.repeated_reads++;
} else if (tool.observationSignature && remember(state.facts, hash(['observation', tool.name, tool.observationSignature]), TURN_PROGRESS_LIMITS.facts)) delta.other_observations++;
}
const count = (rows, kind, field) => {
if ((rows?.length ?? 0) > TURN_PROGRESS_LIMITS.facts) { state.truncated = true; uncertain = true; }
for (const row of (rows ?? []).slice(0, TURN_PROGRESS_LIMITS.facts))
if (remember(state.facts, hash([kind, row]), TURN_PROGRESS_LIMITS.facts)) delta[field]++;
};
count(facts.changes, 'changes', 'changed_files'); count(facts.checks, 'checks', 'check_results');
count(facts.requirements, 'requirements', 'requirement_evidence'); count(facts.userBoundaries, 'user', 'user_boundaries');
if (delta.read_characters) reasons.push('new_returned_file_or_artifact_range');
if (delta.repeated_reads) reasons.push('same_sha_range_already_returned');
for (const field of ['changed_files', 'check_results', 'requirement_evidence', 'user_boundaries', 'other_observations']) if (delta[field]) reasons.push(field);
const waiting = (facts.waiting ?? []).slice(0, 16).map(row => ({ kind: row.kind, id: row.id }));
const growth = delta.read_characters + delta.changed_files + delta.check_results + delta.requirement_evidence + delta.other_observations;
const classification = facts.phase === 'baseline' ? 'baseline' : waiting.length ? 'waiting' : growth ? 'evidence_growth' : delta.new_failures ? 'new_failure_evidence'
: delta.user_boundaries ? 'user_boundary' : uncertain ? 'unknown_bounded' : delta.repeated_failures ? 'repeated_failure_candidate'
: delta.repeated_reads ? 'repeated_read_candidate' : 'no_observed_change';
if (facts.phase === 'baseline') { for (const key of Object.keys(delta)) delta[key] = 0; reasons.length = 0; reasons.push('existing_facts_not_run_progress'); }
const observation = { schemaVersion: 1, mode: 'shadow', taskId: scope.taskId, runId: scope.runId,
stepId: facts.stepId ?? null, stepIndex: facts.stepIndex ?? null, phase: facts.phase ?? 'settled', classification,
delta, reasons: [...new Set(reasons)].slice(0, 16), tools: refs, waiting, truncated: state.truncated,
note: '外显事实观察;不等于业务交付,不改变停止、权限或预算。' };
state.observations++; state.turns.push(observation);
if (state.turns.length > TURN_PROGRESS_LIMITS.turns) { state.turns.shift(); state.truncated = true; }
return { state, observation };
}
export function toolProgressFacts(record, result, artifact, failureCategory = null) {
const value = { id: record.id, name: record.tool, argsSha256: record.argsSha256, artifactId: artifact?.id, resultSha256: artifact?.sha256 };
const status = result.status;
if (record.requiresVerification || ['unknown', 'interrupted', 'unverified'].includes(status)) {
value.failure = { category: 'requires_verification', signature: hash([status, result.code, result.message]) };
} else if (['failed', 'error', 'denied'].includes(status)) {
value.failure = { category: status === 'denied' ? 'permission' : failureCategory ?? 'tool_or_environment', signature: hash([status, result.code, result.message, result.exit_code]) };
} else if (['read_file', 'read_artifact', 'read_browser_result', 'read_research_evidence'].includes(record.tool) && typeof result.content === 'string') {
const start = result.offset ?? 0, end = result.next_offset ?? start + result.content.length;
// Offsets refer to UTF-16 characters within the original tool range. They
// are deliberately not labeled file bytes or cumulative token savings.
if (end - start === result.content.length) value.read = { key: hash([result.path ?? result.artifact_id ?? result.job_id,
result.range_start_line ?? result.start_line ?? null, result.range_end_line ?? result.end_line ?? null, result.section ?? null]),
sha256: result.sha256, start, end, unit: 'utf16_in_original_range' };
} else if (['inspect_project', 'list_files', 'search_files', 'index_project', 'query_code'].includes(record.tool)) {
const { tool_invocation_id, repeated_read_count, reading_hint, ...actual } = result;
// Random invocation IDs and changing timestamps are not observation growth.
delete actual.inspectedAt; delete actual.createdAt; delete actual.durationMs;
value.observationSignature = hash(actual);
}
return value;
}
@@ -0,0 +1,299 @@
import { verifyNodeBinding } from './environment/environment-inspector.mjs';
import { verifyEnvironmentPreparation } from './environment/environment-evidence.mjs';
import { inspectProject } from './project-inspector.mjs';
import { ChangeSetManager } from './workspaces/change-sets.mjs';
import { verifyPlanEvidence } from './context/request-plan.mjs';
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
import { projectWorkspaceIdentity, unresolvedWorkspaces } from '../shared/contracts/workspaces.mjs';
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 { RequirementReview } from './tasks/requirement-review.mjs';
import { inspectTurnProgress } from './context/turn-progress-recorder.mjs';
import { FileResults } from './tasks/file-results.mjs';
import { taskContract } from '../shared/contracts/task-control.mjs';
import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
existing_verified: '当前成果已核对,无新增修改', needs_requirements: '用户要求仍有待复核事项', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
export function verifiedCheck(store, session, inspection) {
const task = store.core.task.get(session.taskId);
const job = store.core.check_job.get(task?.verification.checkJobId);
if (!job || job.sessionId !== session.id || job.taskId !== task.id || job.projectId !== session.projectId
|| job.status !== 'passed' || job.stale || !inspection.scope.complete) return null;
const same = job.sourceFingerprint ? job.sourceFingerprint === inspection.sourceFingerprint : job.fingerprint === inspection.fingerprint;
if (!same || !job.results.length || job.results.some(result => result.status !== 'passed' || result.exitCode !== 0)
|| !job.results.some(result => result.kind === 'test' && result.tests?.passed > 0 && result.tests.passed === result.tests.total && !result.tests.failed && !result.tests.skipped && !result.tests.cancelled)) return null;
try { verifyNodeBinding(store.project(session.projectId),job.environment); verifyEnvironmentPreparation(store,session.projectId,job.environment); } catch { return null; }
for (const result of job.results) {
if (!result.logArtifactId) return null;
try {
const artifact = store.owned('artifact', result.logArtifactId, session.id);
if (artifact.taskId !== task.id || artifact.kind !== 'check-log') return null;
store.artifactStore.read(artifact);
verifyPythonCheckEvidence(store, session, job, result);
} catch { return null; }
}
return job;
}
export class DeliveryReporter {
constructor(store, { redact = String } = {}) { this.store = store; this.redact = redact; }
async create(session, { job = null, inspection = null } = {}) {
const taskId = session.taskId, runId = session.runId;
const task = this.store.owned('task', taskId, session.id);
const run = this.store.owned('run', runId, session.id);
const project = this.store.project(session.projectId);
await verifyWorkspaceProject(this.store, project);
inspection ??= await inspectProject(project);
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)
.map(value => ({ id: value.id, tool: value.tool, status: value.state }));
requiresVerification.push(...unresolvedWorkspaces(this.store, project.id).map(value => ({ id: value.id, tool: 'workspace', status: value.status })));
const unresolved = jobs.filter(value => value.requiresVerification || value.status === 'unknown');
const checkJobs = [...this.store.core.check_job.values()].filter(value => value.taskId === taskId);
const pythonEvidence = new Map();
for (const checkJob of checkJobs) if (!checkJob.stale && checkJob.sourceFingerprint === inspection.sourceFingerprint) {
for (const result of checkJob.results.filter(value => value.engine === 'python' && value.status === 'passed')) {
try { verifyPythonCheckEvidence(this.store, session, checkJob, result); pythonEvidence.set(result.id, { verified: true }); }
catch (error) {
pythonEvidence.set(result.id, { verified: false, error: error.message });
requiresVerification.push({ id: result.id, tool: 'python_check', status: 'evidence_unverified' });
}
}
}
const sets = [...this.store.core.change_set.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
const changeSets = sets.map(set => {
let snapshotVerified = true, snapshotError = null;
try { new ChangeSetManager(this.store).snapshots(session, set); } catch (error) { snapshotVerified = false; snapshotError = error.message; }
return { id: set.id, taskId: set.taskId, runId: set.runId, status: set.status, fingerprint: set.fingerprint,
paths: set.files.map(file => file.path), snapshotVerified, snapshotError, requiresVerification: !!set.requiresVerification,
summary: set.summary, verifiedAt: set.verifiedAt ?? null, finishedAt: set.finishedAt ?? null };
});
requiresVerification.push(...changeSets.filter(set => set.requiresVerification || !set.snapshotVerified)
.map(set => ({ id: set.id, tool: 'change_set', status: set.status })));
const commits = jobs.filter(value => value.status === 'completed' && value.commit && value.sourceFingerprint === inspection.sourceFingerprint);
const contextCache = new Map();
const contextPlans = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === taskId).map(plan => {
let evidenceVerified = true, evidenceError = null;
try {
verifyPlanEvidence(this.store, session, plan, contextCache);
} catch (error) { evidenceVerified = false; evidenceError = error.message; }
return { id: plan.id, runId: plan.runId, stepId: plan.stepId, status: plan.status, requestSha256: plan.requestSha256, requestBytes: plan.requestBytes,
requestArtifactId: plan.requestArtifactId, planArtifactId: plan.artifactId, estimatedInputTokens: plan.estimatedInputTokens,
beforeInputTokens: plan.beforeInputTokens, beforeBytes: plan.beforeBytes, estimateMethod: plan.estimateMethod, budget: plan.budget,
archivedGroups: plan.archivedGroups, retainedMessages: plan.retainedMessages, actualUsage: plan.actualUsage, requestAttempts: plan.requestAttempts,
historyIndexArtifactId: plan.historyIndexArtifactId, historyIndexSha256: plan.historyIndexSha256,
workingSetArtifactId: plan.workingSetArtifactId ?? null, workingSetSha256: plan.workingSetSha256 ?? null,
workingSetEntries: plan.workingSetEntries ?? 0, workingSetViewVersion: plan.workingSetViewVersion ?? 1,
workingRetentionTokens: plan.workingRetentionTokens ?? 0,
latestToolsArtifactId: plan.latestToolsArtifactId ?? null, latestToolsSha256: plan.latestToolsSha256 ?? null,
latestToolsEntries: plan.latestToolsEntries ?? 0, evidenceVerified, evidenceError };
});
requiresVerification.push(...contextPlans.filter(plan => !plan.evidenceVerified).map(plan => ({ id: plan.id, tool: 'model_context', status: 'evidence_unverified' })));
const deliveryReview = pendingDeliveryReview(this.store, session);
const browserVerification = await currentBrowserVerification(this.store, session, inspection);
const planner = new TaskPlanManager(this.store), taskPlan = await planner.inspect(session, { inspection, candidates: false });
const requirements = await new RequirementReview(this.store, { planner }).inspect(session, { inspection });
const taskPlanHistory = [...this.store.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
try { planner.planFor(session, value.id); evidenceVerified = true; } catch (error) { evidenceError = error.message; }
return { id: value.id, runId: value.runId, revision: value.revision, parentPlanId: value.parentPlanId, steps: value.steps,
requirementsSha256: value.requirementsSha256, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256, evidenceVerified, evidenceError };
});
const taskProofs = [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ id: value.id, runId: value.runId, planId: value.planId, stepKey: value.stepKey, status: value.status, evidenceId: value.evidenceId,
outcome: value.outcome, error: value.error, createdAt: value.createdAt, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256 }));
const browserChecks = [...this.store.core.browser_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
if (value.resultArtifactId) { try { verifyBrowserJob(this.store, session, value); evidenceVerified = true; } catch (error) { evidenceError = error.message; } }
if (value.requiresVerification || value.resultArtifactId && !evidenceVerified) requiresVerification.push({ id: value.id, tool: 'browser_check', status: 'evidence_unverified' });
return { id: value.id, taskId: value.taskId, runId: value.runId, planId: value.planId, status: value.status, summary: value.summary,
sourceFingerprint: value.sourceFingerprint, buildSha256: value.buildSha256, assertions: value.assertions, screenshots: value.screenshots,
resultArtifactId: value.resultArtifactId ?? null, resultSha256: value.resultSha256 ?? null, cleanup: value.cleanup ?? null,
requiresVerification: !!value.requiresVerification, evidenceVerified, evidenceError, acknowledgedAt: value.acknowledgedAt ?? null };
});
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('核对页面结果期间任务已切换,请重新生成报告。'), { status: 409 });
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'
: requirements.configured && !requirements.all_resolved ? 'needs_requirements'
: 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: requirements.status, note: '源码和检查证据不代替业务需求验收。' },
requirements,
turnObservations: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ runId: value.id, ...inspectTurnProgress(this.store, session, value) })),
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,
consumption: structuredClone(value.consumption ?? []),
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })),
usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null },
changes: changes.map(value => ({ id: value.id, path: value.path, status: value.status, reason: value.reason, baseSha256: value.baseSha256,
sha256: value.sha256, changeSetId: value.changeSetId ?? null, appliedAt: value.appliedAt ?? null, additions: value.additions, deletions: value.deletions })),
changeSets,
...(deliveryReview ? { deliveryReview: { planId: deliveryReview.id, status: 'pending', paths: deliveryReview.paths } } : {}),
contextPlans,
browserVerification, browserChecks,
taskPlan, taskPlanHistory, taskProofs,
checks: checkJobs.map(value => ({ id: value.id, status: value.status, planId: value.planId,
...(value.environment ? { environment:value.environment } : {}),
contractArtifactId: this.store.core.check_plan.get(value.planId)?.contractArtifactId ?? null,
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
sourceFingerprint: value.sourceFingerprint ?? null, startedAt: value.startedAt, finishedAt: value.finishedAt,
results: value.results.map(result => ({ ...result, logExcerpt: undefined,
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null,
...(result.engine === 'python' ? { pythonEvidence: pythonEvidence.get(result.id) ?? { verified: false, state: 'historical_or_not_passed' } } : {}) })) })),
verifiedCheckJobId: check?.id ?? null,
deliveries: jobs.map(value => ({ id: value.id, status: value.status, commit: value.commit ?? null, expectedCommit: value.expectedCommit ?? null,
parent: value.parent, sourceFingerprint: value.sourceFingerprint, paths: value.paths, summary: value.summary, requiresVerification: !!value.requiresVerification,
workspacePreserved: value.workspacePreserved ?? null, indexPreserved: value.indexPreserved ?? null, finishedAt: value.finishedAt })),
requiresVerification,
limitations: ['本切片验证已选工程检查和提交范围;业务需求验收另行记录。', '提交为本地普通提交,不执行仓库hooks和GPG签名。', '请求输入为本地UTF-8估算;服务实际分词和用量另行记录。', '未配置模型单价,费用未知。'],
};
const safe = JSON.parse(this.redact(JSON.stringify(report)));
const markdown = renderDeliveryMarkdown(safe);
const jsonArtifact = this.store.artifactStore.write(session, run, safe, { kind: 'delivery-report' });
const markdownArtifact = this.store.artifactStore.write(session, run, markdown, { kind: 'delivery-report-markdown', mediaType: 'text/markdown' });
this.store.core.artifact.set(jsonArtifact.id, jsonArtifact); this.store.core.artifact.set(markdownArtifact.id, markdownArtifact);
if (job) { job.reportArtifactId = jsonArtifact.id; job.reportMarkdownArtifactId = markdownArtifact.id; }
this.store.save(session, { type: 'delivery.report', detail: { status, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id } });
return { report: safe, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id };
}
}
export function renderDeliveryMarkdown(report) {
const lines = ['# 项目交付报告', '', '**' + report.statusLabel + '**', '', '生成时间:' + report.generatedAt, '',
'项目:' + report.project.name, '项目目录:' + report.project.root, 'Task:' + report.task.id, '',
'## 任务与范围', '', report.task.goal, '',
'源码指纹:' + report.source.fingerprint, '当前Git HEAD:' + (report.source.gitHead ?? '未启用'),
'分支:' + (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.requirements) {
lines.push('', '## 用户要求与证据', '', report.requirements.note, '', '复核状态:' + report.requirements.status,
'', '| 要求 / 条件 | 用户原文来源 | 修订 | 复核状态 | 原证据 / 下一步 |', '| --- | --- | --- | --- | --- |');
for (const item of report.requirements.items) lines.push('| ' + [item.title + ' / ' + item.criterion,
item.source.kind + ':' + item.source.id + ' [' + item.source.start + ',' + item.source.end + ') ' + item.source.quote,
item.revision, item.status, item.error ?? item.user_note ?? item.proof_artifact_id ?? (item.status === 'not_requested' ? '按约定未执行,非测试通过' : '选择实际证据或完成用户验收')].map(escapeCell).join(' | ') + ' |');
if (report.requirements.unreviewed_sources?.length) lines.push('', '尚未审阅的用户来源:' + report.requirements.unreviewed_sources.join('、'));
if (report.requirements.error) lines.push('', report.requirements.error);
}
if (report.turnObservations?.some(row => row.recorded || row.error)) {
lines.push('', '## 单轮观察(仅记录)', '', '外显事实分类不改变停止、权限或预算;不是自主交付收益证明。', '',
'| Run / 轮次 | 观察 | 新读取字符 | 重复读取 | 新失败 / 重复失败 | 原收据核对 |', '| --- | --- | --- | --- | --- | --- |');
for (const run of report.turnObservations) if (run.error) lines.push('', escapeCell(run.runId + ':' + (typeof run.error === 'string' ? run.error : '观察未能记录,原执行结果保留。')), '');
for (const run of report.turnObservations) for (const turn of run.turns) lines.push('| ' + [run.runId + ' / ' + (turn.stepIndex ?? turn.phase),
turn.classification, turn.delta.read_characters, turn.delta.repeated_reads, turn.delta.new_failures + ' / ' + turn.delta.repeated_failures,
run.evidence_verified ? '原字节已核对' : run.error].map(escapeCell).join(' | ') + ' |');
}
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
'| 步骤 / 通过条件 | 状态 | 前置依赖 | 原证据 |', '| --- | --- | --- | --- |');
for (const step of report.taskPlan.steps) lines.push('| ' + [step.title + ' / ' + step.criterion, step.status,
step.depends_on.join(', ') || '无', step.evidence?.id ?? '尚未核验'].map(escapeCell).join(' | ') + ' |', ...(step.error ? ['', step.error, ''] : []));
if (report.taskPlan.error) lines.push('', report.taskPlan.error);
lines.push('', '任务计划固定实际操作范围;业务语义验收另行记录。', '', '### 原计划与核验工件', '');
for (const plan of report.taskPlanHistory ?? []) lines.push('计划 ' + plan.revision + ':' + plan.contractArtifactId + ' · SHA256 ' + plan.contractSha256);
for (const proof of report.taskProofs ?? []) lines.push('步骤 ' + proof.stepKey + ' · ' + proof.status + ':' + proof.contractArtifactId + ' · SHA256 ' + proof.contractSha256);
}
if (report.workspace?.kind === 'managed-worktree') lines.push('', '## 独立开发工作区', '', '工作区:' + report.workspace.workspaceId,
'来源项目:' + report.workspace.sourceProjectId, '来源目录:' + report.workspace.sourceRoot,
'起始提交:' + report.workspace.baseCommit, '独立分支:' + report.workspace.branch,
'交付保存在此分支;合并回来源项目需要另行审查。');
if (report.changeSets?.length) {
lines.push('', '## 多文件变更集', '', '| 批次 | 实际状态 | 快照 | 审查指纹 |', '| --- | --- | --- | --- |');
for (const set of report.changeSets) lines.push('| ' + [set.id, set.status, set.snapshotVerified ? 'SHA256校验通过' : '需要核对', set.fingerprint].map(escapeCell).join(' | ') + ' |',
'', set.summary ?? '', '');
}
lines.push('', '## 实际检查', '', '| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |', '| --- | --- | --- | --- | --- |');
for (const job of report.checks) for (const result of job.results) lines.push('| ' + [job.id.slice(0, 8) + ' / ' + result.command,
job.stale ? '源码已变化 / ' + result.status : result.status, result.exitCode ?? '未知', result.tests ? result.tests.passed + '/' + result.tests.total : '不适用或未知', result.logSha256 ?? '未知'].map(escapeCell).join(' | ') + ' |');
const environments=report.checks.filter(job=>job.environment);
if(environments.length){
lines.push('','### 实际依赖环境','','| 检查记录 | Node / npm | 声明与运行时输入 | 实际依赖字节 | 准备记录 |','| --- | --- | --- | --- | --- |');
for(const job of environments)lines.push('| '+[job.id,job.environment.runtime.node.version+' / '+(job.environment.runtime.npm?.version??'未知'),job.environment.dependencyInputs,job.environment.installed.sha256??'没有依赖目录',job.environment.preparation?.jobId??'已有环境,无所属准备凭据'].map(escapeCell).join(' | ')+' |');
lines.push('','环境准备只记录安装;以上工程检查结果另行判定。');
}
const pythonResults = report.checks.flatMap(job => job.results.filter(result => result.python));
if (pythonResults.length) {
lines.push('', '### Python实际执行', '', '| 检查 | 解释器 | 版本 | 结构化结果SHA256 |', '| --- | --- | --- | --- |');
for (const result of pythonResults) lines.push('| ' + [result.command, result.python.runtime.executable, result.python.runtime.version, result.metricsSha256 ?? '未返回'].map(escapeCell).join(' | ') + ' |',
'', '运行器SHA256:' + result.python.runner.sha256, '封存输入SHA256:' + result.python.inputSha256,
...(result.compilation ? ['语法编译:' + result.compilation.compiled + '/' + result.compilation.total + ' 个源码文件。'] : []));
}
if (report.browserChecks?.length || report.browserVerification?.required) {
lines.push('', '## 实际页面验收', '', '当前页面验收:' + report.browserVerification.status, '', '| 浏览器Job | 状态 | 实际断言 | 原结果SHA256 |', '| --- | --- | --- | --- |');
for (const check of report.browserChecks ?? []) {
lines.push('| ' + [check.id, check.status, check.assertions.passed + '/' + check.assertions.total, check.evidenceVerified ? check.resultSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
for (const image of check.screenshots) lines.push('', '截图 ' + image.label + ' · ' + image.width + '×' + image.height + ' · SHA256 ' + image.sha256);
}
lines.push('', '浏览器页面属于工程输入;观察或截图不代替断言,源码或构建变化后需要重新检查。', '');
}
lines.push('', '## Git交付', '');
if (report.deliveryReview) lines.push('Git提交预览已保存,等待确认。计划:' + report.deliveryReview.planId, '');
if (!report.deliveries.length) lines.push('尚无内置Git提交记录。');
for (const delivery of report.deliveries) lines.push('- ' + delivery.status + ' · ' + (delivery.commit ?? '实际结果未确认') + ' · ' + delivery.paths.join(', '),
' ' + (delivery.summary ?? ''));
lines.push('', '## 模型与用量', '', 'Run型号为启动配置;每次实际发送与返回型号见下表。型号标识或登记映射不认证底层模型权重。', '', '| Run | 启动型号 | 状态 | 已报告tokens |', '| --- | --- | --- | --- |');
for (const run of report.runs) lines.push('| ' + [run.id, run.model?.mode === 'demo' ? '离线固定演示' : run.model?.model ?? '未记录',
run.status, run.usage?.totalTokens ?? 0].map(escapeCell).join(' | ') + ' |');
lines.push('', '| 尝试 | 请求型号 | 上游报告型号 | 核对结果 | 原响应 SHA256 |', '| --- | --- | --- | --- | --- |');
for (const run of report.runs) {
for (const receipt of run.consumption ?? []) {
const identity = receipt.modelIdentity;
lines.push('| ' + [receipt.attemptId, identity?.requestedModel ?? receipt.model ?? '未记录', identity?.reportedModels?.join(', ') || '未记录',
modelIdentityLabel(identity), identity?.responseSource?.sha256 ?? '未记录'].map(escapeCell).join(' | ') + ' |');
if (identity?.mapping) lines.push('', '用户登记的映射依据:' + escapeCell(identity.mapping.source));
}
if (!run.consumption?.length && run.usage?.requests) lines.push('', 'Run ' + run.id + ' 的历史记录未保存返回型号核对,不能从启动配置补推。');
}
lines.push('', '累计已报告:' + (report.usage.totalTokens ?? 0) + ' tokens;未报告请求:' + (report.usage.unknownRequests ?? 0) + '。费用:未知。', '', '## 尚待确认', '');
if (report.contextPlans?.length) {
const at = lines.length - 2;
const contextLines = ['', '## 请求上下文', '', '| 请求 | 状态 | 输入估算 | 已报告输入 | 省略组 | 正文SHA256校验 |', '| --- | --- | --- | --- | --- | --- |'];
for (const plan of report.contextPlans) contextLines.push('| ' + [plan.id, plan.status, plan.estimatedInputTokens,
plan.actualUsage?.prompt_tokens ?? '未返回', plan.archivedGroups, plan.evidenceVerified ? plan.requestSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
lines.splice(at, 0, ...contextLines, '');
}
for (const value of report.requiresVerification) lines.push('- ' + value.tool + ' · ' + value.id + ' · ' + value.status);
for (const note of report.limitations) lines.push('- ' + note);
return lines.join('\n') + '\n';
}
@@ -0,0 +1,952 @@
import { approvalPresentation } from '../shared/approval-presentation.mjs';
import { PreviewManager } from '../core/preview/preview-manager.mjs';
import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs';
import { BrowsingManager } from '../core/browser/browsing-manager.mjs';
import { browsingToolDefinitions, browsingAction } from '../shared/contracts/browsing.mjs';
import { publicEnvironmentDiagnostic } from '../core/environment/environment-manager.mjs';
import { EnvironmentManager } from '../core/environment/environment-manager.mjs';
import { spawn, execFile } from 'node:child_process';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { sanitizeModelText } from '../core/models/upstream-error.mjs';
import { StringDecoder } from 'node:string_decoder';
import { setImmediate as yieldExecution } from 'node:timers/promises';
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions, browserToolDefinitions } from './provider.mjs';
import { now, repairToolPairs } from './store.mjs';
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
import { tokenBudgetState,checkModelDispatchBudget } from '../shared/contracts/model-reservation.mjs';
import { taskToolAllowed, taskContract } from '../shared/contracts/task-control.mjs';
import { CheckRunner } from '../core/check-runner.mjs';
import { inspectProject } from '../core/project-inspector.mjs';
import { projectEnvironment } from '../core/process-environment.mjs';
import { GitDelivery } from '../core/git-delivery.mjs';
import { ProjectIndex } from '../core/context/project-index.mjs';
import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan.mjs';
import { ENGINE_SEED_RESERVATION } from '../shared/contracts/engine-context.mjs';
import { InputAttachments } from '../core/context/input-attachments.mjs';
import { BudgetResume } from '../core/context/budget-resume.mjs';
import { artifactPage, filePage, readMessageBudget, readBatchBudget, spendReadBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, recordUnchangedAction, readCoverageContext, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { taskDeliveryProgress } from '../core/context/delivery-progress.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
import { WorkspaceManager, verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../shared/contracts/workspaces.mjs';
import { ResearchManager } from '../core/research-manager.mjs';
import { EngineManager } from '../core/engine-manager.mjs';
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 { RequirementReview } from '../core/tasks/requirement-review.mjs';
import { recordTurnProgress } from '../core/context/turn-progress-recorder.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';
import { TaskCheckpointManager } from '../core/tasks/task-checkpoint-manager.mjs';
import { SkillRegistry, skillToolDefinitions, skillReadInput } from '../core/skills/skill-registry.mjs';
import { McpRegistry } from '../core/tools/mcp-registry.mjs';
import { mcpToolDefinitions, mcpCallInput, assertMcpResolved } from '../core/tools/mcp-contract.mjs';
import { WorkerManager } from '../core/tasks/worker-manager.mjs';
import { EvaluationManager } from '../core/evaluation/evaluation-manager.mjs';
import { WORKER_TOOLS, COLLABORATION_CLOSED, workerForSession, assertWorkerTool, assertWorkersResolved, workerUsage, workerConflict } from '../shared/contracts/workers.mjs';
const workerAuthority = Symbol('internal-worker-start');
const labels = { diagnose_environment:'诊断工程环境',plan_environment:'准备依赖计划',prepare_environment:'执行依赖准备',inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
labels.prepare_change_set = '准备多文件变更集';
labels.list_research_targets = '查看本任务登记工件';
labels.analyze_research_target = 'REA静态分析登记工件';
labels.read_research_evidence = '读取原REA Evidence字段';
labels.inspect_engine_checks = '查看本任务外部引擎核验';
labels.plan_browser = '准备页面检查计划';
labels.run_browser = '运行实际浏览器检查';
labels.read_browser_result = '读取原页面执行结果';
labels.inspect_browser_tabs = '核对本任务浏览标签页';
labels.observe_browser_tab = '观察所属浏览页面';
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工具';
export function validateToolArgs(tool, args) {
if (!Object.hasOwn(labels, tool)) throw new Error('当前能力表没有工具:' + tool);
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('工具参数必须是 JSON 对象。');
if (tool === '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; }
if (['observe_browser_tab','act_browser_tab'].includes(tool)) { const {tab_id,...input}=args; if(typeof tab_id!=='string')throw new Error('需要当前Task的标签页ID。'); if(tool==='act_browser_tab')browsingAction(input); else if(Object.keys(input).length)throw new Error('观察不接受脚本或附加参数。'); return; }
if (tool === 'plan_browser') { browserPlanInput(args); return; }
if (['run_browser', 'read_browser_result'].includes(tool)) {
const key = tool === 'run_browser' ? 'plan_id' : 'browser_job_id';
if (typeof args[key] !== 'string' || Object.keys(args).some(field => ![key, ...(tool === 'read_browser_result' ? ['section', 'offset', 'limit'] : [])].includes(field))) throw new Error('浏览器工具需要所属计划或结果ID,不能添加执行脚本。');
if (args.section !== undefined && !['page', 'steps', 'console', 'requests', 'overview'].includes(args.section)) throw new Error('浏览器原结果字段无效。');
for (const field of ['offset', 'limit']) if (args[field] !== undefined && (!Number.isSafeInteger(args[field]) || args[field] < (field === 'limit' ? 1 : 0) || field === 'limit' && args[field] > 16000)) throw new Error('浏览器结果分页范围无效。');
return;
}
if (tool === 'inspect_engine_checks') {
if (Object.keys(args).length) throw new Error('引擎核验查询只读取当前任务的已保存结果。');
return;
}
if (['list_research_targets', 'analyze_research_target', 'read_research_evidence'].includes(tool)) {
if (tool === 'analyze_research_target' && (typeof args.target_id !== 'string' || !['javascript', 'pe-imports', 'pe-resources'].includes(args.operation))) throw new Error('REA分析需要登记target_id和实际支持的静态分析方式。');
if (tool === 'read_research_evidence' && (typeof args.research_job_id !== 'string' || args.pointer !== undefined && typeof args.pointer !== 'string')) throw new Error('Evidence读取需要research_job_id及有效字段。');
if (args.refresh !== undefined || args.path !== undefined) throw new Error('模型只能使用已登记工件,重新分析由用户发起。');
for (const field of ['offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < (field === 'limit' ? 1 : 0) || field === 'limit' && args[field] > 16000)) throw new Error('Evidence分页范围无效。');
if (args.pointer !== undefined && args.pointer.length > 400) throw new Error('Evidence字段超过400字符。');
return;
}
if (tool === 'prepare_change_set') {
if (!Array.isArray(args.change_ids) || !args.change_ids.length || args.change_ids.length > 32
|| args.change_ids.some(id => typeof id !== 'string' || !/^[a-f0-9-]{36}$/i.test(id))
|| new Set(args.change_ids).size !== args.change_ids.length) throw new Error('变更集需要1到32个不同的提案ID。');
return;
}
const required = ['diagnose_environment','plan_environment','inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'prepare_environment' ? ['plan_id','fingerprint'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
: tool === 'propose_patch' ? ['path', 'base_sha256', 'reason'] : tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
for (const field of ['depth', 'start_line', 'end_line', 'offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < 0)) throw new Error('工具参数 ' + field + ' 必须是非负整数。');
if (tool === 'read_file' && args.limit !== undefined && (args.limit < 1 || args.limit > 16000)) throw new Error('文件分页limit需要1到16000个字符。');
if (tool === 'read_file' && args.expected_sha256 !== undefined && (typeof args.expected_sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(args.expected_sha256))) throw new Error('文件续读expected_sha256需要64位SHA256。');
if (args.case_sensitive !== undefined && typeof args.case_sensitive !== 'boolean') throw new Error('case_sensitive 必须是布尔值。');
if (tool === 'plan_checks' && args.names !== undefined && (!Array.isArray(args.names) || args.names.some(name => typeof name !== 'string'))) throw new Error('检查脚本名称需要文本数组。');
if (tool === 'plan_delivery' && args.message !== undefined && typeof args.message !== 'string') throw new Error('提交说明需要文本。');
if (tool === 'query_code' && (args.kind !== undefined && !['all', 'symbols', 'imports', 'files'].includes(args.kind) || args.query.length > 200)) throw new Error('索引查询类型无效或查询超过200字。');
if (tool === 'propose_patch' && (!/^[a-f0-9]{64}$/i.test(args.base_sha256) || !Array.isArray(args.edits) || !args.edits.length || args.edits.length > 32)) throw new Error('精确补丁需要有效SHA256和1到32个替换。');
}
export class Runtime {
constructor(store, provider, { appDirectory } = {}) {
this.store = store; this.provider = provider;
this.appDirectory = appDirectory;
this.active = new Map(); this.waiters = new Map();
}
isActive(id) { return !!this.browsing?.isActive(id) || !!this.previews?.isActive(id) || !!this.environments?.isActive(id) || !!this.evaluations?.isActive(id) || this.active.has(id) || !!this.workers?.isActive(id) || !!this.controlledEngines?.isActive(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id) || !!this.research?.isActive(id) || !!this.engines?.isActive(id) || !!this.browser?.isActive(id) || !!this.taskPlans?.isActive(id); }
hasActivity() { return (this.provider.hub?.networkChecks?.active.size ?? 0) > 0 || (this.browsing?.active.size ?? 0) > 0 || (this.previews?.active.size ?? 0) > 0 || (this.environments?.active.size ?? 0) > 0 || (this.evaluations?.active.size ?? 0) > 0 || (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.workers?.active.size ?? 0) > 0 || (this.controlledEngines?.drivers.size ?? 0) > 0 || (this.mcp?.active.size ?? 0) > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; }
evaluationManager() { return this.evaluations ??= new EvaluationManager(this.store, this); }
workerManager() { return this.workers ??= new WorkerManager(this.store, this); }
projectIndexer() { return this.codeIndex ??= new ProjectIndex({ cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') }); }
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 });
await this.requirementReview().assertReady(session);
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' });
}
requirementReview() { return new RequirementReview(this.store, { planner: this.taskPlanner(), redact: value => this.provider.redact(value) }); }
taskPlanner() { return this.taskPlans ??= new TaskPlanManager(this.store, { redact: value => this.provider.redact(value),
projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
browserManager() { return this.browser ??= new BrowserManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
previewManager() { return this.previews ??= new PreviewManager(this.store, { runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) }); }
localFilePreviews() { return this.filePreviews ??= new LocalFilePreviews(this.store); }
browsingManager() { return this.browsing ??= new BrowsingManager(this.store, { redact: value => this.provider.redact(value), workbenchOrigin: this.workbenchOrigin }); }
engineManager() {
return this.engines ??= new EngineManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) });
}
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
inputAttachments() { return this.inputs ??= new InputAttachments(this.store,{busy:projectId=>this.projectHasActivity(projectId)}); }
budgetResumes(){return this.resumes??=new BudgetResume(this.store,this.provider,this);}
resumeBudget(id,input){const session=this.store.session(id),plan=this.budgetResumes().verify(session,input);return this.start(id,'',true,{resumePlan:plan});}
engineRunner() { return this.controlledEngines ??= new EngineRunner(this.store, this.provider, { appDirectory: this.appDirectory }); }
memoryManager() { return this.projectMemories ??= new ProjectMemoryManager(this.store); }
checkpointManager() { return this.taskCheckpoints ??= new TaskCheckpointManager(this.store, {
taskPlans: this.taskPlanner(), redact: value => this.provider.redact(value) }); }
skillRegistry() { return this.skills ??= new SkillRegistry(this.store, {
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) }); }
mcpRegistry() { return this.mcp ??= new McpRegistry(this.store, { taskPlans: this.taskPlanner(),
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
researchManager() {
return this.research ??= new ResearchManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) });
}
projectHasActivity(projectId, exceptSessionId = null, { excludeGroupId = null, excludeEvaluationId = null } = {}) {
return !!this.previews?.projectActive(projectId) || !!this.environments?.projectActive(projectId) || !!this.evaluations?.projectActive(projectId, excludeEvaluationId) || !!this.workers?.projectActive(projectId, excludeGroupId) || !!this.controlledEngines?.projectActive(projectId, exceptSessionId) || [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.environments?.projectActive(projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId);
}
workspaceManager() {
return this.workspaces ??= new WorkspaceManager(this.store, { initialize: this.store.core.workspace.size === 0,
redact: value => this.provider.redact(value), projectBusy: projectId =>
!!this.previews?.projectLive(projectId) || !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId) || [...this.active.values()].some(run => run.project.id === projectId) || !!this.environments?.projectActive(projectId) || !!this.checks?.projectActive(projectId)
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
changeSetManager() {
return this.changeSets ??= new ChangeSetManager(this.store, { beforeApply: (session, set) => this.workerManager().verifyMerge(session, set), projectBusy: (projectId, exceptId) =>
!!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId, exceptId) || [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId)
|| !!this.environments?.projectActive(projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
environmentManager() {
return this.environments ??= new EnvironmentManager(this.store, { runtimeDirectory: this.appDirectory ? path.join(this.appDirectory,'runtime') : null,
redact: value => this.provider.redact(value), projectBusy: (projectId,exceptId) => this.projectHasActivity(projectId,exceptId) });
}
checkRunner() {
return this.checks ??= new CheckRunner(this.store, { redact: value => this.provider.redact(value), runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
pythonRunnerPath: path.join(this.appDirectory ?? process.cwd(), 'scripts', 'python-check-runner.py'),
projectBusy: (projectId, exceptId) => !!this.environments?.projectActive(projectId) || !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId, exceptId) || [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
gitDelivery() {
return this.deliveries ??= new GitDelivery(this.store, { redact: value => this.provider.redact(value),
projectBusy: (projectId, exceptId) => !!this.evaluations?.projectActive(projectId) || !!this.workers?.projectActive(projectId) || !!this.controlledEngines?.projectActive(projectId, exceptId) || [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.environments?.projectActive(projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.projectActive(projectId) || !!this.browser?.projectActive(projectId) || !!this.taskPlans?.projectActive(projectId) });
}
startWorker(session, worker, config) {
if (workerForSession(this.store, session) !== worker || !this.workers?.active.has(worker.collaborationId)
|| this.store.core.collaboration.get(worker.collaborationId)?.status !== 'running') throw workerConflict('子任务只能由所属父协作启动。');
return this.start(session.id, worker.goal, true, { workerAuthorization: workerAuthority, worker, workerConfig: config });
}
start(id, content, resume = false, { instructionSource = null, workerAuthorization = null, worker = null, workerConfig = null, attachmentIds=[],resumePlan=null } = {}) {
if (this.provider.hub?.networkChecks?.active.size) throw Object.assign(new Error('连接诊断正在执行,请等待结束或在模型中心停止诊断,再开始任务。'), { status: 409 });
const session = this.store.session(id);
assertWorkersResolved(this.store, session.projectId);
const boundWorker = workerForSession(this.store, session);
if (workerAuthorization !== null && workerAuthorization !== workerAuthority || workerConfig && workerAuthorization !== workerAuthority
|| boundWorker && (workerAuthorization !== workerAuthority || boundWorker !== worker)) throw workerConflict('受限子任务请在父协作中开始或继续,不能替换目标或配置。');
if (!boundWorker && [...this.store.core.evaluation.values()].some(batch => batch.projectId === session.projectId && !['completed', 'retained'].includes(batch.status))) throw workerConflict('工程已有未收尾评测,请在评测中处理原样本或保留现场结束。');
if (!boundWorker && [...this.store.core.collaboration.values()].some(group => group.projectId === session.projectId && !COLLABORATION_CLOSED.has(group.status))) throw workerConflict('项目已有未收尾父协作,请先处理子任务和合并审查,再发送新目标。');
assertMcpResolved(this.store, session.projectId);
if (pendingDeliveryReview(this.store, session)) throw Object.assign(new Error('当前任务已有待确认的Git交付预览。请在任务记录中审查并确认提交,或撤回预览后继续。'), { status: 409 });
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
if (this.isActive(id) || this.projectHasActivity(session.projectId)) throw Object.assign(new Error('这个项目已有任务、检查或Git交付在执行。'), { status: 409 });
if ([...this.store.core.delivery_job.values()].some(job => job.projectId === session.projectId && job.requiresVerification)) throw Object.assign(new Error('项目有结果未知的Git交付,请先在所属任务中核对提交结果。'), { status: 409 });
if (!resume && (typeof content !== 'string' || !content.trim() || content.length > 20000)) throw new Error('任务内容不能为空,也不能超过 20,000 字符。');
const project = this.store.project(session.projectId);
const attachments=this.inputAttachments().validateSelection(session,attachmentIds);
if(attachments.length&&this.store.core.task.get(session.taskId)?.attachmentIds?.length&&!['completed','idle'].includes(this.store.core.task.get(session.taskId).status))throw Object.assign(new Error('当前任务已有截图,请新建任务再添加。'),{status:409});
safePath(project);
const controller = new AbortController();
const initialConfig = structuredClone(resumePlan?.config ?? workerConfig ?? this.store.config);
const config = resumePlan || workerConfig ? initialConfig : this.provider.prepareConfig ? this.provider.prepareConfig(initialConfig, this.store) : initialConfig;
if (config.mode !== 'demo') this.provider.validate(config);
if (attachments.length && config.mode==='demo') throw Object.assign(new Error('演示执行器不会读取图片,请先选择支持视觉的模型连接。'),{status:409});
if (attachments.length && !config.modelRouting) throw Object.assign(new Error('请在模型中心添加并声明支持视觉的连接,再发送图片。'),{status:409});
const record = this.store.beginRun(session, content, resume, config, { instructionSource, inputAttachments:attachments,resumePlan });
const run = { controller, id: record.id, taskId: record.taskId, project, record, config, ...(worker ? { worker } : {}) };
this.active.set(id, run);
session.status = 'running'; session.recoveryNotice = null; session.executionMode = config.mode;
session.runId = run.id;
if (session.title === '新任务') session.title = String(content).replace(/\s+/g, ' ').slice(0, 28);
if (!resume || content) {
const userMessage=this.store.message(session, 'user', String(content));
if(attachments.length)userMessage.attachmentIds=attachments.map(row=>row.boundAttachmentId);
session.providerMessages.push({ role: 'user', content: String(content) });
}
if (resume) this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
session.failure = null;
this.store.save(session);
const deadline = record.budget.maxDurationMs > 0 ? setTimeout(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs) : null;
run.promise = this.run(session, config, run).finally(() => {
clearTimeout(deadline);
try {
const status = session.status;
if (record.purpose === 'diagnostic') session.status = record.taskStatusBefore;
this.store.finishRun(session, record, run.stopReason ?? null, { status });
} finally { this.active.delete(id); }
});
run.promise.catch(() => {});
return session;
}
async capturePauseInputs(run) {
if (!run.worker && run.record.purpose !== 'diagnostic' && ['no_progress', 'step_limit'].includes(run.stopReason)) {
try { run.record.finalSourceFingerprint = (await inspectProject(run.project)).sourceFingerprint; } catch { /* No fingerprint means no claim of unchanged inputs. */ }
}
}
resume(id, content) {
const session = this.store.session(id);
if (content) return this.start(id, content);
if (session.status === 'needs_review') throw Object.assign(new Error(pendingDeliveryReview(this.store, session)
? '请在任务记录中确认或撤回已有Git预览,再继续任务。' : '请先审查待处理改动;继续请求模型不能代替文件审核。'), { status: 409 });
if (!['failed', 'paused'].includes(session.status)) throw Object.assign(new Error('当前任务已经结束。可以发送新的任务,或查看待审查改动。'), { status: 409 });
return this.start(id, '', true);
}
continueReviewed(id) {
const session = this.store.session(id), run = this.store.core.run.get(session.runId), task = this.store.core.task.get(session.taskId);
if (this.isActive(id) || this.checks?.projectActive(session.projectId)) throw Object.assign(new Error('请等待正在执行的任务或检查结束。'), { status: 409 });
const stoppedForReview = run?.status === 'needs_review' || run?.status === 'paused' && run.stopReason === 'step_limit';
if (!task || run?.taskId !== task.id || !stoppedForReview || pendingDeliveryReview(this.store, session) || session.changes.some(change => ['pending', 'conflict'].includes(change.status))
|| [...this.store.core.tool.values()].some(tool => tool.taskId === task.id && tool.requiresVerification)
|| !session.changes.some(change => change.status === 'applied' && (!change.taskId || change.taskId === task.id))) throw Object.assign(new Error('当前没有已审查并应用、需要继续交付的任务改动。'), { status: 409 });
if (taskContract(task).checks === 'skip' && task.delivery?.status === 'files_applied') throw Object.assign(new Error('文件已按原要求应用完成,无需自动检查;如需追加工作,请明确发送新的要求。'), { status: 409 });
const result = this.start(id, '', true, { instructionSource: 'review-action' });
this.store.message(session, 'system', '审查操作:改动已应用,继续核对原目标。原有范围与限制保留,此操作没有追加测试要求。');
return result;
}
async run(session, config, run) {
const signal = run.controller.signal;
let projectionLogged = false;
let currentStep = null;
try {
// Immediate providers and local tools still need to deliver UI events and
// process stop/deadline input between completed, persisted operations.
await yieldExecution(undefined, { signal });
await verifyWorkspaceProject(this.store, run.project);
const originalTask = this.store.core.task.get(run.taskId);
if (!run.worker && run.record.purpose !== 'diagnostic' && originalTask.stagnation?.count >= 2) {
const current = await inspectProject(run.project);
if (current.sourceFingerprint === originalTask.stagnation.sourceFingerprint) throw new BudgetExceeded('no_progress', '连续两次运行未增加源码改动、检查结果或新的读取依据。本次未请求模型;请根据原日志修改源码或发送具体调整,避免重复空续接。');
originalTask.stagnation = null;
}
recordTurnProgress(this.store, session, run.record, null, 'baseline');
for (let step = 0; step < config.maxSteps; step++) {
signal.throwIfAborted();
checkBudget(run.record, this.store.core.task.get(run.taskId));
const stepRecord = this.store.beginStep(session, run.record);
currentStep = stepRecord;
const task = this.store.core.task.get(run.taskId);
config.inputImages=this.inputAttachments().images(session,task);
if(config.inputImages.length&&config.mode==='demo')throw new Error('固定演示执行器不会读取图片;请连接并声明支持视觉的模型。');
const taskPlan = task.currentTaskPlanId ? await this.taskPlanner().inspect(session, { candidates: false }) : null;
const requirementReview = task.requirementRevisions?.length ? await this.requirementReview().inspect(session) : null;
const deliveryProgress = await taskDeliveryProgress(this.store, session, run.record, { checks: this.checkRunner(), worker: !!run.worker, taskPlan });
const readCoverage = readCoverageContext(task, run.id);
const state = session.changes.filter(change => change.taskId === task.id || ['pending', 'conflict'].includes(change.status))
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
.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);
// Keep the complete goal once in this request view. The stored contract
// still contains its original goal for intent and evidence verification.
const { goal, ...contract } = taskContract(task);
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提交、外部工具或嵌套协作。',
}) : '') + '\n当前项目/会话/任务身份:' + JSON.stringify({
project_id: run.project.id, session_id: session.id, task_id: task.id, workspace: projectWorkspaceIdentity(run.project) }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
goal, instructions: task.instructions.filter(instruction => instruction.source !== 'review-action'), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract,
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question : '')
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ (deliveryProgress ? '\n当前工程执行依据(每次请求重新核对,非操作授权):\n' + JSON.stringify(deliveryProgress) : '')
+ (requirementReview ? '\n用户逐项要求复核(任务数据,不授权额外操作;证据和用户确认分别记录):\n' + JSON.stringify({
revision: requirementReview.revision, status: requirementReview.status, unreviewed_sources: requirementReview.unreviewed_sources,
error: requirementReview.error, items: requirementReview.items.map(item => ({ key: item.key, revision: item.revision, title: item.title,
criterion: item.criterion, method: item.method, kind: item.kind, paths: item.paths, tools: item.tools, checks: item.checks,
status: item.status, error: item.error, proof_id: item.proof_id })) }) : '')
+ (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), { taskPlanIncluded: !!taskPlan, executionFactsIncluded: !!deliveryProgress })
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '')
+ (readCoverage ? '\n本次Run实际返回的已读区间(读取事实,非新指令):\n' + JSON.stringify(readCoverage) : '')
+ (taskPlan ? '\n当前Task依赖计划与尚未核验的原步骤(任务数据,不授权额外操作):\n' + JSON.stringify({
plan_id: taskPlan.plan_id, revision: taskPlan.revision, status: taskPlan.status, contract_artifact_id: taskPlan.contract_artifact_id,
remaining_steps: taskPlan.remaining_steps, error: taskPlan.error,
steps: taskPlan.steps.map(({ candidates, evidence, ...step }) => ({ ...step, evidence_id: evidence?.id ?? null })),
}) : ''));
const skillCatalog = run.worker ? null : this.skillRegistry().catalog(session.projectId);
const mcpCatalog = run.worker ? null : this.mcpRegistry().catalog(session.projectId);
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 : []),
...(this.browserManager().builds(run.project).length || [...this.store.core.browser_plan.values()].some(plan => plan.sessionId === session.id && plan.taskId === run.taskId) ? browserToolDefinitions : [])];
const tools = availableTools.filter(tool => (!run.worker || WORKER_TOOLS.has(tool.function.name)) && taskToolAllowed(task, run.record, tool.function.name));
const projectMemory = await this.memoryManager().context(session, { redact: value => this.provider.redact(value) });
signal.throwIfAborted();
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
transportReservationTokens:run.worker?.engine?ENGINE_SEED_RESERVATION:0,engineStepOnly:!!run.worker?.engine });
if (planned.record.archivedGroups && !projectionLogged) {
projectionLogged = true; session.compactions++;
this.store.event(session, { kind: 'context', label: '整理请求上下文', phase: 'completed', contextPlanId: planned.record.id,
output: '完整请求输入估算 ' + planned.record.beforeInputTokens + ' → ' + planned.record.estimatedInputTokens +
' tokens;省略 ' + planned.record.archivedGroups + ' 个完整消息组,原历史和参数已保存为SHA256工件。估算与服务实际用量分别记录。' });
}
let requestEvent;
const externalEngine = !!run.worker?.engine;
if (externalEngine) { planned.record.engineStepOnly = true; planned.record.engine = 'deepseek-workbench'; }
let response, requestStarted = false, responseAccounted = externalEngine;
try {
signal.throwIfAborted(); checkBudget(run.record, task);
if (run.worker && !externalEngine) { planned.record.workerDispatchedAt = now(); this.store.save(session, { type: 'worker.request_intent' }); }
requestStarted = true;
const progressHandler = progress => {
if (progress.consumption) {
this.store.recordConsumption(session, run.record, { ...progress.consumption, requestId: planned.record.id }, planned.record.tokenReservation?.reservedTokens??planned.record.estimatedInputTokens + config.maxOutputTokens);
responseAccounted = true;
if (run.worker) { planned.record.workerUsageAccounted = true; this.store.save(session); }
return;
}
if (progress.responseCapture !== undefined || progress.streamCapture !== undefined) {
const raw = progress.responseCapture ?? progress.streamCapture;
const decoded = raw.toString('utf8'), redacted = sanitizeModelText(decoded, value => this.provider.redact(value));
const captured = redacted === decoded ? raw : Buffer.from(redacted, 'utf8');
const artifact = this.store.artifactStore.write(session, run.record, captured, { kind: progress.streamCapture !== undefined ? 'model-stream-response' : 'model-http-response', mediaType: 'text/plain' });
this.store.core.artifact.set(artifact.id, artifact);
if (progress.modelIdentity) progress.modelIdentity.responseSource = { artifactId: artifact.id, sha256: artifact.sha256, sessionId: session.id,
scope: progress.streamCapture !== undefined ? 'sse-stream' : 'http-body' };
if (progress.upstream) Object.assign(progress.upstream, { artifactId: artifact.id, artifactSha256: artifact.sha256,
artifactScope: progress.streamCapture !== undefined ? 'sse-stream' : 'http-body', sessionId: session.id });
if (progress.upstream?.capture) Object.assign(progress.upstream.capture, { retention: 'artifact', storedBytes: artifact.bytes });
this.store.save(session); return;
}
if (!requestEvent) requestEvent = this.store.event(session, { kind: externalEngine ? 'engine' : 'model', runId: run.id,
source: externalEngine ? 'controlled_engine' : 'model_connection', label: externalEngine ? '受控引擎执行' : '请求模型服务', phase: 'running', startedAt: now(), contextPlanId: planned.record.id });
if (progress.engineRunId) requestEvent.engineRunId = progress.engineRunId;
planned.record.status = progress.phase === 'running' || progress.phase === 'retrying' ? 'requesting' : planned.record.status;
planned.record.requestAttempts = Math.max(planned.record.requestAttempts, progress.attempt ?? 0);
stepRecord.modelAttempts = Math.max(stepRecord.modelAttempts, progress.attempt ?? 0);
requestEvent.phase = progress.phase; requestEvent.attempts = progress.attempt;
if (progress.streaming) requestEvent.stream = { status: 'receiving', protocol: progress.protocol, sequence: progress.streamSequence,
bytes: progress.streamBytes, textCharacters: progress.textCharacters, textPreview: this.provider.redact(progress.textPreview ?? '').slice(0, 8000), toolFragments: progress.toolFragments };
if (progress.stream) requestEvent.stream = { ...requestEvent.stream, ...progress.stream, status: progress.stream.terminal ? 'completed' : 'receiving' };
if (progress.phase === 'failed' && requestEvent.stream) requestEvent.stream.status = 'incomplete';
if (progress.connectionId) { requestEvent.connectionId = progress.connectionId; requestEvent.modelAttemptId = progress.modelAttemptId; requestEvent.actualModel = progress.model; }
if (progress.modelIdentity) requestEvent.modelIdentity = progress.modelIdentity;
requestEvent.label = progress.switching ? '正在切换模型池连接' : progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务';
if (externalEngine) requestEvent.label = progress.phase === 'completed' ? '引擎原结果已收到' : '受控引擎执行';
requestEvent.output = progress.phase === 'retrying' ? '第 ' + progress.attempt + ' 次请求失败,将自动重试(最多 ' + progress.maxAttempts + ' 次)。'
: progress.phase === 'completed' ? '模型响应已收到;工具请求将在校验后执行。'
: progress.streaming ? '正在接收模型输出,工具参数完整核对前不会执行。' : progress.diagnostic?.message ?? '正在等待模型响应。';
if (externalEngine) requestEvent.output = progress.phase === 'completed' ? '原引擎工具请求或最终输出已返回,后续按所属任务核验。' : '等待所属引擎;实际模型尝试另有记录。';
if (progress.diagnostic) requestEvent.diagnostic = progress.diagnostic;
if (progress.durationMs !== undefined) requestEvent.durationMs = progress.durationMs;
if (['completed', 'failed'].includes(progress.phase)) requestEvent.finishedAt = now();
this.store.save(session);
};
const requestConfig=config.modelRouting&&!externalEngine?{...config,modelRouting:{...config.modelRouting,maxAttempts:Math.min(config.modelRouting.maxAttempts,planned.record.maxBudgetAttempts)}}:config;
response = externalEngine
? await this.engineRunner().complete(session, run, planned.messages, progressHandler, planned.record, tools)
: await this.provider.complete(requestConfig, planned.messages, run.project, signal, progressHandler, planned.record, tools,
{maxBudgetAttempts:planned.record.maxBudgetAttempts,beforeDispatch:({previousFailure}={})=>checkModelDispatchBudget(this.store,session,run.record,requestConfig,planned.body,0,previousFailure)});
if (response.compatibility?.length && requestEvent) { requestEvent.compatibility = response.compatibility; this.store.save(session); }
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
if (run.worker && !externalEngine && !responseAccounted) {
this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(response.message), 'utf8') / 3) + 8);
planned.record.workerUsageAccounted = true; this.store.save(session); responseAccounted = true;
}
} catch (error) {
if (requestEvent?.stream && requestEvent.stream.status !== 'completed') { requestEvent.stream.status = signal.aborted ? 'interrupted' : 'incomplete'; requestEvent.phase = signal.aborted ? 'interrupted' : 'failed'; requestEvent.finishedAt = now(); }
this.requestPlanner().finish(session, planned.record, { error: Object.assign(new Error(this.provider.redact(error.message ?? String(error))), { name: signal.aborted ? 'AbortError' : error.name }), attempts: planned.record.requestAttempts });
if (run.worker && requestStarted && !responseAccounted) {
this.store.recordResponse(session, run.record, null, planned.record.tokenReservation?.reservedTokens??planned.record.estimatedInputTokens + config.maxOutputTokens);
planned.record.workerUsageAccounted = true;
this.store.save(session, { type: 'worker.request_usage_unknown' });
}
try { checkBudget(run.record,task); }
catch(budget){
if(error.diagnostic?.kind==='model_identity') { error.diagnostic.budgetStopReason=budget.reason; throw error; }
if(budget instanceof BudgetExceeded&&error.diagnostic)budget.contextBudget={modelFailure:structuredClone(error.diagnostic)};
throw budget;
}
throw error;
}
signal.throwIfAborted();
if (run.worker) checkBudget(run.record, task);
const message = response.message;
const calls = message.tool_calls ?? [];
if (run.worker && (calls.length > 16 || workerUsage(this.store, run.worker).toolCalls + calls.length > run.worker.budget.maxToolCalls)) throw new BudgetExceeded('worker_tool_limit', '子任务工具次数超出固定累计预算或单次16项上限;这批工具未执行,原响应和用量已保存。');
run.readMessageBytes = readMessageBudget(planned.record, message);
run.readBatchBudget = readBatchBudget(planned.record, message);
run.readPageCharacters = planned.record.budget.inputBudget - planned.record.nextReadFixedInputTokens
- (planned.record.workingRetentionTokens ?? 0) < 4096 ? 2000 : Infinity;
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
if (new Set(calls.map(call => call.id)).size !== calls.length || calls.some(call => previousIds.has(call.id))) throw new Error('模型返回了重复的工具调用 ID,请重新发送任务。');
session.providerMessages.push(message);
if (!responseAccounted) this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8);
for (const call of calls) {
const event = { id: randomUUID(), createdAt: now(), startedAt: now(), kind: 'tool', phase: 'queued',
toolCallId: call.id, tool: call.function.name, label: labels[call.function.name] ?? call.function.name, taskId: run.taskId, runId: run.id };
session.events.push(event); this.store.registerInvocation(session, call, run.record, event);
}
if (message.content) this.store.message(session, 'assistant', message.content);
else this.store.save(session);
checkBudget(run.record, this.store.core.task.get(run.taskId));
if (!calls.length) {
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') {
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')) {
session.status = 'paused'; run.stopReason = 'verification_incomplete';
this.store.message(session, 'system', '答复已收到,但当前任务的工程检查尚未通过,不能视为交付完成。原目标与检查结果已保留。');
}
if (externalEngine) await this.engineRunner().finish(session, run);
if (session.status === 'completed' && run.worker) {
try { await this.workerManager().output(session, run.worker); signal.throwIfAborted(); }
catch (error) {
if (signal.aborted) throw error;
session.status = 'paused'; run.stopReason = 'worker_incomplete';
this.store.message(session, 'system', '子任务还不能交付:' + this.provider.redact(error.message ?? String(error)) + '。原目标和结果已保存。');
}
}
if (session.status === 'completed' && task.currentTaskPlanId && run.record.purpose !== 'diagnostic') {
const finalPlan = await this.taskPlanner().inspect(session, { candidates: false });
if (!finalPlan.all_verified) {
session.status = 'paused'; run.stopReason = 'task_plan_incomplete';
this.store.message(session, 'system', '任务计划仍有未核验、失效或待更新的步骤,原任务已保存。请核对执行计划后继续;模型文字不代替实际完成。');
}
}
if (session.status === 'completed' && task.requirementRevisions?.length && run.record.purpose !== 'diagnostic') {
const review = await this.requirementReview().inspect(session);
if (!review.all_resolved) {
session.status = 'paused'; run.stopReason = 'requirements_incomplete';
this.store.message(session, 'system', '答复已保留;用户要求仍有待复核、失效或未审阅来源,请在任务的要求与证据中核对。');
}
}
this.store.save(session); return;
}
let deliveryReview = null, mcpReview = null;
const preparedSets = new Set();
for (const call of calls) {
let result;
if (deliveryReview || mcpReview) {
const event = session.events.find(value => value.toolCallId === call.id && value.runId === run.id);
this.store.beginInvocation(session, call, run.record, event);
result = mcpReview ? { status: 'interrupted', reason: 'mcp_review', mcp_job_id: mcpReview,
message: '外部MCP结果待核对,这项后续调用未执行,不会自动重放。' }
: { status: 'interrupted', reason: 'git_review', plan_id: deliveryReview.id,
message: 'Git预览已经准备,等待用户确认。这项后续调用未执行,不会自动重放。' };
event.phase = 'interrupted'; event.finishedAt = now(); event.output = result.message;
this.store.finishInvocation(session, event, result);
}
else if (signal.aborted) result = { status: 'interrupted', message: '用户停止了任务,这次调用没有执行。' };
else result = await this.executeTool(session, call, run);
const invocation = [...this.store.core.tool.values()].findLast(row => row.runId === run.id && row.callId === call.id);
if (invocation?.resultArtifactId) (stepRecord.progressToolIds ??= []).push(invocation.id);
spendReadBudget(run.readBatchBudget, call, result);
session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
if (call.function.name === 'prepare_change_set' && result.status === 'awaiting_review') preparedSets.add(result.change_set_id);
if (call.function.name === 'call_registered_mcp' && result.requires_verification) mcpReview = result.mcp_job_id;
if (call.function.name === 'plan_delivery' && result.status === 'awaiting_review') {
deliveryReview = this.store.owned('delivery_plan', result.plan_id, session.id);
run.record.review = { kind: 'git_delivery', planId: deliveryReview.id, status: 'pending', preparedAt: now() };
}
this.store.save(session);
await yieldExecution(undefined, { signal });
signal.throwIfAborted();
}
this.store.finishStep(session, stepRecord);
if (mcpReview) {
session.status = 'paused'; run.stopReason = 'mcp_review';
this.store.message(session, 'system', '外部MCP操作结果待核对,原任务和后续未执行调用已保存。请在MCP运行记录查看原始输入与结果后人工核对,再显式继续。');
this.store.save(session); return;
}
if (deliveryReview) {
session.status = 'needs_review'; run.stopReason = 'git_review';
this.store.message(session, 'system', 'Git交付预览已保存。请在任务记录中审查并确认本地提交,或撤回预览。等待确认期间不继续请求模型。');
this.store.save(session, { type: 'delivery.awaiting_review', detail: { planId: deliveryReview.id } });
return;
}
// Settle the whole model turn first: later proposals can make a sealed
// set partial, and later tools may fail or need verification/stop.
for (const id of preparedSets) {
let ready = false;
try { ready = await this.changeSetManager().reviewReady(session, id, run.record); }
catch (error) {
this.store.event(session, { kind: 'system', source: 'workbench', label: '变更批次交接预检未通过', phase: 'failed',
output: this.provider.redact(error.message ?? String(error)) });
}
signal.throwIfAborted();
if (!ready) continue;
run.record.review = { kind: 'change_set', changeSetId: id, fingerprint: this.store.core.change_set.get(id).fingerprint, status: 'pending' };
session.status = 'needs_review'; run.stopReason = 'change_set_review';
this.store.message(session, 'system', '当前任务的完整变更批次已封存,同轮工具结果已保存。请审查并应用或撤销批次;等待审查期间不继续请求模型。应用后可显式续接原任务进行检查。');
this.store.save(session, { type: 'change_set.awaiting_review', detail: { changeSetId: id } });
return;
}
stepRecord.progressSettled = true;
recordTurnProgress(this.store, session, run.record, stepRecord);
if (this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress',
'模型连续重复读取工件或核对相同的工程状态,未推进当前任务。实际结果和原任务已保存,请核对后继续。');
}
run.stopReason = 'step_limit';
await this.capturePauseInputs(run);
session.status = 'paused';
this.store.message(session, 'assistant', '已到达本次工具步数上限。执行记录已保存,可以查看结果后继续。');
this.store.save(session);
} catch (error) {
this.store.interruptPending(session, run.record);
const repaired = repairToolPairs(session.providerMessages, callId => this.store.savedToolResult(session.id, callId));
if (repaired.changed) session.providerMessages = repaired.messages;
const budget = error instanceof BudgetExceeded ? error : signal.reason instanceof BudgetExceeded ? signal.reason : null;
if (signal.aborted || budget) {
run.stopReason = budget?.reason ?? 'cancelled';
if(budget)run.record.budgetPause={schema:1,reason:budget.reason,createdAt:now(),taskId:run.taskId,runId:run.id,
...(budget.contextBudget??{}),runUsage:structuredClone(run.record.usage),taskUsage:structuredClone(this.store.core.task.get(run.taskId).usage),
tokenAccounting:tokenBudgetState(run.record,this.store.core.task.get(run.taskId)),
runBudget:structuredClone(run.record.budget),taskBudget:structuredClone(this.store.core.task.get(run.taskId).budget),
note:'本地预留与上游报告用量分开记录。单个在途响应可能超过预估;超额后停止后续请求,未知用量保持未知。'};
for (const event of session.events.filter(item => item.kind === 'model' && item.runId === run.id && ['running', 'retrying'].includes(item.phase))) {
event.phase = 'interrupted'; event.finishedAt = now(); event.output = '模型请求已停止,已完成的工具结果保留。';
}
await this.capturePauseInputs(run);
session.status = 'paused';
this.store.message(session, 'system', budget?.message ?? '任务已停止,执行记录已保存。');
} else {
session.status = error.diagnostic?.kind === 'model_identity' ? 'paused' : 'failed';
if (error.diagnostic?.kind === 'model_identity') run.stopReason = 'model_identity';
const diagnostic = error.diagnostic ?? { source: 'workbench', origin: 'local', stage: 'agent_loop', kind: 'runtime',
title: '工作台任务需要处理', message: this.provider.redact(error.message ?? String(error)), occurredAt: now() };
session.lastFailure = { ...diagnostic, runId: run.id };
const message = this.store.message(session, 'system', diagnostic.message);
session.failure = { ...session.lastFailure, messageId: message.id };
this.store.event(session, { kind: 'error', source: diagnostic.source, label: diagnostic.title, phase: 'failed',
output: diagnostic.message, diagnostic: session.lastFailure });
}
this.store.save(session);
} finally {
if (currentStep && !currentStep.progressSettled) {
currentStep.progressSettled = true;
recordTurnProgress(this.store, session, run.record, currentStep, 'settled', session.lastFailure?.runId === run.id ? session.lastFailure : null);
}
if (run.worker?.engine) await this.engineRunner().finish(session, run);
}
}
async executeTool(session, call, run) {
const tool = call.function.name;
const event = session.events.find(value => value.toolCallId === call.id && value.runId === run.id)
?? this.store.event(session, { kind: 'tool', toolCallId: call.id, tool, label: labels[tool] ?? tool, phase: 'queued', startedAt: now() });
this.store.beginInvocation(session, call, run.record, event);
let result;
let progressFailureCategory = 'invalid_input';
try {
const args = JSON.parse(call.function.arguments);
validateToolArgs(tool, args);
progressFailureCategory = 'permission';
if (!taskToolAllowed(this.store.core.task.get(run.taskId), run.record, tool, args)) throw new Error(run.record.purpose === 'diagnostic'
? '本次是只读运行诊断,不执行文件修改、命令或其他副作用操作。原任务目标保持。' : '原任务明确无需测试;这项自动检查没有执行。请直接完成原目标,追加测试需要用户明确要求。');
assertWorkerTool(this.store, session, tool, args);
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
progressFailureCategory = 'tool_or_environment';
const proofHint = !!this.store.core.task.get(run.taskId)?.currentTaskPlanId && PLAN_READ_TOOLS.includes(tool);
const readMetadata = { ...(proofHint ? { tool_invocation_id: event.invocationId } : {}),
...(tool === 'read_browser_result' ? { repeated_read_count: Number.MAX_SAFE_INTEGER, reading_hint: BROWSER_READ_HINT } : {}) };
const batch = run.readBatchBudget;
const pageBytes = batch?.remainingCalls ? Math.floor(batch.remainingBytes / batch.remainingCalls) : run.readMessageBytes ?? 16000;
const maximumMessageBytes = Math.max(1, pageBytes - readMetadataReserve(readMetadata));
if (!['act_browser_tab','prepare_environment','run_command', 'run_checks', 'run_browser'].includes(tool)) this.store.invocationState(session, event, 'running');
else this.store.save(session);
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
else if (tool === 'read_registered_skill') {
verifyPlanEvidence(this.store, session, this.store.owned('context_plan', run.record.currentContextPlanId, session.id));
result = this.skillRegistry().read(session, run.record, args, { maximumMessageBytes, callId: call.id });
recordArtifactRead(this.store.core.task.get(run.taskId), this.store.owned('artifact', result.artifact_id, session.id), result, event.invocationId, run.id);
}
else if (tool === 'call_registered_mcp') {
verifyPlanEvidence(this.store, session, this.store.owned('context_plan', run.record.currentContextPlanId, session.id));
const manager = this.mcpRegistry(), registration = manager.prepareCall(session, run.record, args);
result = await this.requestCommand(session, event, { mcpRegistrationId: registration.id,
command: 'MCP程序 ' + registration.launch.executable.path + '\n入口 ' + (registration.launch.entry?.path ?? '(直接程序)')
+ '\n工具 ' + args.tool + '\n参数 ' + JSON.stringify(args.arguments) + '\n契约 ' + args.contract_sha256,
reason: '启动已登记的外部程序并调用所选工具;进程拥有当前用户权限,独立进程不等于系统沙箱。' }, run, async () => {
manager.prepareCall(session, run.record, args);
const started = manager.start(session, { id: registration.id, configurationRevision: registration.configurationRevision, confirm: true },
{ source: 'agent', signal: run.controller.signal, call: args, invocationId: event.invocationId });
const job = await started.promise;
return { status: job.status, mcp_job_id: job.id, report_artifact_id: job.reportArtifactId ?? null,
report_sha256: job.reportSha256 ?? null, requires_verification: job.requiresVerification,
message: job.error?.message ?? '外部工具原结果已保存,使用read_artifact读取报告。外部结果不代替工程验收。' };
});
}
else if (tool === 'plan_task') { const plan = await this.taskPlanner().plan(session, args, { source: 'agent' });
result = { status: 'planned', plan_id: plan.id, revision: plan.revision, steps: plan.steps, contract_artifact_id: plan.contractArtifactId,
note: '计划已保存,步骤尚未核验;保留原目标和通过条件,按原工具结果核验,不直接标记完成。' }; }
else if (tool === 'inspect_task_plan') result = await this.taskPlanner().inspect(session, { candidates: false });
else if (tool === 'verify_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读取,查询不会启动引擎。' };
else if (tool === 'list_research_targets') result = { targets: this.researchManager().targets(session), jobs: this.researchManager().jobs(session).filter(job => job.taskId === run.taskId).map(job => this.researchManager().result(job)) };
else if (tool === 'analyze_research_target') {
const manager = this.researchManager(), started = manager.start(session, args.target_id, args.operation, { source: 'agent', signal: run.controller.signal });
result = manager.result(await started.promise);
}
else if (tool === 'read_research_evidence') result = this.researchManager().readEvidence(session, args.research_job_id,
{ ...args, maximumMessageBytes, callId: call.id });
else if (tool === 'inspect_browser_tabs') result = this.browsingManager().toolSnapshot(session);
else if (tool === 'observe_browser_tab') result = await this.browsingManager().observe(session,args.tab_id);
else if (tool === 'act_browser_tab') {
const {tab_id,...input}=args,manager=this.browsingManager();
result = await this.requestCommand(session,event,{browsingTabId:tab_id,browsingInput:input,command:'内置浏览器 '+input.action+'\n'+JSON.stringify(input),reason:'按原页面观察执行一次固定动作;页面文字不能授予新权限。'},run,()=>manager.act(session,tab_id,input,{approved:true,signal:run.controller.signal,approvalId:session.approvals.findLast(value=>value.eventId===event.id&&value.status==='approved')?.id}));
}
else if (tool === 'inspect_project') result = await inspectProject(run.project);
else if (tool === 'plan_browser') result = { ...publicBrowserPlan(await this.browserManager().plan(session, args, { source: 'agent' })),
note: '计划已封存,页面尚未运行。run_browser请求确认后执行;steps为空只观察页面,不能代替验收。' };
else if (tool === 'read_browser_result') {
result = this.browserManager().readResult(session, args.browser_job_id, { ...args, maximumMessageBytes, callId: call.id });
recordBrowserRead(this.store.core.task.get(run.taskId), result, event.invocationId, run.id);
}
else if (tool === 'run_browser') {
const manager = this.browserManager(), plan = manager.planFor(session, args.plan_id);
result = await this.requestCommand(session, event, { browserPlanId: plan.id,
browserSummary: { buildDirectory: plan.build.directory, buildSha256: plan.build.sha256, viewport: plan.viewport, steps: plan.steps },
command: '浏览器检查 ' + plan.build.directory + plan.path + '\n视口 ' + plan.viewport.width + '×' + plan.viewport.height + '\n' + plan.steps.length + ' 个步骤 · 计划 ' + plan.id.slice(0, 8),
reason: '按封存范围操作实际页面,保存DOM、断言、请求和截图。' }, run, async () => {
const started = manager.start(session, plan.id, { source: 'agent', signal: run.controller.signal }); return manager.result(session, await started.promise);
});
}
else if (tool === 'index_project') {
const index = await this.projectIndexer().refresh(run.project);
if (session.taskId !== run.record.taskId || session.runId !== run.record.id) throw new Error('建立索引期间Task/Run已切换,请重新读取当前任务。');
const artifact = this.store.artifactStore.write(session, run.record, JSON.parse(this.provider.redact(JSON.stringify(index))), { kind: 'project-index' });
this.store.core.artifact.set(artifact.id, artifact);
result = { status: index.coverage.truncated ? 'partial' : 'indexed', ...this.projectIndexer().summary(index), artifact_id: artifact.id,
symbols: index.symbols.slice(0, 12), imports: index.imports.slice(0, 8), note: '完整索引在本Task的工件中。定位后读取实际行;文件SHA256用于精确补丁,索引不等同于运行验证。' };
}
else if (tool === 'query_code') {
const index = await this.projectIndexer().refresh(run.project);
if (session.taskId !== run.record.taskId || session.runId !== run.record.id) throw new Error('索引查询期间Task/Run已切换,请重新读取当前任务。');
result = this.projectIndexer().query(index, args);
}
else if (tool === 'read_artifact') {
const artifact = this.store.owned('artifact', args.artifact_id, session.id), text = this.store.artifactStore.read(artifact);
result = artifactPage(artifact, text, args, { callId: call.id, maximumMessageBytes });
recordArtifactRead(this.store.core.task.get(run.taskId), artifact, result, event.invocationId, run.id);
}
else if (tool === 'prepare_change_set') {
const set = await this.changeSetManager().prepare(session, args.change_ids, { source: 'agent' });
result = { status: 'awaiting_review', change_set_id: set.id, task_id: set.taskId, fingerprint: set.fingerprint,
files: set.files.map(file => ({ path: file.path, change_id: file.changeId, base_sha256: file.baseSha256, sha256: file.sha256 })),
note: '只封存了整批审查范围,未写入项目。请用户在改动面板审核整个批次并确认应用。' };
}
else if(tool==='diagnose_environment') result=publicEnvironmentDiagnostic(await this.environmentManager().diagnose(session));
else if(tool==='plan_environment') result=await this.environmentManager().plan(session,args,{source:'agent'});
else if(tool==='prepare_environment') {
const manager=this.environmentManager(),plan=manager.own(session,args.plan_id,args.fingerprint);
result=await this.requestCommand(session,event,{command:plan.invocation.executable+'\n'+plan.invocation.args.map(arg=>JSON.stringify(arg)).join('\n'),
environmentPlanId:plan.id,environmentSummary:{root:plan.root,registry:plan.registry,scripts:plan.scripts,offline:plan.offline,timeoutMs:plan.timeoutMs,lifecycle:plan.lifecycle,installScriptPackages:plan.installScriptPackages},
reason:'准备所属独立工作区依赖;'+(plan.scripts==='skip'?'跳过所有安装脚本':'允许根工程和依赖安装脚本')+';完成后仍需工程检查。'},run,async()=>{
const approval=session.approvals.findLast(row=>row.environmentPlanId===plan.id&&row.status==='approved'&&row.runId===run.id);
const {promise}=await manager.start(session,plan.id,plan.fingerprint,{approved:true,signal:run.controller.signal,source:'agent',approvalId:approval?.id});
const job=await promise;return {status:job.status,job_id:job.id,plan_id:plan.id,summary:job.summary,log_artifact_id:job.logArtifactId,environment:job.after,requires_verification:job.requiresVerification};
});
}
else if (tool === 'plan_checks') result = await this.checkRunner().plan(session, args.names);
else if (tool === 'plan_delivery') {
const plan = await this.gitDelivery().plan(session, args.message === undefined ? {} : { message: args.message }, { source: 'agent' });
result = { status: 'awaiting_review', plan_id: plan.id, task_id: plan.taskId, paths: plan.paths, message: plan.message,
author: plan.author, parent: plan.snapshot.head, branch: plan.snapshot.branch, source_fingerprint: plan.sourceFingerprint,
diff_artifact_id: plan.diffArtifactId, check_job_id: plan.checkJobId, policy: plan.policy,
note: '只准备了预览,尚未提交。用户在任务记录中审核并确认本地Git提交。' };
}
else if (tool === 'delivery_report') {
const saved = await this.gitDelivery().report(session, { source: 'agent' });
result = { status: 'completed', report_status: saved.report.status, artifact_id: saved.artifactId, markdown_artifact_id: saved.markdownArtifactId,
verified_check_job_id: saved.report.verifiedCheckJobId, source_fingerprint: saved.report.source.fingerprint,
note: saved.report.task.note };
}
else if (tool === 'run_checks') {
const plan = this.checkRunner().planFor(session, args.plan_id);
const previous = await this.checkRunner().unchangedResult(session, plan.id);
if (previous) {
recordUnchangedCheck(this.store.core.task.get(run.taskId), previous, run.id);
result = { status: previous.status === 'passed' ? 'completed' : previous.status, check_status: previous.status, job_id: previous.id,
plan_id: previous.planId, results: previous.results, summary: previous.summary, reused: true, verification_refreshed: false,
message: '当前已记录工程、命令和运行环境输入与原检查一致;返回原结果,未再次执行或刷新核验。请修复失败;用户可在工程检查中显式重跑。' };
} else result = await this.requestCommand(session, event, { command: plan.checks.map(check => check.command).join('\n'), checkPlanId: plan.id,
checkScripts: plan.checks.map(check => ({ name: check.name, script: check.script, lifecycle: check.lifecycle,
...(check.python ? { python: { runtime: check.python.runtime, mode: check.python.mode } } : {}) })),
reason: '执行工程检查计划 ' + plan.id.slice(0, 8) + ';保存测试数量、退出码和日志。' }, run, async () => {
const { promise } = await this.checkRunner().start(session, plan.id, { signal: run.controller.signal, source: 'agent' });
recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
const job = await promise;
return { status: job.status === 'cancelled' ? 'interrupted' : job.status === 'passed' ? 'completed' : job.status,
check_status: job.status, job_id: job.id, plan_id: job.planId, results: job.results, summary: job.summary,
requires_verification: job.requiresVerification === true, fingerprint: job.fingerprint };
});
}
else if (tool === 'list_files') result = listFiles(run.project, args.path, args.depth ?? 3, 500);
else if (tool === 'read_file') {
result = filePage(readLines(run.project, args), args, { callId: call.id, maximumMessageBytes,
// Match the planner's complete-small-source retention boundary;
// returning a larger page that is immediately trimmed adds no useful
// throughput. The escaped JSON budget can still make this smaller.
...(run.readBatchBudget ? { maximumPageCharacters: run.readPageCharacters } : {}) });
recordFileRead(this.store.core.task.get(run.taskId), result, event.invocationId, run.id);
}
else if (tool === 'search_files') result = searchFiles(run.project, args);
else if (tool === 'propose_file') result = proposeFile(this.store, session, args);
else if (tool === 'propose_patch') result = proposePatch(this.store, session, args);
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
else throw new Error('当前能力表没有工具:' + tool);
if (proofHint) result.tool_invocation_id = event.invocationId;
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : ['failed', 'error'].includes(result.status) ? 'failed' : 'completed';
if (tool === 'inspect_session') recordSessionInspection(this.store.core.task.get(run.taskId), result);
else if (['propose_file', 'propose_patch', 'verify_task_step'].includes(tool)) {
const task=this.store.core.task.get(run.taskId);
if(result.status==='unchanged'||result.reused===true){
result.unchanged_action_count=recordUnchangedAction(task,tool,result,run.id);
result.reading_hint=task.readProgress.warning;
}else if(!['error','failed','interrupted','unknown','denied','unverified','stale'].includes(result.status))clearReadStreak(task);
}
if (typeof result.stdout === 'string') { result.stdout = this.provider.redact(result.stdout); result.stderr = this.provider.redact(result.stderr ?? ''); }
event.output = this.provider.redact(typeof result.stdout === 'string' ? result.stdout + (result.stderr ? '\n' + result.stderr : '') : JSON.stringify(result).slice(0, 16000));
if (result.exit_code !== undefined) event.exitCode = result.exit_code;
} catch (error) {
const record = this.store.core.tool.get(event.invocationId);
if (record) record.progressFailureCategory = progressFailureCategory;
result = { status: run.controller.signal.aborted ? 'interrupted' : 'error', message: this.provider.redact(error.message ?? String(error)) };
event.phase = result.status === 'interrupted' ? 'interrupted' : 'failed';
event.output = result.message;
}
event.finishedAt = now();
event.durationMs = Date.parse(event.finishedAt) - Date.parse(event.startedAt);
result = JSON.parse(this.provider.redact(JSON.stringify(result)));
this.store.finishInvocation(session, event, result);
return result;
}
async requestCommand(session, event, args, run, execute) {
const command = String(args.command ?? '').trim();
const maximum = args.mcpRegistrationId && execute ? 24000 : 6000;
if (!command || command.length > maximum) throw new Error(maximum === 6000
? '终端命令不能为空,也不能超过 6,000 字符。' : 'MCP审批内容不能为空,也不能超过24,000字符;参数仍按工具契约核对。');
const approval = { id: randomUUID(), toolCallId: event.toolCallId, eventId: event.id, invocationId: event.invocationId,
taskId: run.taskId, runId: run.id, projectId: session.projectId, command,
...(execute ? args.browsingTabId ? {browsingTabId:args.browsingTabId,browsingInput:args.browsingInput} : args.environmentPlanId ? {environmentPlanId:args.environmentPlanId,environmentSummary:args.environmentSummary} : args.mcpRegistrationId ? { mcpRegistrationId: args.mcpRegistrationId } : args.browserPlanId ? { browserPlanId: args.browserPlanId, browserSummary: args.browserSummary } : { checkPlanId: args.checkPlanId, checkScripts: args.checkScripts } : {}),
reason: String(args.reason ?? '').slice(0, 800), cwd: args.mcpRegistrationId ? '所属MCP临时目录(将在启动后记录)' : run.project.root,
shell: args.browsingTabId ? '内置浏览器 · 原页面固定动作' : args.environmentPlanId ? '依赖准备 · 固定npm命令' : args.mcpRegistrationId ? 'MCP · 外部独立进程' : args.browserPlanId ? '浏览器 · 独立Edge环境' : execute ? '工程检查器 · 直接进程' : executionEnvironment().shell, status: 'pending', createdAt: now() };
session.approvals.push(approval);
event.phase = 'waiting'; session.status = 'awaiting_approval';
this.store.invocationState(session, event, 'waiting');
recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
const decision = await new Promise(resolve => {
const signal = run.controller.signal;
const settle = value => { this.waiters.delete(approval.id); signal.removeEventListener('abort', cancel); resolve(value); };
const cancel = () => { if (approval.status === 'pending') approval.status = 'interrupted'; this.store.save(session); settle(false); };
this.waiters.set(approval.id, { sessionId: session.id, settle, runId: run.id });
signal.addEventListener('abort', cancel, { once: true });
if (signal.aborted) cancel();
});
if (!decision) { if (!run.controller.signal.aborted) session.status = 'running'; return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: approvalPresentation(approval).denied, requires_verification: false }; }
run.controller.signal.throwIfAborted();
const cwd = safePath(run.project);
event.phase = 'running'; event.executedAt = now(); session.status = 'running';
this.store.invocationState(session, event, 'running');
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
if (execute) return execute();
return this.executeCommand(command, cwd, run.controller.signal, output => {
event.output = output; this.store.save(session);
});
}
decide(sessionId, approvalId, allow) {
const session = this.store.session(sessionId);
const approval = session.approvals.find(item => item.id === approvalId);
const waiter = this.waiters.get(approvalId);
if (!approval || approval.status !== 'pending' || !waiter || waiter.sessionId !== sessionId || waiter.runId !== session.runId
|| approval.runId !== session.runId || approval.taskId !== session.taskId || approval.projectId !== session.projectId) throw Object.assign(new Error('确认请求已过期;需要重新请求命令。'), { status: 409 });
approval.status = allow ? 'approved' : 'denied'; approval.decidedAt = now();
this.store.save(session); waiter.settle(!!allow);
}
executeCommand(command, cwd, signal, onOutput) {
return new Promise(resolve => {
const windows = process.platform === 'win32';
const executable = windows ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : '/bin/sh';
const bootstrap = "$workbenchUtf8 = [Text.UTF8Encoding]::new($false)\n[Console]::InputEncoding = $workbenchUtf8\n[Console]::OutputEncoding = $workbenchUtf8\n$OutputEncoding = $workbenchUtf8\n$workbenchCode = [Console]::In.ReadToEnd()\ntry {\n & ([scriptblock]::Create($workbenchCode))\n $workbenchSucceeded = $?\n if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\n if (-not $workbenchSucceeded) { exit 1 }\n} catch { [Console]::Error.WriteLine($_.Exception.Message); [Console]::Error.WriteLine($_.FullyQualifiedErrorId); exit 1 }";
const argumentsList = windows ? ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(bootstrap, 'utf16le').toString('base64')] : ['-c', command];
const childEnv = projectEnvironment();
const child = spawn(executable, argumentsList, { cwd, windowsHide: true, stdio: [windows ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: childEnv });
if (windows) { child.stdin.on('error', () => {}); child.stdin.end(command, 'utf8'); }
const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
let stdout = '', stderr = '', truncated = false, timedOut = false, killed = false, lastUpdate = 0, settled = false;
const append = (kind, data) => {
const previous = kind === 'stdout' ? stdout : stderr;
const joined = previous + data;
if (joined.length > 32000) truncated = true;
if (kind === 'stdout') stdout = joined.slice(0, 32000); else stderr = joined.slice(0, 32000);
if (Date.now() - lastUpdate > 250) { lastUpdate = Date.now(); onOutput(stdout + (stderr ? '\n' + stderr : '')); }
};
const terminate = () => {
if (killed || !child.pid || settled) return;
killed = true;
if (windows) execFile('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, () => {});
else child.kill('SIGTERM');
};
const finish = (code, error) => {
if (settled) return; settled = true;
clearTimeout(timeout); signal.removeEventListener('abort', terminate);
resolve({ status: signal.aborted ? 'interrupted' : timedOut || error || code !== 0 ? 'failed' : 'completed',
exit_code: code, stdout, stderr: error ? stderr + '\n' + error.message : stderr,
truncated, timed_out: timedOut, command });
};
const timeout = setTimeout(() => { timedOut = true; terminate(); }, 60000);
signal.addEventListener('abort', terminate, { once: true });
child.stdout.on('data', data => append('stdout', decoders.stdout.write(data)));
child.stderr.on('data', data => append('stderr', decoders.stderr.write(data)));
child.stdout.on('end', () => append('stdout', decoders.stdout.end()));
child.stderr.on('end', () => append('stderr', decoders.stderr.end()));
child.on('error', error => finish(null, error));
child.on('close', code => finish(code));
if (signal.aborted) terminate();
});
}
async stop(sessionId, expected = null) {
const original = this.active.get(sessionId);
const assertOriginal = () => {
if (!expected) return;
const session = this.store.session(sessionId);
if (session.taskId !== expected.taskId || session.runId !== expected.runId || this.active.get(sessionId) && this.active.get(sessionId) !== original) {
throw Object.assign(new Error('原停止请求的任务或运行已变化。'), { status: 409 });
}
};
assertOriginal();
await this.browsing?.stop(sessionId);
await this.previews?.stop(sessionId);
await this.evaluations?.stopParent(sessionId);
await this.workers?.stopParent(sessionId);
assertOriginal();
const run = this.active.get(sessionId);
if (!run) { await this.environments?.stop(sessionId); await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); await this.research?.stop(sessionId); await this.engines?.stop(sessionId); await this.browser?.stop(sessionId); await this.mcp?.stop(sessionId); await this.taskPlans?.settle(sessionId); return; }
const session = this.store.session(sessionId);
session.status = 'stopping'; this.store.save(session);
run.controller.abort(new Error('用户停止任务'));
await run.promise;
}
async stopAll() { await this.filePreviews?.stopAll(); await this.browsing?.stopAll(); await this.previews?.stopAll(); await this.evaluations?.stopAll(); await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); await this.environments?.stopAll(); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
}
@@ -0,0 +1,216 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { observeTurn, toolProgressFacts, TURN_PROGRESS_LIMITS } from '../src/core/context/turn-progress.mjs';
import { recordTurnProgress, inspectTurnProgress } from '../src/core/context/turn-progress-recorder.mjs';
import { fixture, compatibleFixture, call, completion, assertToolPairs, until } from './helpers.mjs';
import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
import { DeliveryReporter } from '../src/core/delivery-report.mjs';
import { RequirementReview } from '../src/core/tasks/requirement-review.mjs';
import { CheckRunner } from '../src/core/check-runner.mjs';
import { proposeFile, applyChange } from '../src/server/files.mjs';
const sha = value => createHash('sha256').update(value).digest('hex');
const facts = (fields = {}) => ({ projectId: 'p', sessionId: 's', taskId: 't', runId: 'r', stepIndex: 0, phase: 'settled', ...fields });
const read = (start, end, fields = {}) => ({ id: randomUUID(), name: 'read_file', argsSha256: 'args', read: { key: 'original-file-range', sha256: sha('source'), unit: 'utf16_in_original_range', start, end, ...fields } });
const fail = (category, signature = 'original error', fields = {}) => ({ id: randomUUID(), name: 'read_file', argsSha256: 'same-arguments', failure: { category, signature }, ...fields });
test('fixed normal exploration, pagination, SHA changes and repeated ranges are external observations, not a score', () => {
let state, result; const expected = [
[read(0, 4), 'evidence_growth', 4], [read(4, 8), 'evidence_growth', 4], [read(2, 6), 'repeated_read_candidate', 0],
[read(6, 10), 'evidence_growth', 2], [read(0, 4, { sha256: sha('changed source') }), 'evidence_growth', 4],
];
for (const [tool, classification, growth] of expected) { result = observeTurn(state, facts({ tools: [tool] })); state = result.state;
assert.equal(result.observation.classification, classification); assert.equal(result.observation.delta.read_characters, growth); }
assert.equal(state.mode, 'shadow'); assert.equal('score' in result.observation, false); assert.equal('shouldAbort' in result.observation, false);
});
test('read-only research is valid work; model summaries and unchanged timestamped listings do not become engineering evidence', () => {
const first = observeTurn(null, facts({ tools: [read(0, 30)] })); assert.equal(first.observation.classification, 'evidence_growth');
const conclusion = observeTurn(first.state, facts({ modelText: 'I have finished all requirements', privateReasoning: 'DO_NOT_SAVE' }));
assert.equal(conclusion.observation.classification, 'no_observed_change'); assert.ok(!JSON.stringify(conclusion).includes('DO_NOT_SAVE'));
const record = { id: 'first', tool: 'list_files', argsSha256: 'same' };
const a = toolProgressFacts(record, { files: ['a'], inspectedAt: 'first', tool_invocation_id: '1' });
const b = toolProgressFacts({ ...record, id: 'second' }, { files: ['a'], inspectedAt: 'later', tool_invocation_id: '2' });
const result = observeTurn(observeTurn(null, facts({ tools: [a] })).state, facts({ tools: [b] }));
assert.equal(result.observation.classification, 'no_observed_change');
});
test('new permissions, network and broken tools are failure evidence; repeated invalid inputs remain candidates', () => {
let state;
for (const category of ['permission', 'network', 'invalid_input', 'tool_or_environment']) {
let result = observeTurn(state, facts({ tools: [fail(category)] })); state = result.state; assert.equal(result.observation.classification, 'new_failure_evidence');
result = observeTurn(state, facts({ tools: [fail(category)] })); state = result.state; assert.equal(result.observation.classification, 'repeated_failure_candidate');
assert.equal(result.observation.delta.repeated_failures, 1);
}
const changed = observeTurn(state, facts({ tools: [fail('network', 'different actual error')] })); assert.equal(changed.observation.classification, 'new_failure_evidence');
});
test('waiting for original long checks, review and approvals stays waiting across repeated observations', () => {
let state;
for (const kind of ['check_job', 'approval', 'review']) for (let i = 0; i < 4; i++) {
const result = observeTurn(state, facts({ tools: [fail('permission')], waiting: [{ kind, id: 'owned-operation' }] })); state = result.state;
assert.equal(result.observation.classification, 'waiting'); assert.equal(result.observation.waiting[0].kind, kind);
}
});
test('baseline facts, real repairs, current-source check results and requirement evidence have distinct growth', () => {
const prior = { changes: [['a', 'sha-old']], checks: [['old-source', 'failed', 'log']], requirements: [['req', 'rev1', 'proof']] };
let result = observeTurn(null, facts({ ...prior, phase: 'baseline' })); assert.equal(result.observation.classification, 'baseline');
assert.equal(result.observation.delta.check_results, 0);
result = observeTurn(result.state, facts(prior)); assert.equal(result.observation.classification, 'no_observed_change');
result = observeTurn(result.state, facts({ changes: [['a', 'sha-new']], checks: [['new-source', 'passed', 'new-log']], requirements: [['req', 'rev2', 'new-proof']] }));
assert.equal(result.observation.delta.changed_files, 1); assert.equal(result.observation.delta.check_results, 1); assert.equal(result.observation.delta.requirement_evidence, 1);
result = observeTurn(result.state, facts({ userBoundaries: [['message-1', 'same-text'], ['message-2', 'same-text']] }));
assert.equal(result.observation.classification, 'user_boundary'); assert.equal(result.observation.delta.user_boundaries, 2);
});
test('bounded memory keeps unknown instead of claiming an unretained range is repeated; Task/Run instances cannot mix', () => {
let state;
for (let i = 0; i < TURN_PROGRESS_LIMITS.sources; i++) state = observeTurn(state, facts({ tools: [read(0, 1, { key: String(i) })] })).state;
const full = observeTurn(state, facts({ tools: [read(0, 1, { key: 'unretained' })] }));
assert.equal(full.observation.classification, 'unknown_bounded'); assert.equal(full.observation.delta.repeated_reads, 0); assert.equal(full.state.reads.length, TURN_PROGRESS_LIMITS.sources);
assert.throws(() => observeTurn(state, facts({ runId: 'another' })), /another Task\/Run/);
for (let i = 0; i < 70; i++) state = observeTurn(state, facts()).state;
assert.equal(state.turns.length, TURN_PROGRESS_LIMITS.turns); assert.equal(state.truncated, true);
});
test('actual runtime records growing pages then a repeated page without changing model rounds, stop rules or original tool pairs', async t => {
const f = fixture(t); let requests = 0;
const model = await compatibleFixture(t, (url, body) => {
requests++; assert.ok(!JSON.stringify(body).includes('same_sha_range_already_returned')); assert.ok(!JSON.stringify(body).includes('turn-progress-shadow'));
return { body: requests < 4 ? completion([call('page-' + requests, 'read_file', { path: 'README.md', offset: requests === 1 ? 0 : 10, limit: 10 })]) : completion([], '研究结论:已读取原说明前两页。') };
});
f.store.saveConfig({ mode: 'compatible', model: 'owned-shadow', baseUrl: model.baseUrl, maxSteps: 6 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll()); runtime.start(f.session.id, '只研究原README说明,不修改文件。');
await runtime.active.get(f.session.id).promise;
const run = f.store.core.run.get(f.session.runId), turns = run.progressShadow.turns.filter(row => row.phase === 'settled');
assert.equal(requests, 4); assert.equal(turns.length, 4); assert.equal(turns[0].classification, 'evidence_growth'); assert.equal(turns[0].delta.read_characters, 10);
assert.equal(turns[1].delta.read_characters, 10); assert.equal(turns[2].classification, 'repeated_read_candidate');
assert.equal(turns[3].classification, 'no_observed_change'); assert.equal(f.session.status, 'completed'); assert.equal(run.stopReason, null);
assertToolPairs(f.session.providerMessages); assert.equal(f.session.changes.length, 0);
const original = structuredClone(run.progressShadow), report = await new DeliveryReporter(f.store).create(f.session);
assert.equal(report.report.turnObservations[0].evidence_verified, true);
f.store.close(); const restored = new Store(f.data); f.onCleanup(() => restored.close());
assert.deepEqual(restored.core.run.get(run.id).progressShadow, original);
const ref = turns[0].tools[0], record = restored.owned('tool', ref.id, f.session.id), argsSha = record.argsSha256;
record.argsSha256 = '0'.repeat(64); assert.equal(inspectTurnProgress(restored, restored.session(f.session.id), restored.core.run.get(run.id)).evidence_verified, false); record.argsSha256 = argsSha;
const artifact = restored.owned('artifact', ref.result_artifact_id, f.session.id); artifact.sha256 = '0'.repeat(64);
assert.equal(inspectTurnProgress(restored, restored.session(f.session.id), restored.core.run.get(run.id)).evidence_verified, false);
});
test('actual invalid tool calls repeat under the original step budget; observation never adds an early stop', async t => {
const f = fixture(t); let requests = 0;
const model = await compatibleFixture(t, () => ({ body: completion([call('bad-' + (++requests), 'read_file', { path: 17 })]) }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-invalid', baseUrl: model.baseUrl, maxSteps: 4 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll()); runtime.start(f.session.id, '研究已有文件'); await runtime.active.get(f.session.id).promise;
const run = f.store.core.run.get(f.session.runId), turns = run.progressShadow.turns.filter(row => row.phase === 'settled');
assert.equal(requests, 4); assert.equal(run.stopReason, 'step_limit'); assert.equal(turns[0].classification, 'new_failure_evidence');
assert.equal(turns[1].classification, 'repeated_failure_candidate'); assert.ok(turns[0].reasons.includes('new_failure:invalid_input')); assertToolPairs(f.session.providerMessages);
});
test('actual command approval is observed as waiting and denial stays a permission failure', async t => {
const f = fixture(t); let requests = 0;
const model = await compatibleFixture(t, () => ({ body: ++requests === 1 ? completion([call('read-before-approval', 'read_file', { path: 'README.md' }), call('approval', 'run_command', { command: 'node --version', reason: '所属环境检查' })]) : completion([], '审批拒绝,原目标保留。') }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-waiting', baseUrl: model.baseUrl, maxSteps: 3 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll()); runtime.start(f.session.id, '检查所属环境');
await until(() => f.session.status === 'awaiting_approval'); const run = f.store.core.run.get(f.session.runId);
assert.equal(run.progressShadow.turns.at(-1).classification, 'waiting'); assert.equal(run.progressShadow.turns.at(-1).waiting[0].kind, 'approval');
runtime.decide(f.session.id, f.session.approvals.at(-1).id, false); await runtime.active.get(f.session.id).promise;
assert.ok(run.progressShadow.turns.some(row => row.reasons.includes('new_failure:permission'))); assert.equal(requests, 2); assert.equal(f.session.approvals[0].status, 'denied');
const settled = run.progressShadow.turns.find(row => row.phase === 'settled');
assert.ok(settled.delta.read_characters > 0); assert.equal(settled.delta.repeated_reads, 0); assertToolPairs(f.session.providerMessages);
});
test('network errors remain model failures with shadow failure evidence, never a fabricated no-progress cause', async t => {
const f = fixture(t);
const model = await compatibleFixture(t, () => ({ status: 502, body: { error: { message: 'Owned upstream gateway failure' } } }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-network', baseUrl: model.baseUrl, maxSteps: 2 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll()); runtime.start(f.session.id, '读取当前工程'); await runtime.active.get(f.session.id).promise;
const run = f.store.core.run.get(f.session.runId); assert.equal(run.stopReason, null); assert.equal(f.session.status, 'failed');
assert.equal(f.session.lastFailure.runId, run.id); assert.equal(f.session.lastFailure.httpStatus, 502);
assert.ok(run.progressShadow.turns.some(row => row.classification === 'new_failure_evidence')); assert.equal(run.progressShadow.turns.at(-1).tools[0].tool, 'model_request');
assert.equal(inspectTurnProgress(f.store, f.session, run).evidence_verified, true);
f.session.events.find(row => row.id === run.progressShadow.turns.at(-1).tools[0].source_event_id).diagnostic.httpStatus = 503;
assert.equal(inspectTurnProgress(f.store, f.session, run).evidence_verified, false);
});
test('observer receipt failure cannot change tool results, model budget or completion', async t => {
const f = fixture(t), original = f.store.artifactStore.write.bind(f.store.artifactStore); let requests = 0;
f.store.artifactStore.write = (session, run, value, options) => { if (options?.kind === 'turn-progress-shadow') throw new Error('owned observer failure'); return original(session, run, value, options); };
const model = await compatibleFixture(t, () => ({ body: ++requests === 1 ? completion([call('read', 'read_file', { path: 'README.md' })]) : completion([], '原工具完成') }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-observer-fault', baseUrl: model.baseUrl, maxSteps: 3 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll()); runtime.start(f.session.id, '研究当前说明'); await runtime.active.get(f.session.id).promise;
assert.equal(requests, 2); assert.equal(f.session.status, 'completed'); assert.equal(f.store.core.run.get(f.session.runId).progressShadowError.kind, 'observation_unavailable');
assert.equal(f.store.savedToolResult(f.session.id, 'read').content.length > 0, true); assertToolPairs(f.session.providerMessages);
});
test('a later receipt recovers after an observation write failure without misaligning retained source receipts', async t => {
const f = fixture(t), original = f.store.artifactStore.write.bind(f.store.artifactStore); let requests = 0, observations = 0;
f.store.artifactStore.write = (session, run, value, options) => {
if (options?.kind === 'turn-progress-shadow' && ++observations === 2) throw new Error('owned single observation fault');
return original(session, run, value, options);
};
const model = await compatibleFixture(t, () => ({ body: ++requests < 3 ? completion([call('recovery-' + requests, 'read_file', { path: 'README.md', offset: (requests - 1) * 10, limit: 10 })]) : completion([], '原研究工具完成') }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-recovery', baseUrl: model.baseUrl, maxSteps: 4 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll()); runtime.start(f.session.id, '研究当前说明'); await runtime.active.get(f.session.id).promise;
const run = f.store.core.run.get(f.session.runId), view = inspectTurnProgress(f.store, f.session, run);
assert.equal(requests, 3); assert.equal(f.session.status, 'completed'); assert.equal(view.evidence_verified, true); assert.match(view.error, /部分观察未能记录/);
assert.equal(view.turns.length, view.artifact_ids.length); assert.equal(view.turns.length, 3); assertToolPairs(f.session.providerMessages);
});
test('real applied files, counted checks and current requirement proofs grow after an existing-facts baseline', async t => {
const f = fixture(t);
fs.writeFileSync(path.join(f.projectRoot, 'package.json'), JSON.stringify({ private: true, type: 'module', scripts: { test: 'node --test check.test.mjs' } }));
fs.writeFileSync(path.join(f.projectRoot, 'check.test.mjs'), "import test from 'node:test'; import assert from 'node:assert/strict'; test('owned evidence',()=>assert.equal(2+2,4));\n");
const run = beginPlanTask(f, '解释README.md的实际内容,保留工程证据。'), manager = new RequirementReview(f.store), runner = new CheckRunner(f.store);
f.onCleanup(() => runner.stopAll());
const read = completeRead(f);
await manager.save(f.session, { expected_revision: 0, requirements: [{ key: 'read', title: '原说明', criterion: '原读取可核对', kind: 'analysis', tools: ['read_file'], method: 'evidence', source: { kind: 'goal', id: run.taskId, start: 0, end: 5 } }] });
await manager.verify(f.session, { expected_revision: 1, key: 'read', evidence_id: read.id });
let plan = await runner.plan(f.session, ['test']), job = await (await runner.start(f.session, plan.id)).promise;
assert.equal(job.status, 'passed'); assert.ok(job.results[0].tests.passed > 0);
const baseline = recordTurnProgress(f.store, f.session, run, null, 'baseline');
assert.equal(baseline.delta.check_results, 0); assert.equal(baseline.delta.requirement_evidence, 0);
assert.equal(recordTurnProgress(f.store, f.session, run, null).classification, 'no_observed_change');
const change = proposeFile(f.store, f.session, { path: 'README.md', content: '# Newly observed actual content\n', reason: 'owned applied evidence' });
applyChange(f.store, f.session, change.change_id);
const current = completeRead(f); await manager.verify(f.session, { expected_revision: 1, key: 'read', evidence_id: current.id });
plan = await runner.plan(f.session, ['test']); job = await (await runner.start(f.session, plan.id)).promise; assert.equal(job.status, 'passed');
const observed = recordTurnProgress(f.store, f.session, run, null);
assert.equal(observed.delta.changed_files, 1); assert.equal(observed.delta.check_results, 1); assert.equal(observed.delta.requirement_evidence, 1);
assert.equal(inspectTurnProgress(f.store, f.session, run).evidence_verified, true);
});
test('receipt retention stays aligned at the cap and a foreign step cannot enter the Run', t => {
const f = fixture(t), run = beginPlanTask(f);
for (let i = 0; i < 43; i++) assert.ok(recordTurnProgress(f.store, f.session, run, null, i === 0 ? 'baseline' : 'settled'));
assert.equal(run.progressShadow.turns.length, 40); assert.equal(run.progressShadowArtifactIds.length, 40);
assert.equal([...f.store.core.artifact.values()].filter(row => row.kind === 'turn-progress-shadow').length, 43);
assert.equal(inspectTurnProgress(f.store, f.session, run).evidence_verified, true);
assert.equal(recordTurnProgress(f.store, f.session, run, { runId: 'foreign' }), null); assert.equal(run.progressShadow.observations, 43);
});
test('an actual approved long check records its owned running job as waiting before the original counted result', async t => {
const f = fixture(t); let requests = 0;
fs.writeFileSync(path.join(f.projectRoot, 'package.json'), JSON.stringify({ private: true, type: 'module', scripts: { test: 'node --test check.test.mjs' } }));
fs.writeFileSync(path.join(f.projectRoot, 'check.test.mjs'), "import test from 'node:test'; test('owned long check',async()=>{await new Promise(resolve=>setTimeout(resolve,750));});\n");
const model = await compatibleFixture(t, () => ({ body: ++requests === 1 ? completion([call('check-plan', 'plan_checks', { names: ['test'] })])
: requests === 2 ? completion([call('check-run', 'run_checks', { plan_id: [...f.store.core.check_plan.values()].at(-1).id })]) : completion([], '所属实际检查结果已保留。') }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-long-check', baseUrl: model.baseUrl, maxSteps: 4 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll()); f.onCleanup(() => runtime.checkRunner().stopAll());
runtime.start(f.session.id, '检查当前工程并解释实际检查结果。');
await until(() => f.session.status === 'awaiting_approval'); runtime.decide(f.session.id, f.session.approvals.at(-1).id, true);
const run = f.store.core.run.get(f.session.runId);
await until(() => run.progressShadow.turns.at(-1)?.waiting.some(row => row.kind === 'check_job'));
assert.equal(requests, 2); assert.equal(run.progressShadow.turns.at(-1).classification, 'waiting');
await runtime.active.get(f.session.id).promise;
assert.equal(requests, 3); assert.equal(f.session.status, 'completed'); assert.equal(run.stopReason, null);
assert.equal([...f.store.core.check_job.values()].at(-1).status, 'passed');
assert.ok(run.progressShadow.turns.some(row => row.delta.check_results === 1)); assertToolPairs(f.session.providerMessages);
});
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"edaf6fb0-eccb-423a-bb86-a2db36e499dc","stepId":null,"stepIndex":null,"phase":"baseline","classification":"baseline","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["existing_facts_not_run_progress"],"tools":[],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"e7026c14-7ea2-445d-a0be-e3df43858b53","stepId":"74667903-890c-4b22-9572-50d8fc119634","stepIndex":2,"phase":"settled","classification":"no_observed_change","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":[],"tools":[],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"e7026c14-7ea2-445d-a0be-e3df43858b53","stepId":"29bb7797-6453-4fdf-a320-4f89e9ea472e","stepIndex":1,"phase":"settled","classification":"evidence_growth","delta":{"read_characters":10,"new_sources":1,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":1,"repeated_failures":0,"other_observations":0},"reasons":["new_failure:permission","new_returned_file_or_artifact_range"],"tools":[{"id":"a2e9ca7d-b27e-4d3f-98c0-6c0d3a94fc9d","tool":"read_file","args_sha256":"57f642873864284fedb2d5c96e4642aa706c132084e9095afc40669fed376a12","result_artifact_id":"6fae1f81-24eb-4a87-a50d-d779f871416c","result_sha256":"63e9135badc0fff8baf8467c324533457b4f2f40d2341884526161f059a1a092"},{"id":"b2c45dbc-5dbb-4143-b0eb-bbbcb6c8033c","tool":"run_command","args_sha256":"193c90bd8b2ebb272b1fc48dc3ac1cb5a0e26531fa7de8b640c7584bd2c86fde","result_artifact_id":"2966ad74-4412-4b49-b364-f87a897edd46","result_sha256":"48f073c655039dd7910c0c7cafce446f747c01d3b6db4333773f6bf3575a4fe4"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"status":"denied","message":"命令未执行。","requires_verification":false}
@@ -0,0 +1 @@
{"error":{"message":"Owned shadow gateway failure, original response retained"}}
@@ -0,0 +1 @@
{"error":{"message":"Owned shadow gateway failure, original response retained"}}
@@ -0,0 +1 @@
{"path":"README.md","start_line":1,"end_line":3,"total_lines":4,"content":"project\n\nA","sha256":"ab097f769b6f141417493cdedfbe1c9c9cdb89c52c4b073eb9faf3c5f9ccf16d","bom":false,"truncated":true,"range_start_line":1,"range_end_line":4,"offset":10,"next_offset":20,"total_characters":56,"returned_characters":10,"requested_offset":10,"next_start_line":null,"budget_limited":false,"maximum_message_bytes":10122}
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"","tool_calls":[{"id":"page-3","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\",\"offset\":10,\"limit\":10}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"","tool_calls":[{"id":"page-2","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\",\"offset\":10,\"limit\":10}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"edaf6fb0-eccb-423a-bb86-a2db36e499dc","stepId":"cc3cbb2c-bf42-430d-8ad5-cc11ac46a413","stepIndex":2,"phase":"settled","classification":"evidence_growth","delta":{"read_characters":10,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["new_returned_file_or_artifact_range"],"tools":[{"id":"4381a70b-c3a3-44aa-9216-b93880680a5b","tool":"read_file","args_sha256":"de392539f5ca4139745447bc36ac152dd8bcdfc89ce8fcbc7dbc013c2965f6b5","result_artifact_id":"d4a5bc82-d2d1-4ba4-bc5c-a7c464642e90","result_sha256":"1f95df2aa97ee684bc0e6de9be76462e9b7e05a59889a59046fc5f23df07b4aa"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"ac5260fa-de91-49e6-96b0-c25711c305e9","runId":"e53c83e6-d7a7-4481-b57f-0eb241f77a92","stepId":"f789cb77-c8bc-43e8-be16-b6b90787a318","stepIndex":1,"phase":"settled","classification":"new_failure_evidence","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":1,"repeated_failures":0,"other_observations":0},"reasons":["new_failure:service"],"tools":[{"id":"d26dae46-5a78-4f11-85c9-701264aef40d","tool":"model_request","args_sha256":null,"result_artifact_id":"e7386127-2e81-4ade-b7db-50de4dbe16de","result_sha256":"fa8a0051f6cbf1ed03ac5fddae2dce449169dd64d317e644f7da5a318a20b93a","source_event_id":"4f0e8c40-abd0-4d99-bc81-ff7329d33a96","diagnostic_sha256":"cd1a31a249bf4558d1a6b22c858f462c5aabc9ecad8bd5bc6b19b18a625d6658"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"e7026c14-7ea2-445d-a0be-e3df43858b53","stepId":null,"stepIndex":null,"phase":"baseline","classification":"baseline","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["existing_facts_not_run_progress"],"tools":[],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"path":"README.md","start_line":1,"end_line":1,"total_lines":4,"content":"# Fixture ","sha256":"ab097f769b6f141417493cdedfbe1c9c9cdb89c52c4b073eb9faf3c5f9ccf16d","bom":false,"truncated":true,"range_start_line":1,"range_end_line":4,"offset":0,"next_offset":10,"total_characters":56,"returned_characters":10,"requested_offset":0,"next_start_line":null,"budget_limited":false,"maximum_message_bytes":1777}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"e7026c14-7ea2-445d-a0be-e3df43858b53","stepId":"29bb7797-6453-4fdf-a320-4f89e9ea472e","stepIndex":1,"phase":"waiting","classification":"waiting","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":[],"tools":[],"waiting":[{"kind":"approval","id":"7517a49f-54ce-4c53-9785-81745e09af87"}],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"ac5260fa-de91-49e6-96b0-c25711c305e9","runId":"e53c83e6-d7a7-4481-b57f-0eb241f77a92","stepId":null,"stepIndex":null,"phase":"baseline","classification":"baseline","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["existing_facts_not_run_progress"],"tools":[],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"path":"README.md","start_line":1,"end_line":1,"total_lines":4,"content":"# Fixture ","sha256":"ab097f769b6f141417493cdedfbe1c9c9cdb89c52c4b073eb9faf3c5f9ccf16d","bom":false,"truncated":true,"range_start_line":1,"range_end_line":4,"offset":0,"next_offset":10,"total_characters":56,"returned_characters":10,"requested_offset":0,"next_start_line":null,"budget_limited":false,"maximum_message_bytes":13470}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"edaf6fb0-eccb-423a-bb86-a2db36e499dc","stepId":"fc15864d-79c2-4167-be33-9ac8d2a15ee4","stepIndex":1,"phase":"settled","classification":"evidence_growth","delta":{"read_characters":10,"new_sources":1,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["new_returned_file_or_artifact_range"],"tools":[{"id":"41455faf-7608-4fe5-892c-f1d2f2c9ac20","tool":"read_file","args_sha256":"727fdc5847869fcd031284e34ccab1128e64364fb1dd0b94feb10563b1e7b698","result_artifact_id":"95ab5551-42c5-4524-bd3f-37b1337f5754","result_sha256":"cfd27074ea75245cc0f0b1e0179f0b2e22c0dc3e8d8567513250070343840394"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"path":"README.md","start_line":1,"end_line":3,"total_lines":4,"content":"project\n\nA","sha256":"ab097f769b6f141417493cdedfbe1c9c9cdb89c52c4b073eb9faf3c5f9ccf16d","bom":false,"truncated":true,"range_start_line":1,"range_end_line":4,"offset":10,"next_offset":20,"total_characters":56,"returned_characters":10,"requested_offset":10,"next_start_line":null,"budget_limited":false,"maximum_message_bytes":10965}
@@ -0,0 +1,98 @@
# 项目交付报告
**需要实际工程检查**
生成时间:2026-11-04T03:16:52.097Z
项目:project
项目目录:D:\Ai-project\REA逆向\Agent-Workbench\.qa\test-t4tzVx\project
Task:32d72485-2faf-4435-ba9f-172943b9b0da
## 任务与范围
只研究README.md原说明,不修改文件;本机固定分页观察夹具。
源码指纹:240a01eff2062c68abfd0ce08eea6ee6a39dc0cafb6d7da4c74806cfe09f357e
当前Git HEAD:未启用
分支:未记录
源码和检查证据不代替业务需求验收。
## 改动
| 文件 | 状态 | SHA256 |
| --- | --- | --- |
仅本任务实际应用的文件可进入Git交付预览。
## 用户要求与证据
证据核对只证明所选范围;模型完成答复不等于业务验收。
复核状态:not_recorded
| 要求 / 条件 | 用户原文来源 | 修订 | 复核状态 | 原证据 / 下一步 |
| --- | --- | --- | --- | --- |
尚未审阅的用户来源:32d72485-2faf-4435-ba9f-172943b9b0da、469b7f63-e76b-4935-bb46-9229cc88cd5e
## 单轮观察(仅记录)
外显事实分类不改变停止、权限或预算;不是自主交付收益证明。
| Run / 轮次 | 观察 | 新读取字符 | 重复读取 | 新失败 / 重复失败 | 原收据核对 |
| --- | --- | --- | --- | --- | --- |
| edaf6fb0-eccb-423a-bb86-a2db36e499dc / baseline | baseline | 0 | 0 | 0 / 0 | 原字节已核对 |
| edaf6fb0-eccb-423a-bb86-a2db36e499dc / 1 | evidence_growth | 10 | 0 | 0 / 0 | 原字节已核对 |
| edaf6fb0-eccb-423a-bb86-a2db36e499dc / 2 | evidence_growth | 10 | 0 | 0 / 0 | 原字节已核对 |
| edaf6fb0-eccb-423a-bb86-a2db36e499dc / 3 | repeated_read_candidate | 0 | 1 | 0 / 0 | 原字节已核对 |
| e7026c14-7ea2-445d-a0be-e3df43858b53 / baseline | baseline | 0 | 0 | 0 / 0 | 原字节已核对 |
| e7026c14-7ea2-445d-a0be-e3df43858b53 / 1 | waiting | 0 | 0 | 0 / 0 | 原字节已核对 |
| e7026c14-7ea2-445d-a0be-e3df43858b53 / 1 | evidence_growth | 10 | 0 | 1 / 0 | 原字节已核对 |
| e7026c14-7ea2-445d-a0be-e3df43858b53 / 2 | no_observed_change | 0 | 0 | 0 / 0 | 原字节已核对 |
## 实际检查
| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |
| --- | --- | --- | --- | --- |
## Git交付
尚无内置Git提交记录。
## 模型与用量
Run型号为启动配置;每次实际发送与返回型号见下表。型号标识或登记映射不认证底层模型权重。
| Run | 启动型号 | 状态 | 已报告tokens |
| --- | --- | --- | --- |
| edaf6fb0-eccb-423a-bb86-a2db36e499dc | owned-shadow-ui | paused | 504 |
| e7026c14-7ea2-445d-a0be-e3df43858b53 | owned-shadow-ui | completed | 336 |
| 尝试 | 请求型号 | 上游报告型号 | 核对结果 | 原响应 SHA256 |
| --- | --- | --- | --- | --- |
| 14878126-0d70-4d2c-8db9-57a2a20fa6f5 | owned-shadow-ui | 未记录 | 上游未报告型号 | 6bf86234841f0a8e301a03a01511b25e7b9462a951a63da98ba41cc399979257 |
| 4aea2345-f742-4fa1-9f23-43f0261adf0f | owned-shadow-ui | 未记录 | 上游未报告型号 | 766649c120a7ff239291c671bb33614d92930d7b11bb1e0ba200762021573482 |
| b3340581-5a71-4ded-b0e4-2ca03fdf4f0b | owned-shadow-ui | 未记录 | 上游未报告型号 | 0b95de8795765e496951221843b56799b1a7869cdead9a80cf46a39983e710ca |
| 0b7da5c5-091c-41ea-a5f8-80aa8d78db34 | owned-shadow-ui | 未记录 | 上游未报告型号 | 7559c0ea5e206ebbca81c12dcf83cf367f1ce4aaf041f9fd66da19f3b5af4ed5 |
| 4f8e6f42-e685-4985-959c-6a6eecfa7352 | owned-shadow-ui | 未记录 | 上游未报告型号 | 1533d54eb3cfa022035842742f6595b3885675db8019909517d655c95b8e8510 |
累计已报告:840 tokens;未报告请求:0。费用:未知。
## 请求上下文
| 请求 | 状态 | 输入估算 | 已报告输入 | 省略组 | 正文SHA256校验 |
| --- | --- | --- | --- | --- | --- |
| d4742c07-ffd8-48ab-bc77-600e656c07c1 | completed | 7274 | 123 | 0 | 3cbfa2728047ffc0ff6abb49bc20939d88f45ff331c1d12ba8fa8b4091ff7c44 |
| e49b6945-6f85-4bc6-8052-c4d4a12595a1 | completed | 7941 | 123 | 0 | f399012d337513a9c86a3cce235a67fc43ef8947ba135e1f07b5f5b0ca3cff40 |
| 55cb8b37-8a7f-4c50-9230-0669189eb0dc | completed | 8409 | 123 | 0 | 4f6b1be6c3936b53f94241e0e2329fb3835e884655e86d8fde3f1315cdfb0a5a |
| dcd2cb39-036a-4ab1-8002-0088a2f6a5b0 | completed | 8772 | 123 | 0 | 6f44cd5202e0e939b2bfc3284889ac2fb97be026b7d53f26ea377136e72dec33 |
| f7a06908-bffd-4049-9142-3ba3c9334f3e | completed | 9445 | 123 | 0 | e72ed1accc904b1d39941b0594037023edbd32d32803b20a8ac47d797f28cf18 |
## 尚待确认
- 本切片验证已选工程检查和提交范围;业务需求验收另行记录。
- 提交为本地普通提交,不执行仓库hooks和GPG签名。
- 请求输入为本地UTF-8估算;服务实际分词和用量另行记录。
- 未配置模型单价,费用未知。
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"原审批已拒绝,说明与原工具结果保留。"},"finish_reason":"stop"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
@@ -0,0 +1 @@
{"error":{"message":"Owned shadow gateway failure, original response retained"}}
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"","tool_calls":[{"id":"read-before-approval","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\",\"limit\":10}"}},{"id":"owned-command","type":"function","function":{"name":"run_command","arguments":"{\"command\":\"node --version\",\"reason\":\"所属只读环境检查,需原审批\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"32d72485-2faf-4435-ba9f-172943b9b0da","runId":"edaf6fb0-eccb-423a-bb86-a2db36e499dc","stepId":"351821a6-dd23-464a-ba51-2ff70f39dfe5","stepIndex":3,"phase":"settled","classification":"repeated_read_candidate","delta":{"read_characters":0,"new_sources":0,"repeated_reads":1,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["same_sha_range_already_returned"],"tools":[{"id":"94008aa0-f298-4b7f-a8ad-f2f821ea18c0","tool":"read_file","args_sha256":"de392539f5ca4139745447bc36ac152dd8bcdfc89ce8fcbc7dbc013c2965f6b5","result_artifact_id":"48589b61-95f2-43ea-bf4b-b445f4a5e2d8","result_sha256":"a4b57371daddf6f29e63ffe399a5b4e8789b81a325315f940517f6a2791b096f"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"","tool_calls":[{"id":"page-1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\",\"offset\":0,\"limit\":10}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,975 @@
{
"schemaVersion": 1,
"kind": "engineering-delivery",
"generatedAt": "2026-11-04T03:16:52.097Z",
"status": "needs_checks",
"statusLabel": "需要实际工程检查",
"project": {
"id": "05499550-b5b3-456e-8780-dc66a6c1f10f",
"name": "project",
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\test-t4tzVx\\project"
},
"workspace": {
"kind": "local-project",
"projectId": "05499550-b5b3-456e-8780-dc66a6c1f10f",
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\test-t4tzVx\\project"
},
"task": {
"id": "32d72485-2faf-4435-ba9f-172943b9b0da",
"goal": "只研究README.md原说明,不修改文件;本机固定分页观察夹具。",
"status": "completed",
"instructions": [
{
"id": "469b7f63-e76b-4935-bb46-9229cc88cd5e",
"content": "继续核对所属环境;命令只经原审批执行。",
"createdAt": "2026-11-04T03:16:48.631Z",
"source": "user"
}
],
"acceptance": [],
"contract": {
"schemaVersion": 1,
"goal": "只研究README.md原说明,不修改文件;本机固定分页观察夹具。",
"kind": "general",
"checks": "unspecified"
},
"delivery": null,
"workspaceIdentity": {
"kind": "local-project",
"projectId": "05499550-b5b3-456e-8780-dc66a6c1f10f",
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\test-t4tzVx\\project"
},
"requirementsAcceptance": "not_recorded",
"note": "源码和检查证据不代替业务需求验收。"
},
"requirements": {
"configured": false,
"task_id": "32d72485-2faf-4435-ba9f-172943b9b0da",
"revision": 0,
"sources": [
{
"kind": "goal",
"id": "32d72485-2faf-4435-ba9f-172943b9b0da",
"text": "只研究README.md原说明,不修改文件;本机固定分页观察夹具。",
"at": "2026-11-04T03:16:42.886Z",
"sha256": "522af64f260c8cb48c9c4654b3db5bdffd2bb55d1d1656150fe506aaad756204"
},
{
"kind": "instruction",
"id": "469b7f63-e76b-4935-bb46-9229cc88cd5e",
"text": "继续核对所属环境;命令只经原审批执行。",
"at": "2026-11-04T03:16:48.631Z",
"sha256": "4eb7c2c1cdc682a17820a54813d481160a63d4b91aa71ed2c06ad067e4d02830"
}
],
"items": [],
"all_resolved": false,
"binding_sha256": null,
"note": "证据核对只证明所选范围;模型完成答复不等于业务验收。",
"status": "not_recorded",
"unreviewed_sources": [
"32d72485-2faf-4435-ba9f-172943b9b0da",
"469b7f63-e76b-4935-bb46-9229cc88cd5e"
]
},
"turnObservations": [
{
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"mode": "shadow",
"recorded": true,
"observations": 4,
"truncated": false,
"turns": [
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"stepId": null,
"stepIndex": null,
"phase": "baseline",
"classification": "baseline",
"delta": {
"read_characters": 0,
"new_sources": 0,
"repeated_reads": 0,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 0,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [
"existing_facts_not_run_progress"
],
"tools": [],
"waiting": [],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
},
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"stepId": "fc15864d-79c2-4167-be33-9ac8d2a15ee4",
"stepIndex": 1,
"phase": "settled",
"classification": "evidence_growth",
"delta": {
"read_characters": 10,
"new_sources": 1,
"repeated_reads": 0,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 0,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [
"new_returned_file_or_artifact_range"
],
"tools": [
{
"id": "41455faf-7608-4fe5-892c-f1d2f2c9ac20",
"tool": "read_file",
"args_sha256": "727fdc5847869fcd031284e34ccab1128e64364fb1dd0b94feb10563b1e7b698",
"result_artifact_id": "95ab5551-42c5-4524-bd3f-37b1337f5754",
"result_sha256": "cfd27074ea75245cc0f0b1e0179f0b2e22c0dc3e8d8567513250070343840394"
}
],
"waiting": [],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
},
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"stepId": "cc3cbb2c-bf42-430d-8ad5-cc11ac46a413",
"stepIndex": 2,
"phase": "settled",
"classification": "evidence_growth",
"delta": {
"read_characters": 10,
"new_sources": 0,
"repeated_reads": 0,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 0,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [
"new_returned_file_or_artifact_range"
],
"tools": [
{
"id": "4381a70b-c3a3-44aa-9216-b93880680a5b",
"tool": "read_file",
"args_sha256": "de392539f5ca4139745447bc36ac152dd8bcdfc89ce8fcbc7dbc013c2965f6b5",
"result_artifact_id": "d4a5bc82-d2d1-4ba4-bc5c-a7c464642e90",
"result_sha256": "1f95df2aa97ee684bc0e6de9be76462e9b7e05a59889a59046fc5f23df07b4aa"
}
],
"waiting": [],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
},
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"stepId": "351821a6-dd23-464a-ba51-2ff70f39dfe5",
"stepIndex": 3,
"phase": "settled",
"classification": "repeated_read_candidate",
"delta": {
"read_characters": 0,
"new_sources": 0,
"repeated_reads": 1,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 0,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [
"same_sha_range_already_returned"
],
"tools": [
{
"id": "94008aa0-f298-4b7f-a8ad-f2f821ea18c0",
"tool": "read_file",
"args_sha256": "de392539f5ca4139745447bc36ac152dd8bcdfc89ce8fcbc7dbc013c2965f6b5",
"result_artifact_id": "48589b61-95f2-43ea-bf4b-b445f4a5e2d8",
"result_sha256": "a4b57371daddf6f29e63ffe399a5b4e8789b81a325315f940517f6a2791b096f"
}
],
"waiting": [],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
}
],
"artifact_ids": [
"092aaf76-1965-4bba-aeca-0703bb192ca9",
"9d61022a-cf8d-47ff-89f8-086b4ebc0d5e",
"66fa991a-75cd-48a0-90d1-7d8d8454f93c",
"f5d28be9-4a65-424c-9722-356de6251013"
],
"evidence_verified": true,
"error": null
},
{
"runId": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"mode": "shadow",
"recorded": true,
"observations": 4,
"truncated": false,
"turns": [
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"stepId": null,
"stepIndex": null,
"phase": "baseline",
"classification": "baseline",
"delta": {
"read_characters": 0,
"new_sources": 0,
"repeated_reads": 0,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 0,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [
"existing_facts_not_run_progress"
],
"tools": [],
"waiting": [],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
},
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"stepId": "29bb7797-6453-4fdf-a320-4f89e9ea472e",
"stepIndex": 1,
"phase": "waiting",
"classification": "waiting",
"delta": {
"read_characters": 0,
"new_sources": 0,
"repeated_reads": 0,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 0,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [],
"tools": [],
"waiting": [
{
"kind": "approval",
"id": "7517a49f-54ce-4c53-9785-81745e09af87"
}
],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
},
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"stepId": "29bb7797-6453-4fdf-a320-4f89e9ea472e",
"stepIndex": 1,
"phase": "settled",
"classification": "evidence_growth",
"delta": {
"read_characters": 10,
"new_sources": 1,
"repeated_reads": 0,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 1,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [
"new_failure:permission",
"new_returned_file_or_artifact_range"
],
"tools": [
{
"id": "a2e9ca7d-b27e-4d3f-98c0-6c0d3a94fc9d",
"tool": "read_file",
"args_sha256": "57f642873864284fedb2d5c96e4642aa706c132084e9095afc40669fed376a12",
"result_artifact_id": "6fae1f81-24eb-4a87-a50d-d779f871416c",
"result_sha256": "63e9135badc0fff8baf8467c324533457b4f2f40d2341884526161f059a1a092"
},
{
"id": "b2c45dbc-5dbb-4143-b0eb-bbbcb6c8033c",
"tool": "run_command",
"args_sha256": "193c90bd8b2ebb272b1fc48dc3ac1cb5a0e26531fa7de8b640c7584bd2c86fde",
"result_artifact_id": "2966ad74-4412-4b49-b364-f87a897edd46",
"result_sha256": "48f073c655039dd7910c0c7cafce446f747c01d3b6db4333773f6bf3575a4fe4"
}
],
"waiting": [],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
},
{
"schemaVersion": 1,
"mode": "shadow",
"taskId": "32d72485-2faf-4435-ba9f-172943b9b0da",
"runId": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"stepId": "74667903-890c-4b22-9572-50d8fc119634",
"stepIndex": 2,
"phase": "settled",
"classification": "no_observed_change",
"delta": {
"read_characters": 0,
"new_sources": 0,
"repeated_reads": 0,
"changed_files": 0,
"check_results": 0,
"requirement_evidence": 0,
"user_boundaries": 0,
"new_failures": 0,
"repeated_failures": 0,
"other_observations": 0
},
"reasons": [],
"tools": [],
"waiting": [],
"truncated": false,
"note": "外显事实观察;不等于业务交付,不改变停止、权限或预算。"
}
],
"artifact_ids": [
"68a33b41-d912-40de-9d92-07bed0c5a23d",
"77c897d6-1930-4299-ab6e-88fa801d0e16",
"24f5eea8-d2eb-4697-9ad6-7220d99e09a0",
"1d5be588-b616-4a0d-9553-477d9a821ce9"
],
"evidence_verified": true,
"error": null
}
],
"fileResults": [],
"fileDelivery": {
"satisfied": false,
"requiresChange": false,
"missingPaths": [],
"status": "existing_verified",
"paths": [],
"resultIds": [],
"newChanges": 0,
"stale": []
},
"checkPolicy": "unspecified",
"gitOutcome": {
"status": "uncommitted",
"note": "仅本任务实际应用的文件可进入Git交付预览。"
},
"source": {
"fingerprint": "240a01eff2062c68abfd0ce08eea6ee6a39dc0cafb6d7da4c74806cfe09f357e",
"scope": {
"complete": true,
"scannedFiles": 1,
"bytes": 56,
"excludedFiles": 0,
"maximumFiles": 1000,
"maximumBytes": 16777216,
"note": "有界快照;Git工程遵循ignore并包含未跟踪源码,跳过依赖、链接和常见凭据路径。"
},
"gitHead": null,
"branch": null
},
"runs": [
{
"id": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"resumeOf": null,
"engine": "workbench",
"status": "paused",
"model": {
"mode": "compatible",
"baseUrl": "http://127.0.0.1:53141/v1",
"model": "owned-shadow-ui",
"contextLimit": 16000,
"maxOutputTokens": 2048,
"configRevision": 2,
"modelResponseTimeoutMs": 300000,
"modelStreamIdleTimeoutMs": 120000
},
"startedAt": "2026-11-04T03:16:42.887Z",
"finishedAt": "2026-11-04T03:16:47.806Z",
"usage": {
"requests": 3,
"inputTokens": 369,
"outputTokens": 135,
"totalTokens": 504,
"unknownRequests": 0,
"estimatedUnknownTokens": 0
},
"stopReason": "step_limit",
"consumption": [
{
"attemptId": "14878126-0d70-4d2c-8db9-57a2a20fa6f5",
"requestId": "d4742c07-ffd8-48ab-bc77-600e656c07c1",
"connectionId": null,
"connectionName": null,
"model": "owned-shadow-ui",
"endpoint": "http://127.0.0.1:53141/v1",
"protocol": "chat-completions",
"requestUrl": "http://127.0.0.1:53141/v1/chat/completions",
"responseUrl": "http://127.0.0.1:53141/v1/chat/completions",
"redirected": false,
"redirectMode": "manual",
"startedAt": "2026-11-04T03:16:43.899Z",
"finishedAt": "2026-11-04T03:16:44.257Z",
"outcome": "completed",
"usageStatus": "reported",
"usage": {
"prompt_tokens": 123,
"completion_tokens": 45,
"total_tokens": 168
},
"localEstimate": {
"schemaVersion": 1,
"inputTokens": 7274,
"outputTokens": 2048,
"requestSha256": "3cbfa2728047ffc0ff6abb49bc20939d88f45ff331c1d12ba8fa8b4091ff7c44",
"requestBytes": 20670,
"estimateMethod": "utf8-third-plus-framing-v1"
},
"modelIdentity": {
"schemaVersion": 1,
"requestedModel": "owned-shadow-ui",
"reportedModels": [],
"status": "missing",
"complete": true,
"invalidIdentifiers": false,
"policy": "record",
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
"responseSource": {
"artifactId": "fc522ade-162a-436b-ac45-248d7fe1fc88",
"sha256": "6bf86234841f0a8e301a03a01511b25e7b9462a951a63da98ba41cc399979257",
"sessionId": "43550063-8c3f-4b53-8647-a7ad9b8132db",
"scope": "http-body"
}
},
"estimatedUnknownTokens": 0
},
{
"attemptId": "4aea2345-f742-4fa1-9f23-43f0261adf0f",
"requestId": "e49b6945-6f85-4bc6-8052-c4d4a12595a1",
"connectionId": null,
"connectionName": null,
"model": "owned-shadow-ui",
"endpoint": "http://127.0.0.1:53141/v1",
"protocol": "chat-completions",
"requestUrl": "http://127.0.0.1:53141/v1/chat/completions",
"responseUrl": "http://127.0.0.1:53141/v1/chat/completions",
"redirected": false,
"redirectMode": "manual",
"startedAt": "2026-11-04T03:16:45.107Z",
"finishedAt": "2026-11-04T03:16:45.448Z",
"outcome": "completed",
"usageStatus": "reported",
"usage": {
"prompt_tokens": 123,
"completion_tokens": 45,
"total_tokens": 168
},
"localEstimate": {
"schemaVersion": 1,
"inputTokens": 7941,
"outputTokens": 2048,
"requestSha256": "f399012d337513a9c86a3cce235a67fc43ef8947ba135e1f07b5f5b0ca3cff40",
"requestBytes": 22622,
"estimateMethod": "utf8-third-plus-framing-v1"
},
"modelIdentity": {
"schemaVersion": 1,
"requestedModel": "owned-shadow-ui",
"reportedModels": [],
"status": "missing",
"complete": true,
"invalidIdentifiers": false,
"policy": "record",
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
"responseSource": {
"artifactId": "5f5b6455-2c3a-4a33-8998-0e29f6ac0b1b",
"sha256": "766649c120a7ff239291c671bb33614d92930d7b11bb1e0ba200762021573482",
"sessionId": "43550063-8c3f-4b53-8647-a7ad9b8132db",
"scope": "http-body"
}
},
"estimatedUnknownTokens": 0
},
{
"attemptId": "b3340581-5a71-4ded-b0e4-2ca03fdf4f0b",
"requestId": "55cb8b37-8a7f-4c50-9230-0669189eb0dc",
"connectionId": null,
"connectionName": null,
"model": "owned-shadow-ui",
"endpoint": "http://127.0.0.1:53141/v1",
"protocol": "chat-completions",
"requestUrl": "http://127.0.0.1:53141/v1/chat/completions",
"responseUrl": "http://127.0.0.1:53141/v1/chat/completions",
"redirected": false,
"redirectMode": "manual",
"startedAt": "2026-11-04T03:16:46.175Z",
"finishedAt": "2026-11-04T03:16:46.639Z",
"outcome": "completed",
"usageStatus": "reported",
"usage": {
"prompt_tokens": 123,
"completion_tokens": 45,
"total_tokens": 168
},
"localEstimate": {
"schemaVersion": 1,
"inputTokens": 8409,
"outputTokens": 2048,
"requestSha256": "4f6b1be6c3936b53f94241e0e2329fb3835e884655e86d8fde3f1315cdfb0a5a",
"requestBytes": 23978,
"estimateMethod": "utf8-third-plus-framing-v1"
},
"modelIdentity": {
"schemaVersion": 1,
"requestedModel": "owned-shadow-ui",
"reportedModels": [],
"status": "missing",
"complete": true,
"invalidIdentifiers": false,
"policy": "record",
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
"responseSource": {
"artifactId": "5d73c914-1347-48df-b55d-c86fe12b7512",
"sha256": "0b95de8795765e496951221843b56799b1a7869cdead9a80cf46a39983e710ca",
"sessionId": "43550063-8c3f-4b53-8647-a7ad9b8132db",
"scope": "http-body"
}
},
"estimatedUnknownTokens": 0
}
],
"workspaceIdentity": {
"kind": "local-project",
"projectId": "05499550-b5b3-456e-8780-dc66a6c1f10f",
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\test-t4tzVx\\project"
}
},
{
"id": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"resumeOf": null,
"engine": "workbench",
"status": "completed",
"model": {
"mode": "compatible",
"baseUrl": "http://127.0.0.1:53141/v1",
"model": "owned-shadow-ui",
"contextLimit": 16000,
"maxOutputTokens": 2048,
"configRevision": 2,
"modelResponseTimeoutMs": 300000,
"modelStreamIdleTimeoutMs": 120000
},
"startedAt": "2026-11-04T03:16:48.631Z",
"finishedAt": "2026-11-04T03:16:51.680Z",
"usage": {
"requests": 2,
"inputTokens": 246,
"outputTokens": 90,
"totalTokens": 336,
"unknownRequests": 0,
"estimatedUnknownTokens": 0
},
"stopReason": null,
"consumption": [
{
"attemptId": "0b7da5c5-091c-41ea-a5f8-80aa8d78db34",
"requestId": "dcd2cb39-036a-4ab1-8002-0088a2f6a5b0",
"connectionId": null,
"connectionName": null,
"model": "owned-shadow-ui",
"endpoint": "http://127.0.0.1:53141/v1",
"protocol": "chat-completions",
"requestUrl": "http://127.0.0.1:53141/v1/chat/completions",
"responseUrl": "http://127.0.0.1:53141/v1/chat/completions",
"redirected": false,
"redirectMode": "manual",
"startedAt": "2026-11-04T03:16:49.111Z",
"finishedAt": "2026-11-04T03:16:49.472Z",
"outcome": "completed",
"usageStatus": "reported",
"usage": {
"prompt_tokens": 123,
"completion_tokens": 45,
"total_tokens": 168
},
"localEstimate": {
"schemaVersion": 1,
"inputTokens": 8772,
"outputTokens": 2048,
"requestSha256": "6f44cd5202e0e939b2bfc3284889ac2fb97be026b7d53f26ea377136e72dec33",
"requestBytes": 24996,
"estimateMethod": "utf8-third-plus-framing-v1"
},
"modelIdentity": {
"schemaVersion": 1,
"requestedModel": "owned-shadow-ui",
"reportedModels": [],
"status": "missing",
"complete": true,
"invalidIdentifiers": false,
"policy": "record",
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
"responseSource": {
"artifactId": "ebd78899-c0c4-485f-8c1f-446a6b338b50",
"sha256": "7559c0ea5e206ebbca81c12dcf83cf367f1ce4aaf041f9fd66da19f3b5af4ed5",
"sessionId": "43550063-8c3f-4b53-8647-a7ad9b8132db",
"scope": "http-body"
}
},
"estimatedUnknownTokens": 0
},
{
"attemptId": "4f8e6f42-e685-4985-959c-6a6eecfa7352",
"requestId": "f7a06908-bffd-4049-9142-3ba3c9334f3e",
"connectionId": null,
"connectionName": null,
"model": "owned-shadow-ui",
"endpoint": "http://127.0.0.1:53141/v1",
"protocol": "chat-completions",
"requestUrl": "http://127.0.0.1:53141/v1/chat/completions",
"responseUrl": "http://127.0.0.1:53141/v1/chat/completions",
"redirected": false,
"redirectMode": "manual",
"startedAt": "2026-11-04T03:16:50.881Z",
"finishedAt": "2026-11-04T03:16:51.254Z",
"outcome": "completed",
"usageStatus": "reported",
"usage": {
"prompt_tokens": 123,
"completion_tokens": 45,
"total_tokens": 168
},
"localEstimate": {
"schemaVersion": 1,
"inputTokens": 9445,
"outputTokens": 2048,
"requestSha256": "e72ed1accc904b1d39941b0594037023edbd32d32803b20a8ac47d797f28cf18",
"requestBytes": 26942,
"estimateMethod": "utf8-third-plus-framing-v1"
},
"modelIdentity": {
"schemaVersion": 1,
"requestedModel": "owned-shadow-ui",
"reportedModels": [],
"status": "missing",
"complete": true,
"invalidIdentifiers": false,
"policy": "record",
"scope": "Identifiers in the outgoing request and upstream response; neither equal identifiers nor a declared mapping authenticate model weights.",
"responseSource": {
"artifactId": "dafb6a9b-da55-40d5-9842-71ccc7d75590",
"sha256": "1533d54eb3cfa022035842742f6595b3885675db8019909517d655c95b8e8510",
"sessionId": "43550063-8c3f-4b53-8647-a7ad9b8132db",
"scope": "http-body"
}
},
"estimatedUnknownTokens": 0
}
],
"workspaceIdentity": {
"kind": "local-project",
"projectId": "05499550-b5b3-456e-8780-dc66a6c1f10f",
"root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\test-t4tzVx\\project"
}
}
],
"usage": {
"requests": 5,
"inputTokens": 615,
"outputTokens": 225,
"totalTokens": 840,
"unknownRequests": 0,
"estimatedUnknownTokens": 0,
"priceStatus": "not_configured",
"amount": null,
"currency": null
},
"changes": [],
"changeSets": [],
"contextPlans": [
{
"id": "d4742c07-ffd8-48ab-bc77-600e656c07c1",
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"stepId": "fc15864d-79c2-4167-be33-9ac8d2a15ee4",
"status": "completed",
"requestSha256": "3cbfa2728047ffc0ff6abb49bc20939d88f45ff331c1d12ba8fa8b4091ff7c44",
"requestBytes": 20670,
"requestArtifactId": "f6f6333f-3fd1-49db-8524-90f523ef90e3",
"planArtifactId": "65daf065-21ad-42b4-9c32-79648c6e004a",
"estimatedInputTokens": 7274,
"beforeInputTokens": 7274,
"beforeBytes": 20670,
"estimateMethod": "utf8-third-plus-framing-v1",
"budget": {
"contextLimit": 16000,
"outputReservation": 2048,
"safetyTokens": 1600,
"inputBudget": 12352,
"targetInputTokens": 12352,
"runRemainingTokens": 200000,
"taskRemainingTokens": 1000000,
"limitingReason": "context_limit"
},
"archivedGroups": 0,
"retainedMessages": 1,
"actualUsage": {
"prompt_tokens": 123,
"completion_tokens": 45
},
"requestAttempts": 1,
"historyIndexArtifactId": null,
"historyIndexSha256": null,
"workingSetArtifactId": null,
"workingSetSha256": null,
"workingSetEntries": 0,
"workingSetViewVersion": 4,
"workingRetentionTokens": 0,
"latestToolsArtifactId": null,
"latestToolsSha256": null,
"latestToolsEntries": 0,
"evidenceVerified": true,
"evidenceError": null
},
{
"id": "e49b6945-6f85-4bc6-8052-c4d4a12595a1",
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"stepId": "cc3cbb2c-bf42-430d-8ad5-cc11ac46a413",
"status": "completed",
"requestSha256": "f399012d337513a9c86a3cce235a67fc43ef8947ba135e1f07b5f5b0ca3cff40",
"requestBytes": 22622,
"requestArtifactId": "edfe9b80-8cbe-466d-bd8a-194170317422",
"planArtifactId": "052d0db7-9001-4cba-998d-bb18a9f67d4d",
"estimatedInputTokens": 7941,
"beforeInputTokens": 7941,
"beforeBytes": 22622,
"estimateMethod": "utf8-third-plus-framing-v1",
"budget": {
"contextLimit": 16000,
"outputReservation": 2048,
"safetyTokens": 1600,
"inputBudget": 12352,
"targetInputTokens": 12352,
"runRemainingTokens": 199832,
"taskRemainingTokens": 999832,
"limitingReason": "context_limit"
},
"archivedGroups": 0,
"retainedMessages": 3,
"actualUsage": {
"prompt_tokens": 123,
"completion_tokens": 45
},
"requestAttempts": 1,
"historyIndexArtifactId": null,
"historyIndexSha256": null,
"workingSetArtifactId": null,
"workingSetSha256": null,
"workingSetEntries": 0,
"workingSetViewVersion": 4,
"workingRetentionTokens": 0,
"latestToolsArtifactId": null,
"latestToolsSha256": null,
"latestToolsEntries": 0,
"evidenceVerified": true,
"evidenceError": null
},
{
"id": "55cb8b37-8a7f-4c50-9230-0669189eb0dc",
"runId": "edaf6fb0-eccb-423a-bb86-a2db36e499dc",
"stepId": "351821a6-dd23-464a-ba51-2ff70f39dfe5",
"status": "completed",
"requestSha256": "4f6b1be6c3936b53f94241e0e2329fb3835e884655e86d8fde3f1315cdfb0a5a",
"requestBytes": 23978,
"requestArtifactId": "25bb6bbb-4b03-4257-a282-39a7b8b5d0f9",
"planArtifactId": "a5484481-2440-448a-b6fd-29172c5ed25b",
"estimatedInputTokens": 8409,
"beforeInputTokens": 8409,
"beforeBytes": 23978,
"estimateMethod": "utf8-third-plus-framing-v1",
"budget": {
"contextLimit": 16000,
"outputReservation": 2048,
"safetyTokens": 1600,
"inputBudget": 12352,
"targetInputTokens": 12352,
"runRemainingTokens": 199664,
"taskRemainingTokens": 999664,
"limitingReason": "context_limit"
},
"archivedGroups": 0,
"retainedMessages": 5,
"actualUsage": {
"prompt_tokens": 123,
"completion_tokens": 45
},
"requestAttempts": 1,
"historyIndexArtifactId": null,
"historyIndexSha256": null,
"workingSetArtifactId": null,
"workingSetSha256": null,
"workingSetEntries": 0,
"workingSetViewVersion": 4,
"workingRetentionTokens": 0,
"latestToolsArtifactId": null,
"latestToolsSha256": null,
"latestToolsEntries": 0,
"evidenceVerified": true,
"evidenceError": null
},
{
"id": "dcd2cb39-036a-4ab1-8002-0088a2f6a5b0",
"runId": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"stepId": "29bb7797-6453-4fdf-a320-4f89e9ea472e",
"status": "completed",
"requestSha256": "6f44cd5202e0e939b2bfc3284889ac2fb97be026b7d53f26ea377136e72dec33",
"requestBytes": 24996,
"requestArtifactId": "b2e601ff-5372-41d1-85c6-dc9535a20d05",
"planArtifactId": "de4d5ca6-1a42-4af8-836a-75a616b9f23e",
"estimatedInputTokens": 8772,
"beforeInputTokens": 8772,
"beforeBytes": 24996,
"estimateMethod": "utf8-third-plus-framing-v1",
"budget": {
"contextLimit": 16000,
"outputReservation": 2048,
"safetyTokens": 1600,
"inputBudget": 12352,
"targetInputTokens": 12352,
"runRemainingTokens": 200000,
"taskRemainingTokens": 999496,
"limitingReason": "context_limit"
},
"archivedGroups": 0,
"retainedMessages": 8,
"actualUsage": {
"prompt_tokens": 123,
"completion_tokens": 45
},
"requestAttempts": 1,
"historyIndexArtifactId": null,
"historyIndexSha256": null,
"workingSetArtifactId": null,
"workingSetSha256": null,
"workingSetEntries": 0,
"workingSetViewVersion": 4,
"workingRetentionTokens": 0,
"latestToolsArtifactId": null,
"latestToolsSha256": null,
"latestToolsEntries": 0,
"evidenceVerified": true,
"evidenceError": null
},
{
"id": "f7a06908-bffd-4049-9142-3ba3c9334f3e",
"runId": "e7026c14-7ea2-445d-a0be-e3df43858b53",
"stepId": "74667903-890c-4b22-9572-50d8fc119634",
"status": "completed",
"requestSha256": "e72ed1accc904b1d39941b0594037023edbd32d32803b20a8ac47d797f28cf18",
"requestBytes": 26942,
"requestArtifactId": "6dcbb387-eb1c-4a6d-900d-80bb6b87027b",
"planArtifactId": "d9819700-718e-4241-a409-1d16d36a6b1c",
"estimatedInputTokens": 9445,
"beforeInputTokens": 9445,
"beforeBytes": 26942,
"estimateMethod": "utf8-third-plus-framing-v1",
"budget": {
"contextLimit": 16000,
"outputReservation": 2048,
"safetyTokens": 1600,
"inputBudget": 12352,
"targetInputTokens": 12352,
"runRemainingTokens": 199832,
"taskRemainingTokens": 999328,
"limitingReason": "context_limit"
},
"archivedGroups": 0,
"retainedMessages": 11,
"actualUsage": {
"prompt_tokens": 123,
"completion_tokens": 45
},
"requestAttempts": 1,
"historyIndexArtifactId": null,
"historyIndexSha256": null,
"workingSetArtifactId": null,
"workingSetSha256": null,
"workingSetEntries": 0,
"workingSetViewVersion": 4,
"workingRetentionTokens": 0,
"latestToolsArtifactId": null,
"latestToolsSha256": null,
"latestToolsEntries": 0,
"evidenceVerified": true,
"evidenceError": null
}
],
"browserVerification": {
"required": false,
"status": "not_requested"
},
"browserChecks": [],
"taskPlan": {
"configured": false,
"task_id": "32d72485-2faf-4435-ba9f-172943b9b0da",
"revision": 0,
"status": "not_planned",
"steps": [],
"all_verified": false,
"binding_sha256": null
},
"taskPlanHistory": [],
"taskProofs": [],
"checks": [],
"verifiedCheckJobId": null,
"deliveries": [],
"requiresVerification": [],
"limitations": [
"本切片验证已选工程检查和提交范围;业务需求验收另行记录。",
"提交为本地普通提交,不执行仓库hooks和GPG签名。",
"请求输入为本地UTF-8估算;服务实际分词和用量另行记录。",
"未配置模型单价,费用未知。"
]
}
@@ -0,0 +1,34 @@
{
"success": true,
"passed": [
"actual runtime pages grow then repeat under the original three-round limit",
"original observation receipt opens with the actual tool-result provenance",
"refresh restores the same Task, Run and persisted shadow observations",
"390px keeps observation facts and original receipt actions reachable without page overflow",
"an actual pending approval stays waiting and does not consume the earlier same-turn read twice",
"refusing the original approval preserves the permission failure and the original tool pairs",
"selecting historical and current Runs keeps their independent observations",
"delivery report uses both Runs and independently verifies the original observation receipts",
"original HTTP 502 remains a model failure and is not relabeled as no progress"
],
"errors": [],
"screenshots": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\desktop-pages.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\narrow-pages.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\waiting-approval.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\denied-approval.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\historical-run.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\shadow-electron-d8ed80a6-9a11-4177-a944-2b026add7070\\network-original-failure.png"
],
"snapshots": [
"pages-original.json",
"approval-waiting.json",
"approval-denied.json",
"report-original.json",
"network-original.json"
],
"actualElectron": true,
"installationValidated": false,
"realModelRequests": 0,
"officialServiceTouched": false
}
@@ -0,0 +1,177 @@
[
{
"id": "092aaf76-1965-4bba-aeca-0703bb192ca9",
"kind": "turn-progress-shadow",
"sha256": "8cae03381f54cdb385cddb27c2c519e83acf24b630d13168e2b655489b61d934",
"bytes": 595,
"path": "artifacts/092aaf76-1965-4bba-aeca-0703bb192ca9.txt"
},
{
"id": "fc522ade-162a-436b-ac45-248d7fe1fc88",
"kind": "model-http-response",
"sha256": "6bf86234841f0a8e301a03a01511b25e7b9462a951a63da98ba41cc399979257",
"bytes": 287,
"path": "artifacts/fc522ade-162a-436b-ac45-248d7fe1fc88.txt"
},
{
"id": "95ab5551-42c5-4524-bd3f-37b1337f5754",
"kind": "tool-result",
"sha256": "cfd27074ea75245cc0f0b1e0179f0b2e22c0dc3e8d8567513250070343840394",
"bytes": 404,
"path": "artifacts/95ab5551-42c5-4524-bd3f-37b1337f5754.txt"
},
{
"id": "9d61022a-cf8d-47ff-89f8-086b4ebc0d5e",
"kind": "turn-progress-shadow",
"sha256": "1a72406711d67c1a26a9daf1d15d44ffc1db592a3e4a196457d6375b2bdabc56",
"bytes": 925,
"path": "artifacts/9d61022a-cf8d-47ff-89f8-086b4ebc0d5e.txt"
},
{
"id": "5f5b6455-2c3a-4a33-8998-0e29f6ac0b1b",
"kind": "model-http-response",
"sha256": "766649c120a7ff239291c671bb33614d92930d7b11bb1e0ba200762021573482",
"bytes": 288,
"path": "artifacts/5f5b6455-2c3a-4a33-8998-0e29f6ac0b1b.txt"
},
{
"id": "d4a5bc82-d2d1-4ba4-bc5c-a7c464642e90",
"kind": "tool-result",
"sha256": "1f95df2aa97ee684bc0e6de9be76462e9b7e05a59889a59046fc5f23df07b4aa",
"bytes": 408,
"path": "artifacts/d4a5bc82-d2d1-4ba4-bc5c-a7c464642e90.txt"
},
{
"id": "66fa991a-75cd-48a0-90d1-7d8d8454f93c",
"kind": "turn-progress-shadow",
"sha256": "46cdd71b21fb53cbae9aa19f0dc0f45df5312cc1e922ffbff3727327649a28b2",
"bytes": 925,
"path": "artifacts/66fa991a-75cd-48a0-90d1-7d8d8454f93c.txt"
},
{
"id": "5d73c914-1347-48df-b55d-c86fe12b7512",
"kind": "model-http-response",
"sha256": "0b95de8795765e496951221843b56799b1a7869cdead9a80cf46a39983e710ca",
"bytes": 288,
"path": "artifacts/5d73c914-1347-48df-b55d-c86fe12b7512.txt"
},
{
"id": "48589b61-95f2-43ea-bf4b-b445f4a5e2d8",
"kind": "tool-result",
"sha256": "a4b57371daddf6f29e63ffe399a5b4e8789b81a325315f940517f6a2791b096f",
"bytes": 408,
"path": "artifacts/48589b61-95f2-43ea-bf4b-b445f4a5e2d8.txt"
},
{
"id": "f5d28be9-4a65-424c-9722-356de6251013",
"kind": "turn-progress-shadow",
"sha256": "f58b3902bc4f9a0ada0d3ac9c27ac5ee0b35124246f75b9f5b43e2058f361d0f",
"bytes": 928,
"path": "artifacts/f5d28be9-4a65-424c-9722-356de6251013.txt"
},
{
"id": "68a33b41-d912-40de-9d92-07bed0c5a23d",
"kind": "turn-progress-shadow",
"sha256": "d505d4796ba611dcbc98f36d454ae35351e1bb8c99eb5aad6fa81203565d3565",
"bytes": 595,
"path": "artifacts/68a33b41-d912-40de-9d92-07bed0c5a23d.txt"
},
{
"id": "ebd78899-c0c4-485f-8c1f-446a6b338b50",
"kind": "model-http-response",
"sha256": "7559c0ea5e206ebbca81c12dcf83cf367f1ce4aaf041f9fd66da19f3b5af4ed5",
"bytes": 465,
"path": "artifacts/ebd78899-c0c4-485f-8c1f-446a6b338b50.txt"
},
{
"id": "6fae1f81-24eb-4a87-a50d-d779f871416c",
"kind": "tool-result",
"sha256": "63e9135badc0fff8baf8467c324533457b4f2f40d2341884526161f059a1a092",
"bytes": 403,
"path": "artifacts/6fae1f81-24eb-4a87-a50d-d779f871416c.txt"
},
{
"id": "77c897d6-1930-4299-ab6e-88fa801d0e16",
"kind": "turn-progress-shadow",
"sha256": "f06318cbf68b0958dd99f7583f285c315603ca8805a80cb2afe1dfde5a2b3abf",
"bytes": 654,
"path": "artifacts/77c897d6-1930-4299-ab6e-88fa801d0e16.txt"
},
{
"id": "2966ad74-4412-4b49-b364-f87a897edd46",
"kind": "tool-result",
"sha256": "48f073c655039dd7910c0c7cafce446f747c01d3b6db4333773f6bf3575a4fe4",
"bytes": 80,
"path": "artifacts/2966ad74-4412-4b49-b364-f87a897edd46.txt"
},
{
"id": "24f5eea8-d2eb-4697-9ad6-7220d99e09a0",
"kind": "turn-progress-shadow",
"sha256": "6317856cb7bd7baf2e6565985d6a74d621470fcb0a99f629e10f825beabde3bd",
"bytes": 1241,
"path": "artifacts/24f5eea8-d2eb-4697-9ad6-7220d99e09a0.txt"
},
{
"id": "dafb6a9b-da55-40d5-9842-71ccc7d75590",
"kind": "model-http-response",
"sha256": "1533d54eb3cfa022035842742f6595b3885675db8019909517d655c95b8e8510",
"bytes": 189,
"path": "artifacts/dafb6a9b-da55-40d5-9842-71ccc7d75590.txt"
},
{
"id": "1d5be588-b616-4a0d-9553-477d9a821ce9",
"kind": "turn-progress-shadow",
"sha256": "ac3683e02573a2868bd2d657ea0197efb708cdff66f7930fd67a7f4b5a8d2f47",
"bytes": 602,
"path": "artifacts/1d5be588-b616-4a0d-9553-477d9a821ce9.txt"
},
{
"id": "aafaa874-c122-40a9-b8eb-c113afe2dba5",
"kind": "delivery-report",
"sha256": "332d52a3c750caa72734e5efecad387ab1c3b88cfc8688c1a0d2de37277bcd91",
"bytes": 25016,
"path": "artifacts/aafaa874-c122-40a9-b8eb-c113afe2dba5.txt"
},
{
"id": "d9c431b4-dcd7-4e5a-8dde-f04159408c40",
"kind": "delivery-report-markdown",
"sha256": "210d0398768957c17b3c53f4b62bfddac6a44a8f7f79baf62851f0943551656a",
"bytes": 4739,
"path": "artifacts/d9c431b4-dcd7-4e5a-8dde-f04159408c40.txt"
},
{
"id": "83aefddb-497e-43a3-b268-8b89c1084155",
"kind": "turn-progress-shadow",
"sha256": "4fb0271c2ba830306f64d457fdd398f6f4761966f0e8f4062e5026f8e2e47d52",
"bytes": 595,
"path": "artifacts/83aefddb-497e-43a3-b268-8b89c1084155.txt"
},
{
"id": "3fca0382-4798-40fb-94c3-4ce1e41c1f16",
"kind": "model-http-response",
"sha256": "fa8a0051f6cbf1ed03ac5fddae2dce449169dd64d317e644f7da5a318a20b93a",
"bytes": 80,
"path": "artifacts/3fca0382-4798-40fb-94c3-4ce1e41c1f16.txt"
},
{
"id": "2afc7ad8-cf8b-4881-b7f0-ceae8d72cd9d",
"kind": "model-http-response",
"sha256": "fa8a0051f6cbf1ed03ac5fddae2dce449169dd64d317e644f7da5a318a20b93a",
"bytes": 80,
"path": "artifacts/2afc7ad8-cf8b-4881-b7f0-ceae8d72cd9d.txt"
},
{
"id": "e7386127-2e81-4ade-b7db-50de4dbe16de",
"kind": "model-http-response",
"sha256": "fa8a0051f6cbf1ed03ac5fddae2dce449169dd64d317e644f7da5a318a20b93a",
"bytes": 80,
"path": "artifacts/e7386127-2e81-4ade-b7db-50de4dbe16de.txt"
},
{
"id": "687ccdf2-ff22-4d27-8222-ac6df96584aa",
"kind": "turn-progress-shadow",
"sha256": "b80ff045cdc8353cb8b7016bac2f0b0fc287d891b33c6d7c7557e0a7bfcaf989",
"bytes": 999,
"path": "artifacts/687ccdf2-ff22-4d27-8222-ac6df96584aa.txt"
}
]
Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
{"error":{"message":"Owned shadow gateway failure, original response retained"}}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"afeb84b2-17f6-49c5-8ff3-046f433d6952","runId":"d96f5671-5b91-4fc1-aa15-99ff79d769a5","stepId":"e232a4a6-5fec-4a21-a542-474630e79edc","stepIndex":2,"phase":"settled","classification":"evidence_growth","delta":{"read_characters":10,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["new_returned_file_or_artifact_range"],"tools":[{"id":"ffb806bf-6905-4fcf-9d43-e8bee974cf62","tool":"read_file","result_artifact_id":"8e07dcf5-1997-405f-8cfb-f8cf164e127c","result_sha256":"1f95df2aa97ee684bc0e6de9be76462e9b7e05a59889a59046fc5f23df07b4aa"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"","tool_calls":[{"id":"page-1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\",\"offset\":0,\"limit\":10}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"afeb84b2-17f6-49c5-8ff3-046f433d6952","runId":"bb66d45b-2c6b-46e1-85ca-f183614233b5","stepId":"b7831616-beff-4bfe-a434-9cac7de14feb","stepIndex":2,"phase":"settled","classification":"no_observed_change","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":[],"tools":[],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"","tool_calls":[{"id":"read-before-approval","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\",\"limit\":10}"}},{"id":"owned-command","type":"function","function":{"name":"run_command","arguments":"{\"command\":\"node --version\",\"reason\":\"所属只读环境检查,需原审批\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
@@ -0,0 +1 @@
{"path":"README.md","start_line":1,"end_line":1,"total_lines":4,"content":"# Fixture ","sha256":"ab097f769b6f141417493cdedfbe1c9c9cdb89c52c4b073eb9faf3c5f9ccf16d","bom":false,"truncated":true,"range_start_line":1,"range_end_line":4,"offset":0,"next_offset":10,"total_characters":56,"returned_characters":10,"requested_offset":0,"next_start_line":null,"budget_limited":false,"maximum_message_bytes":13470}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"afeb84b2-17f6-49c5-8ff3-046f433d6952","runId":"d96f5671-5b91-4fc1-aa15-99ff79d769a5","stepId":"c09e2cf7-d600-4854-b0da-3c533c4f45d0","stepIndex":3,"phase":"settled","classification":"repeated_read_candidate","delta":{"read_characters":0,"new_sources":0,"repeated_reads":1,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["same_sha_range_already_returned"],"tools":[{"id":"aaa10bae-2b3e-46e9-9f92-18f9fbf62ed0","tool":"read_file","result_artifact_id":"a369f3af-1ddc-4691-a49d-386cf3708c10","result_sha256":"a4b57371daddf6f29e63ffe399a5b4e8789b81a325315f940517f6a2791b096f"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"error":{"message":"Owned shadow gateway failure, original response retained"}}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"afeb84b2-17f6-49c5-8ff3-046f433d6952","runId":"d96f5671-5b91-4fc1-aa15-99ff79d769a5","stepId":null,"stepIndex":null,"phase":"baseline","classification":"baseline","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["existing_facts_not_run_progress"],"tools":[],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"path":"README.md","start_line":1,"end_line":1,"total_lines":4,"content":"# Fixture ","sha256":"ab097f769b6f141417493cdedfbe1c9c9cdb89c52c4b073eb9faf3c5f9ccf16d","bom":false,"truncated":true,"range_start_line":1,"range_end_line":4,"offset":0,"next_offset":10,"total_characters":56,"returned_characters":10,"requested_offset":0,"next_start_line":null,"budget_limited":false,"maximum_message_bytes":1777}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"afeb84b2-17f6-49c5-8ff3-046f433d6952","runId":"bb66d45b-2c6b-46e1-85ca-f183614233b5","stepId":null,"stepIndex":null,"phase":"baseline","classification":"baseline","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":["existing_facts_not_run_progress"],"tools":[],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"afeb84b2-17f6-49c5-8ff3-046f433d6952","runId":"bb66d45b-2c6b-46e1-85ca-f183614233b5","stepId":"4beb7083-cdb9-4dcf-8568-1b466e1edf64","stepIndex":1,"phase":"waiting","classification":"waiting","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":0,"repeated_failures":0,"other_observations":0},"reasons":[],"tools":[],"waiting":[{"kind":"approval","id":"d718f5a7-b0d9-4da6-921a-a93bcdc4518c"}],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"status":"denied","message":"命令未执行。","requires_verification":false}
@@ -0,0 +1 @@
{"choices":[{"message":{"role":"assistant","content":"","tool_calls":[{"id":"page-2","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\",\"offset\":10,\"limit\":10}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":123,"completion_tokens":45}}
@@ -0,0 +1 @@
{"schemaVersion":1,"mode":"shadow","taskId":"8f785674-d5ca-419d-b7f1-fb73e62de3a4","runId":"58fc25d6-820d-4669-8e03-2526d0cb16ff","stepId":"98d29461-fe15-42e9-8722-b9fa5d464ff5","stepIndex":1,"phase":"settled","classification":"new_failure_evidence","delta":{"read_characters":0,"new_sources":0,"repeated_reads":0,"changed_files":0,"check_results":0,"requirement_evidence":0,"user_boundaries":0,"new_failures":1,"repeated_failures":0,"other_observations":0},"reasons":["new_failure:service"],"tools":[{"id":"ca976084-a27e-4bf8-9885-abf627ec9abc","tool":"model_request","result_artifact_id":"bee96f40-e79f-4a60-a820-dc086e57b8e0","result_sha256":"fa8a0051f6cbf1ed03ac5fddae2dce449169dd64d317e644f7da5a318a20b93a","source_event_id":"3c05f0a7-e273-4555-9075-20a10ba57a99","diagnostic_sha256":"381901a4b2bda64951408ee132e88712c70f4f75918289e6602e9f86e4f8ba2c"}],"waiting":[],"truncated":false,"note":"外显事实观察;不等于业务交付,不改变停止、权限或预算。"}
@@ -0,0 +1 @@
{"path":"README.md","start_line":1,"end_line":3,"total_lines":4,"content":"project\n\nA","sha256":"ab097f769b6f141417493cdedfbe1c9c9cdb89c52c4b073eb9faf3c5f9ccf16d","bom":false,"truncated":true,"range_start_line":1,"range_end_line":4,"offset":10,"next_offset":20,"total_characters":56,"returned_characters":10,"requested_offset":10,"next_start_line":null,"budget_limited":false,"maximum_message_bytes":10965}

Some files were not shown because too many files have changed in this diff Show More