feat(tasks): review sourced requirements against current original evidence

This commit is contained in:
Agent Workbench Dev
2026-11-04 10:36:50 +08:00
parent ce3afb2f0d
commit 785dd0c54d
70 changed files with 6103 additions and 7 deletions
+1
View File
@@ -250,3 +250,4 @@ docs/working-memory-u-git-index.txt binary
docs/working-memory-u-release-identity.json -text
docs/tianshu-research-evidence/** -text
docs/requirements-review-a-evidence/** binary
+1
View File
@@ -47,3 +47,4 @@
!/docs/reading-s-evidence/**/*.log
!/docs/live-delivery-t-evidence/**/*.log
!/docs/requirements-review-a-evidence/**/*.log
+2
View File
@@ -1,5 +1,7 @@
# 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。下方“当前新增研究只读”属于研究时点。
V按一次诊断partial在预检前结束,真实请求0;原正式状态精确保持,46份证据离线通过,见docs/QA-LIVE-DELIVERY-V.md。当前用户新增Tianshu-harness深度源码研究:固定2d0b22e,只读机制/原理/逻辑与本产品差异,不运行第三方安装服务或导入其配置,不改正式Provider/Key,不委派、不推送;真实交付另冻新样本,不续跑V/T/R/P/O。下方U“下一V”和V执行中段落为历史状态。
U已本地交付1.24.8/source7e77fd65/候选20261103235313371:同SHA/原范围页聚合、完整小源码/最新纯读组保留、修改前当前检查事实与routine/latest去重完成。114相关、569输入独立重建22/22、三归档/便携、12实际安装和安装副本16+9文件流程,以及源码/便携/安装三载荷各7请求工作记忆夹具通过。正式原PID36552/Provider、65项目81会话6377记录13484事件及outbox/3720工件、全部原表行/导出/工件和公开模型中心在网页/原生回看后再次精确保持,9229关闭。本轮真实请求0,原T九测试仍失败,未证明真实交付或Purge收益。证据620份/100126636字节离线核验通过,身份见docs/working-memory-u-release-identity.json,回顾见docs/RETROSPECTIVE-WORKING-MEMORY-U.md。下一按docs/LIVE-DELIVERY-V-PLAN.md另冻新诊断/单次预检/Node,旧T/R/P/O不续跑;Node后才React/Python/Purge,1.25及更新性能独立排期。不委派、不提取/复制/解密/重存Key、不推送。
+1 -1
View File
@@ -1,6 +1,6 @@
# 1.25 计划:任务要求与交付复核
状态:后续方案,尚未实现。1.24独立发行、实际安装、正式状态保持与回顾已完成;下一按本计划逐切片实施,不能把方案写成现有能力。
状态:分切片开发中。要求来源、逐项修订和实际证据复核的首个开发切片见[要求复核 A](REQUIREMENTS-REVIEW-A.md),已做相关及实际入口验证;自动草案提取、完整范围约定与诊断闭环继续排期。尚未独立发行/安装/正式升级,正式仍1.24.8,不代表1.25已交付。
1.24增加的是当前文件与来源的核对。文件SHA、采用原因和检查通过仍不能单独证明所有业务要求已满足。下一阶段把任务要求、实际成果及尚未验证事项联系起来,让用户知道“完成了哪些、依据是什么、哪里还需要体验”。
+17
View File
@@ -0,0 +1,17 @@
# 要求与证据复核 A:开发切片回顾
本阶段把用户要求、原文来源和实际证据接到现有 Task,已完成开发验证。本地正式安装仍为 1.24.8;本切片尚未独立发行、安装或正式升级,不能标作 1.25 已交付。原 Tianshu 采用计划是研究时的冻结方案,当前实施状态以本文和后续阶段记录为准。
用户在任务面板的“要求与证据”记录原文范围、验收条件和证据类别。原目标及每次追加都有独立身份、时间和来源 SHA,相同文字不会合并成一个消息实例。每项单独修订,旧要求、失败和工件保留。新增来源先列为未审阅;未改动要求的有效文件事实保留。没有自动提取或模型自签验收。
实际证据复核沿用原 TaskPlanManager、FileResults、检查和浏览器校验。核对当前项目/Task/Run、原调用与参数、工件原字节、选定文件当前 SHA、当前检查和页面构建;非空说明、旧 Task 或伪造 ID 不算证据。“所选证据已核对”“用户已确认”“待复核”“复核失败”“依据失效”“按约定未执行”分别显示。用户确认包含原输入指纹和体验说明,源码变化后需重核。跳过检查只接受当前明确 no-test 约定,不计为通过。
Git 预览和发布重新核对要求绑定;模型答复、手动结束任务与无测试文件应用也保留待复核门。旧任务未配置逐项要求时仍明确显示未记录,不把已有能力倒写为业务验收。工程检查、文件成果和页面权限硬门保留。手机没有新增要求写入或确认权限;本阶段只验证桌面网页在 390px 的响应布局及原手机权限回归,没有声称真机验收。
验证记录:相关首轮 70 项中 69 通过,唯一新用例误取成果返回的 id(应为 result_id);修正后新增及 HTTP 专项 11/11、增加逐文件来源和实际 Git 发布绑定后 12/12。最终要求/HTTP/成果/手机相关 53/53,包含追加来源、相同文字、跨项目/旧 Task、伪造/缺失/篡改工件、要求修订、当前源码变化、并发修订、重开宿主与原消息不变。实际网页七组、Electron 三组通过;TypeScript 和完整构建通过。手机新增路由拒绝另有定向验证。原失败日志、截图与最终结果一起封存,未覆盖原件。
回顾发现:新的原文来源与证据层补齐了原计划不表达的业务要求复核;没有复制另一套执行计划或 Git 系统。新增文件核对只改变对应要求,不自动宣布其业务含义成立。保存接线首错、390px 任务栏重开、迟到拦截已取消请求和隐藏 Electron 截图超时均如实保留;按实际 API/导航/窗口规则修正。最终桌面与窄屏截图已目视检查,内容沿用现有工作台字体、颜色和任务侧栏。
限制与下一步:范围/禁止操作和未知要求仍需用户明确记录,自动草案提取、全面业务语义判断及诊断闭环尚未实现。B 将只观察单轮外显事实;停止/权限/预算保护不因 shadow 改动。独立源码/不可变发行/安装/保留状态正式升级及进一步体验验收继续排期。真实模型请求为 0,正式 Provider/Key 未操作;V 网络 partial、T/R/P/O 失败、重复读取与 Purge 收益未验证保持,旧样本不续跑。
证据位于 `requirements-review-a-evidence/`。运行 `node scripts/verify-adoption-evidence.mjs docs/requirements-review-a-evidence` 只核对封存字节;加 `--source-ref <本切片提交>` 可核对 Git 源码,不重放原工具、检查或模型请求。
@@ -0,0 +1,354 @@
{
"kind": "adoption-stage-evidence",
"stage": "requirements-review-a",
"status": "development_slice_validated_not_released",
"realModelRequests": 0,
"officialServiceChanged": false,
"sourceFiles": [
{
"path": "src/core/tasks/requirement-review.mjs",
"snapshot": "source/src/core/tasks/requirement-review.mjs"
},
{
"path": "src/client/RequirementPanel.tsx",
"snapshot": "source/src/client/RequirementPanel.tsx"
},
{
"path": "src/client/RequirementPanel.css",
"snapshot": "source/src/client/RequirementPanel.css"
},
{
"path": "src/client/TaskPanel.tsx",
"snapshot": "source/src/client/TaskPanel.tsx"
},
{
"path": "src/client/types.ts",
"snapshot": "source/src/client/types.ts"
},
{
"path": "src/core/delivery-report.mjs",
"snapshot": "source/src/core/delivery-report.mjs"
},
{
"path": "src/core/git-delivery.mjs",
"snapshot": "source/src/core/git-delivery.mjs"
},
{
"path": "src/server/app.mjs",
"snapshot": "source/src/server/app.mjs"
},
{
"path": "src/server/runtime.mjs",
"snapshot": "source/src/server/runtime.mjs"
},
{
"path": "src/shared/contracts/task-control.mjs",
"snapshot": "source/src/shared/contracts/task-control.mjs"
},
{
"path": "tests/requirement-review.test.mjs",
"snapshot": "source/tests/requirement-review.test.mjs"
},
{
"path": "tests/requirement-review-api.test.mjs",
"snapshot": "source/tests/requirement-review-api.test.mjs"
},
{
"path": "tests/companion.test.mjs",
"snapshot": "source/tests/companion.test.mjs"
},
{
"path": "scripts/verify-requirements-ui.mjs",
"snapshot": "source/scripts/verify-requirements-ui.mjs"
},
{
"path": "scripts/verify-requirements-desktop.mjs",
"snapshot": "source/scripts/verify-requirements-desktop.mjs"
},
{
"path": "scripts/verify-adoption-evidence.mjs",
"snapshot": "source/scripts/verify-adoption-evidence.mjs"
}
],
"files": [
{
"path": "retrospective.md",
"bytes": 3655,
"sha256": "fdc7cac35a691f14c62e757faa91311b7e1436e769ce9b8901107e6c9749291e"
},
{
"path": "source/scripts/verify-adoption-evidence.mjs",
"bytes": 4224,
"sha256": "26e00cc6666d91ff58cddf754a7e2ec00c8aecea88ad2504eb69c95a4d8af566"
},
{
"path": "source/scripts/verify-requirements-desktop.mjs",
"bytes": 5128,
"sha256": "a07213b4ec9fb0ffbfe834980406b37f71ca766eff388ef9420d67d300218634"
},
{
"path": "source/scripts/verify-requirements-ui.mjs",
"bytes": 7320,
"sha256": "1f05744a94c58e3ded6b59b33bc0244b591856c664c71e3ddd3efa8b8d2cca5e"
},
{
"path": "source/src/client/RequirementPanel.css",
"bytes": 1885,
"sha256": "b0d4511585c088d2a35f077a8e8a6934d7fe293d10c86ccc31a2b1fc727b6034"
},
{
"path": "source/src/client/RequirementPanel.tsx",
"bytes": 13742,
"sha256": "5a457e43b05d1bd599c4c64cacc1645dc9d39ae7fa534aeee6f968cf03c4ab2c"
},
{
"path": "source/src/client/TaskPanel.tsx",
"bytes": 24179,
"sha256": "25e4289226d0ec66f2f1803a8af0416272bf5b70d721355b7bbafd4bf6dd5c9b"
},
{
"path": "source/src/client/types.ts",
"bytes": 42122,
"sha256": "dde9d34c6cd713dfafb9ff3f7679266d7db194c9440a85edc1c3e9d730293eed"
},
{
"path": "source/src/core/delivery-report.mjs",
"bytes": 28149,
"sha256": "3ae6714b9c73d8914031ceaab1f65a48ad8b27b41bb14e211f9f64dcff4104ea"
},
{
"path": "source/src/core/git-delivery.mjs",
"bytes": 41782,
"sha256": "83f1e32429060b805855a3100d6b72299d522eeeb7c93a4bd25b3bb9bb17d0b2"
},
{
"path": "source/src/core/tasks/requirement-review.mjs",
"bytes": 16538,
"sha256": "05680004e70f2c9b215b480e58c12b4d28c3fc91d08173550cdeb0d524adc18f"
},
{
"path": "source/src/server/app.mjs",
"bytes": 76366,
"sha256": "027267159419846d2fc63d42f8c0d2dc0d17341436872183a2dbbbd0bb6c4345"
},
{
"path": "source/src/server/runtime.mjs",
"bytes": 91837,
"sha256": "5c585308da13597c08cd544319f2e5941818bf7638338d29a25a7dcfd8a02652"
},
{
"path": "source/src/shared/contracts/task-control.mjs",
"bytes": 6840,
"sha256": "3338e0fe5ea6e7304cee401e5b0c6de624ddaeccd49b85adf6ce76d2fc372d55"
},
{
"path": "source/tests/companion.test.mjs",
"bytes": 32426,
"sha256": "bc4c4478c69987ac22e7fb3d59c65a9fa8c03c677a2a104fe44931b3adf34663"
},
{
"path": "source/tests/requirement-review-api.test.mjs",
"bytes": 2018,
"sha256": "990cadc188a2f7b93b71ac2c60f5325a6898837d8bad3e001e38066323067020"
},
{
"path": "source/tests/requirement-review.test.mjs",
"bytes": 15159,
"sha256": "39ad8606cd3b17b5e9b6db8ac53a17510d22439ce4d4e000db17d47faea1ae8e"
},
{
"path": "validation/build-first.log",
"bytes": 1090,
"sha256": "7a3da76a0e7a60f7df0f80a880de232077d3a008a859e4b5c07728060376e058"
},
{
"path": "validation/build-requirements-final.log",
"bytes": 1090,
"sha256": "dc744ded38fc0480e93a5d4935560a9c99ab5b3ed9358e6dff8e916846b1f711"
},
{
"path": "validation/electron-4a37e4be-2efc-456d-9e5a-ca680ed17ac1/result.json",
"bytes": 524,
"sha256": "4a6cb8511ddfdf9cf5ce0348a01b4a52f1ade5b0c589526f997dc1634ca18748"
},
{
"path": "validation/electron-4a37e4be-2efc-456d-9e5a-ca680ed17ac1/verified.png",
"bytes": 115342,
"sha256": "1a4688db95f67f7633636d1b673a389a09611a29f993ff8ac06997101c747612"
},
{
"path": "validation/electron-7e0fe298-edd7-48f1-a2ec-40e15294f74b/result.json",
"bytes": 528,
"sha256": "429d7373861a12e1b8406a097cf1a118d6f7fbe689890661ee088a8306745402"
},
{
"path": "validation/electron-final.log",
"bytes": 777,
"sha256": "8e1489ebdf879c9d9d161c36ba73e1bd31881f97e7322c22748907580c579378"
},
{
"path": "validation/electron-first.log",
"bytes": 735,
"sha256": "9e1d50d47890b605ff04f6416310bbd8bb3cebdb0939623cb2e6c8e90a81fd24"
},
{
"path": "validation/electron-second.log",
"bytes": 777,
"sha256": "9f764d0300214c819b26deb8333774535c7cc0ecb3ae54e36d4a62e6b27fdab6"
},
{
"path": "validation/mobile-routes.tap",
"bytes": 222,
"sha256": "45a5c999b53013c37485ee8edfcd2b1620bef7d1a295beec9906a344441691a9"
},
{
"path": "validation/requirements-acceptance.tap",
"bytes": 6198,
"sha256": "8f38f5fb5a57f859176f265ef9fd26a20ae72af0354809167e43ad765555b061"
},
{
"path": "validation/requirements-final.tap",
"bytes": 1473,
"sha256": "d7ea497b2c0558946008656ea27c0dbb6a810faabdab45da40c681b365e32911"
},
{
"path": "validation/requirements-first.tap",
"bytes": 3389,
"sha256": "60e83642a0e4eea101fdbc712b531df8bfa95e03e0f30f22b04668d7ce14ee4d"
},
{
"path": "validation/requirements-related.tap",
"bytes": 9641,
"sha256": "7287e611352e234263e330fdaeb19a2f2a3a842545c5f1dbe7bb6b7d2fd8e7ef"
},
{
"path": "validation/requirements-scoped.tap",
"bytes": 1572,
"sha256": "7d54f3d5558037f547c6a6a60c00cb8a7c451522e945783d98d92aa978628da8"
},
{
"path": "validation/ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5/desktop-stale.png",
"bytes": 118286,
"sha256": "00fb276a4a240fa8ac843b88776959be52e715da460280a719bbb0145d138b69"
},
{
"path": "validation/ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5/desktop-verified.png",
"bytes": 117205,
"sha256": "7ba589d2bff35fa30a6a58c6a43fa99f9791f5f111eb318362695c67ee5d4919"
},
{
"path": "validation/ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5/narrow-stale.png",
"bytes": 48976,
"sha256": "e3ab5c711f245e35a072ef2153991956598464169b3c6bf26b9867275079f9f9"
},
{
"path": "validation/ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5/result.json",
"bytes": 5140,
"sha256": "16093fcebbf36b2d591d53f9026b0b5035366622485154a020927cf62c5064cb"
},
{
"path": "validation/ui-b16d50fd-3185-4257-b6e2-d404bcd016b2/failure.png",
"bytes": 183249,
"sha256": "5d786918ee329d9d447db86c610ee56c398e8eb674ef642f49fdadb871b1cfe7"
},
{
"path": "validation/ui-b16d50fd-3185-4257-b6e2-d404bcd016b2/result.json",
"bytes": 683,
"sha256": "4be129e5fefd97275543e3d37df5894c04b1aa6d83b08fda70e7ef4d86a775c1"
},
{
"path": "validation/ui-be243cdc-aace-4a11-9528-559b5aa6a275/desktop-stale.png",
"bytes": 121344,
"sha256": "716fc8ca4dddf48b554baaa8534018b52daa4e2a1b6bbcbf2b6320e591dc2918"
},
{
"path": "validation/ui-be243cdc-aace-4a11-9528-559b5aa6a275/desktop-verified.png",
"bytes": 117101,
"sha256": "de2a6f977cd7e03ec465fc9f4b83224831ee906324ef867a2e6d61a078e03cb8"
},
{
"path": "validation/ui-be243cdc-aace-4a11-9528-559b5aa6a275/failure.png",
"bytes": 23435,
"sha256": "ec7985043ee807486e3c60a9169e0cd15f3dad15036d5984f5943c4d1059ccd6"
},
{
"path": "validation/ui-be243cdc-aace-4a11-9528-559b5aa6a275/result.json",
"bytes": 1779,
"sha256": "8bbde16e849793e00e53677574b2c437030a17491cb8a24a4b9cf1cb69e5fefd"
},
{
"path": "validation/ui-final.log",
"bytes": 1684,
"sha256": "89c4736d14d4d6677aa7266a87f82c346c2628b53e8e5d102f05ea196a67b848"
},
{
"path": "validation/ui-first.log",
"bytes": 778,
"sha256": "58081a4880283656cfcaf9ac0b4a9c13e45b2e03485d5feadc38c5eb85217fee"
},
{
"path": "validation/ui-second.log",
"bytes": 2200,
"sha256": "800fcb7e39d36b59bcec613f1f1e40b9a763abcda910ad47569531d0ba725700"
},
{
"path": "validation/ui-third.log",
"bytes": 733,
"sha256": "6bf5686273f9cf91b166b431dcccb29af9115a21d39d18a5e18eb48dbccfd12f"
}
],
"bytes": 1299321,
"testRuns": [
{
"path": "validation/requirements-first.tap",
"tests": 10,
"passed": 8,
"failed": 2
},
{
"path": "validation/requirements-related.tap",
"tests": 70,
"passed": 69,
"failed": 1
},
{
"path": "validation/requirements-acceptance.tap",
"tests": 53,
"passed": 53,
"failed": 0
},
{
"path": "validation/mobile-routes.tap",
"tests": 1,
"passed": 1,
"failed": 0
}
],
"uiRuns": [
{
"path": "validation/ui-b16d50fd-3185-4257-b6e2-d404bcd016b2/result.json",
"success": false,
"passed": 0
},
{
"path": "validation/ui-be243cdc-aace-4a11-9528-559b5aa6a275/result.json",
"success": false,
"passed": 5
},
{
"path": "validation/ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5/result.json",
"success": true,
"passed": 7
},
{
"path": "validation/electron-7e0fe298-edd7-48f1-a2ec-40e15294f74b/result.json",
"success": false,
"passed": 2
},
{
"path": "validation/electron-4a37e4be-2efc-456d-9e5a-ca680ed17ac1/result.json",
"success": true,
"passed": 3
}
]
}
@@ -0,0 +1,17 @@
# 要求与证据复核 A:开发切片回顾
本阶段把用户要求、原文来源和实际证据接到现有 Task,已完成开发验证。本地正式安装仍为 1.24.8;本切片尚未独立发行、安装或正式升级,不能标作 1.25 已交付。原 Tianshu 采用计划是研究时的冻结方案,当前实施状态以本文和后续阶段记录为准。
用户在任务面板的“要求与证据”记录原文范围、验收条件和证据类别。原目标及每次追加都有独立身份、时间和来源 SHA,相同文字不会合并成一个消息实例。每项单独修订,旧要求、失败和工件保留。新增来源先列为未审阅;未改动要求的有效文件事实保留。没有自动提取或模型自签验收。
实际证据复核沿用原 TaskPlanManager、FileResults、检查和浏览器校验。核对当前项目/Task/Run、原调用与参数、工件原字节、选定文件当前 SHA、当前检查和页面构建;非空说明、旧 Task 或伪造 ID 不算证据。“所选证据已核对”“用户已确认”“待复核”“复核失败”“依据失效”“按约定未执行”分别显示。用户确认包含原输入指纹和体验说明,源码变化后需重核。跳过检查只接受当前明确 no-test 约定,不计为通过。
Git 预览和发布重新核对要求绑定;模型答复、手动结束任务与无测试文件应用也保留待复核门。旧任务未配置逐项要求时仍明确显示未记录,不把已有能力倒写为业务验收。工程检查、文件成果和页面权限硬门保留。手机没有新增要求写入或确认权限;本阶段只验证桌面网页在 390px 的响应布局及原手机权限回归,没有声称真机验收。
验证记录:相关首轮 70 项中 69 通过,唯一新用例误取成果返回的 id(应为 result_id);修正后新增及 HTTP 专项 11/11、增加逐文件来源和实际 Git 发布绑定后 12/12。最终要求/HTTP/成果/手机相关 53/53,包含追加来源、相同文字、跨项目/旧 Task、伪造/缺失/篡改工件、要求修订、当前源码变化、并发修订、重开宿主与原消息不变。实际网页七组、Electron 三组通过;TypeScript 和完整构建通过。手机新增路由拒绝另有定向验证。原失败日志、截图与最终结果一起封存,未覆盖原件。
回顾发现:新的原文来源与证据层补齐了原计划不表达的业务要求复核;没有复制另一套执行计划或 Git 系统。新增文件核对只改变对应要求,不自动宣布其业务含义成立。保存接线首错、390px 任务栏重开、迟到拦截已取消请求和隐藏 Electron 截图超时均如实保留;按实际 API/导航/窗口规则修正。最终桌面与窄屏截图已目视检查,内容沿用现有工作台字体、颜色和任务侧栏。
限制与下一步:范围/禁止操作和未知要求仍需用户明确记录,自动草案提取、全面业务语义判断及诊断闭环尚未实现。B 将只观察单轮外显事实;停止/权限/预算保护不因 shadow 改动。独立源码/不可变发行/安装/保留状态正式升级及进一步体验验收继续排期。真实模型请求为 0,正式 Provider/Key 未操作;V 网络 partial、T/R/P/O 失败、重复读取与 Purge 收益未验证保持,旧样本不续跑。
证据位于 `requirements-review-a-evidence/`。运行 `node scripts/verify-adoption-evidence.mjs docs/requirements-review-a-evidence` 只核对封存字节;加 `--source-ref <本切片提交>` 可核对 Git 源码,不重放原工具、检查或模型请求。
@@ -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,54 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { _electron } from 'playwright';
import { fixture, until } from '../tests/helpers.mjs';
import { beginPlanTask, completeRead } from '../tests/fixtures/task-plan-fixture.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';
const root = path.resolve('.qa/requirements-progress', 'electron-' + randomUUID()); fs.mkdirSync(root, { recursive: true });
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t);
beginPlanTask(f, '解释当前工程依据,保留用户原文和原读取。'); completeRead(f); f.session.title = 'Electron要求证据原任务'; f.store.save(f.session); f.store.close();
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);
const controller = new HostController({ appRoot: process.cwd(), dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 });
const passed = [], errors = [], screenshots = []; let application, result;
const mark = name => { passed.push(name); console.log('PASS ' + name); };
try {
await controller.start(); assert.equal((await controller.api('/bootstrap')).config.hasKey, false);
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 });
const page = await application.firstWindow(); page.on('pageerror', error => errors.push(error.message));
const window = await application.browserWindow(page); await window.evaluate(win => win.setSize(1440, 1080));
await page.locator('.connection.connected').waitFor(); assert.equal(await page.evaluate(() => typeof window.process), 'undefined');
await page.getByLabel('当前项目').selectOption(f.project.id); await page.locator('.session-list button').filter({ hasText: f.session.title }).click();
await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
const panel = page.getByLabel('要求与证据', { exact: true }); await until(() => panel.getByRole('button', { name: '记录要求', exact: true }).isEnabled());
await panel.getByRole('button', { name: '记录要求', exact: true }).click();
const editor = page.getByRole('dialog', { name: '记录用户要求', exact: true });
await editor.getByLabel('要求名称', { exact: true }).fill('原生窗口核对工程说明'); await editor.getByLabel('要求验收条件', { exact: true }).fill('实际读取当前文件,保留原来源');
await editor.getByRole('button', { name: '保存要求', exact: true }).click(); await editor.waitFor({ state: 'hidden' }); mark('sandboxed actual Electron saves a sourced requirement');
const row = panel.locator('.requirement-list > li').first(); await row.getByRole('combobox').selectOption({ index: 1 });
await row.getByRole('button', { name: '复核所选证据', exact: true }).click(); await until(async () => (await row.locator('.requirement-state').textContent()) === '所选证据已核对');
mark('actual Electron verifies the original tool result');
await page.reload(); await page.locator('.connection.connected').waitFor();
if (!await panel.isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await until(async () => (await row.locator('.requirement-state').textContent()) === '所选证据已核对');
await window.evaluate(win => { win.showInactive(); win.setContentSize(1440, 1080); });
await until(() => page.evaluate(() => innerWidth === 1440));
await panel.scrollIntoViewIfNeeded(); const screenshot = path.join(root, 'verified.png'); await page.screenshot({ path: screenshot }); screenshots.push(screenshot);
mark('renderer reload restores the same Task and requirement proof'); assert.deepEqual(errors, []);
result = { success: true, passed, errors, screenshots, actualElectron: true, installationValidated: false, realModelRequests: 0, officialServiceTouched: false };
} catch (error) { result = { success: false, passed, errors, screenshots, error: error.stack, realModelRequests: 0 }; }
finally {
if (application) await application.close(); if (await controller.health()) await controller.stop();
for (const dispose of disposers.reverse()) await dispose();
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ root, ...result })); if (!result.success) process.exitCode = 1;
@@ -0,0 +1,84 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { chromium } from 'playwright';
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
import { beginPlanTask, completeRead } from '../tests/fixtures/task-plan-fixture.mjs';
const directory = path.resolve('.qa/requirements-progress', 'ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t);
beginPlanTask(f, '研究现有README.md,说明原工程依据,不修改参考文件。'); const read = completeRead(f);
f.session.title = '要求复核原工程'; f.store.save(f.session);
const other = f.store.createSession(f.project.id), originalSession = f.session; f.session = other; beginPlanTask(f, '另一个独立研究目标');
other.title = '另一任务的独立目标'; f.store.save(other); f.session = originalSession; f.store.close();
const host = await launchWorkbench(t, f.data); assert.notEqual(new URL(host.url).port, '4318'); assert.equal(host.bootstrap.config.hasKey, false);
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1080 } });
const passed = [], screenshots = [], errors = [];
page.on('pageerror', error => errors.push(error.message));
const panel = () => page.getByLabel('要求与证据', { exact: true }), row = () => panel().locator('.requirement-list > li').first();
const mark = name => { passed.push(name); console.log('PASS ' + name); };
const shot = async name => { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' }); screenshots.push(file); };
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();
if (!await panel().isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await panel().getByRole('button', { name: '记录要求', exact: true }).waitFor();
await until(async () => await panel().getByRole('button', { name: '记录要求', exact: true }).isEnabled());
}
async function verify() {
await row().getByRole('combobox').selectOption(read.id);
await row().getByRole('button', { name: '复核所选证据', exact: true }).click();
await until(async () => (await row().locator('.requirement-state').textContent()) === '所选证据已核对');
}
let result;
try {
await page.goto(host.url); await select(f.session);
await panel().getByRole('button', { name: '记录要求', exact: true }).click();
const editor = page.getByRole('dialog', { name: '记录用户要求', exact: true });
await editor.getByLabel('要求名称', { exact: true }).fill('解释当前工程的实际依据');
await editor.getByLabel('要求验收条件', { exact: true }).fill('保留README原读取和可核对结论,参考文件保持原字节');
await editor.getByRole('button', { name: '保存要求', exact: true }).click(); await editor.waitFor({ state: 'hidden' });
assert.equal(await row().locator('.requirement-state').textContent(), '待复核'); mark('manual source selection creates pending requirement, never automatic acceptance');
await verify(); mark('actual original read proof verified through UI');
await panel().scrollIntoViewIfNeeded(); await shot('desktop-verified');
await page.reload(); await select(f.session); await until(async () => (await row().locator('.requirement-state').textContent()) === '所选证据已核对');
mark('saved requirement and proof survive page refresh');
await row().getByRole('button', { name: '修订此要求', exact: true }).click();
await editor.getByLabel('要求验收条件', { exact: true }).fill('追加核对当前说明,旧复核记录保留');
await editor.getByRole('button', { name: '保存要求', exact: true }).click(); await editor.waitFor({ state: 'hidden' });
await until(async () => (await row().locator('.requirement-state').textContent()) === '待复核');
assert.match(await panel().textContent(), /原复核历史.*1 条/s); mark('requirement revision invalidates its proof and preserves original history');
await verify();
const file = path.join(f.projectRoot, 'README.md'), original = fs.readFileSync(file); fs.appendFileSync(file, '\nChanged externally in owned fixture\n');
await panel().getByRole('button', { name: '刷新复核', exact: true }).click();
await until(async () => (await row().locator('.requirement-state').textContent()) === '依据已失效');
await row().getByRole('button', { name: '复核所选证据', exact: true }).click();
await until(async () => (await panel().textContent()).includes('原读取对应旧文件SHA'));
await panel().scrollIntoViewIfNeeded(); await shot('desktop-stale'); mark('source mutation and stale original read are visible failures with preserved history');
fs.writeFileSync(file, original);
await page.setViewportSize({ width: 390, height: 844 });
if (!await panel().isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await panel().scrollIntoViewIfNeeded(); await shot('narrow-stale');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), true); mark('390px viewport keeps requirement controls usable without page overflow');
await page.setViewportSize({ width: 1440, height: 1080 });
let release = null, held = false;
await page.route('**/requirements?taskId=' + f.session.taskId, async route => {
held = true; await new Promise(resolve => { release = resolve; });
try { await route.continue(); } catch (error) { if (!/Route is already handled|Invalid InterceptionId/.test(error.message)) errors.push(error.message); }
});
await panel().getByRole('button', { name: '刷新复核', exact: true }).click(); await until(() => held);
await select(other); release(); await page.unroute('**/requirements?taskId=' + f.session.taskId);
await until(async () => (await panel().textContent()).includes('尚未逐项记录要求'));
assert.ok(!(await panel().textContent()).includes('解释当前工程的实际依据')); mark('late response for original Task cannot replace the newly selected task');
assert.deepEqual(errors, []);
const requirements = await host.api('/sessions/' + f.session.id + '/requirements?taskId=' + f.session.taskId);
result = { success: true, passed, screenshots, errors, requirements, realModelRequests: 0, officialServiceTouched: false, companionWritePermissionsAdded: false };
} catch (error) {
await shot('failure').catch(() => {}); result = { success: false, passed, screenshots, errors, error: error.stack, realModelRequests: 0 };
} finally {
await browser.close(); for (const dispose of disposers.reverse()) await dispose();
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result, requirements: undefined })); if (!result.success) process.exitCode = 1;
@@ -0,0 +1,19 @@
.requirement-list { list-style: none; padding: 0; margin: 0; }
.requirement-list > li { padding: 14px 0; border-top: 1px solid #dce7e2; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.requirement-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; }
.requirement-heading strong { font-size: 13px; }
.requirement-state { color: #674917; background: #fbf2df; padding: 2px 6px; border-radius: 3px; flex-shrink: 0; font-size: 11px; }
.requirement-evidence_verified, .requirement-user_confirmed { color: #154b4a; background: #edf3f1; }
.requirement-list summary, .requirement-history summary { cursor: pointer; color: #526a70; }
.requirement-list blockquote, .requirement-quote { margin: 9px 0; border-left: 2px solid #bbcfc7; padding: 6px 12px; white-space: pre-wrap; font-size: 12px; max-height: 150px; overflow: auto; }
.requirement-list code { font-size: 10px; overflow-wrap: anywhere; }
.requirement-actions { display: flex; flex-wrap: wrap; gap: 12px; margin: 7px 0; }
.requirement-confirm label { display: grid; gap: 6px; }
.requirement-confirm textarea { width: 100%; box-sizing: border-box; font: inherit; padding: 8px; border: 1px solid #cbded3; border-radius: 5px; margin-bottom: 8px; }
.requirement-history { font-size: 11px; margin-top: 12px; }
.requirement-history p { display: grid; gap: 4px; }
.requirement-editor { max-height: 72vh; overflow: auto; }
.requirement-offsets { display: flex; gap: 12px; margin: 12px 0; }
.requirement-offsets label { min-width: 0; font-size: 12px; }
.requirement-panel button:focus-visible, .requirement-panel textarea:focus-visible, .requirement-editor :is(input, select, textarea):focus-visible { outline: 2px solid #4664d9; outline-offset: 2px; }
@media (max-width: 600px) { .requirement-heading { flex-direction: column; gap: 4px; } .requirement-panel .button { min-height: 36px; } }
@@ -0,0 +1,102 @@
import { useEffect, useRef, useState } from 'react';
import { Check, FileText, Plus, RefreshCw } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { RequirementItem, RequirementView, Session, TaskPlanStep } from './types';
import './RequirementPanel.css';
const states: Record<string, string> = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对',
evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行' };
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
const clean = (row: RequirementItem) => ({ key: row.key, title: row.title, criterion: row.criterion, kind: row.kind, method: row.method,
source: { kind: row.source.kind, id: row.source.id, start: row.source.start, end: row.source.end },
...(row.kind === 'analysis' ? { tools: row.tools } : ['changes', 'results'].includes(row.kind) ? { paths: row.paths }
: row.kind === 'checks' ? { checks: row.checks } : { viewport_width: row.viewport_width, actions: row.actions }) });
const scope = (kind: TaskPlanStep['kind']) => kind === 'analysis' ? { tools: ['read_file'] } : ['changes', 'results'].includes(kind)
? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] };
export function RequirementPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task, run = session.execution?.run;
const identity = `${session.projectId}/${session.id}/${task?.id}/${run?.id}`;
const selected = useRef(identity); selected.current = identity;
const generation = useRef(0), mutation = useRef(false);
const [view, setView] = useState<RequirementView | null>(null), [loading, setLoading] = useState(false), [saving, setSaving] = useState(false);
const [draft, setDraft] = useState<RequirementItem | null>(null), [picked, setPicked] = useState<Record<string, string>>({}), [notes, setNotes] = useState<Record<string, string>>({});
const [notice, setNotice] = useState('');
const disabled = busy || saving || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => { generation.current++; setView(null); setDraft(null); setPicked({}); setNotes({}); setNotice(''); setSaving(false); mutation.current = false;
return () => { generation.current++; }; }, [identity]);
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, session.revision, session.status]);
async function load() {
if (!task || mutation.current) return;
const scopeId = identity, request = ++generation.current; setLoading(true);
try { const result = await api<RequirementView>(`/sessions/${session.id}/requirements?taskId=${task.id}`);
if (selected.current === scopeId && generation.current === request) setView(result);
} catch (error) { if (selected.current === scopeId && generation.current === request) onError(error); }
finally { if (selected.current === scopeId && generation.current === request) setLoading(false); }
}
async function mutate(action: string, input: object) {
if (!task || !run || !view || mutation.current) return;
mutation.current = true; generation.current++; setSaving(true); setNotice(''); const scopeId = identity;
try {
const reply = await api<{ session: Session; requirements: RequirementView; verification?: { status: string; message?: string } }>(`/sessions/${session.id}/${action}`,
{ taskId: task.id, runId: run.id, expected_revision: view.revision, ...input });
if (selected.current !== scopeId) return;
setView(reply.requirements); onSession(reply.session);
setNotice(reply.verification?.status === 'error' ? reply.verification.message ?? '复核未通过,原失败已保留。' : action === 'requirements' ? '要求与原文来源已保存。' : '本次复核已记录。');
if (action === 'requirements') setDraft(null);
} catch (error) { if (selected.current === scopeId) onError(error); }
finally { if (selected.current === scopeId) { mutation.current = false; setSaving(false); setLoading(false); } }
}
function edit(row?: RequirementItem) {
const source = view?.sources[0]; if (!source) return;
setDraft(row ? { ...clean(row), depends_on: [] } : { key: 'req_' + crypto.randomUUID().slice(0, 8), title: '', criterion: '', kind: 'analysis', method: 'evidence',
source: { kind: source.kind, id: source.id, start: 0, end: source.text.length }, depends_on: [], ...scope('analysis') });
}
const source = view?.sources.find(row => row.id === draft?.source.id && row.kind === draft?.source.kind);
return <section className="task-record-section requirement-panel" aria-label="要求与证据">
<div className="record-heading"><h3>要求与证据</h3><span>{view?.items.length ?? 0} 项</span></div>
<p className="record-footnote">逐项保留用户原文与实际依据,工程证据和用户体验分别记录。</p>
<div className="plan-toolbar"><button className="text-button" disabled={loading || disabled} onClick={() => void load()}><RefreshCw size={13} />刷新复核</button>
<button className="button secondary" disabled={disabled || !view || view.status === 'unverified' || (view.items.length >= 24)} onClick={() => edit()}><Plus size={13} />记录要求</button></div>
{notice && <p className="plan-notice" role="status">{notice}</p>}
{view?.error && <p className="plan-problem" role="alert">{view.error}</p>}
{!!view?.unreviewed_sources?.length && <p className="plan-problem">有 {view.unreviewed_sources.length} 份用户来源尚未审阅。核对原目标和追加要求后保存要求;旧复核记录保留。</p>}
{view && !view.items.length && <p className="record-empty">尚未逐项记录要求。模型的完成答复保留在原会话中。</p>}
<ol className="requirement-list">{view?.items.map(row => <li key={row.key}>
<div className="requirement-heading"><strong>{row.title}</strong><span className={'requirement-state requirement-' + row.status}>{states[row.status ?? 'pending'] ?? row.status}</span></div>
<p>{row.criterion}</p>
<details><summary>用户原文 · {row.source.kind === 'goal' ? '原目标' : '追加要求'} · 要求修订 {row.revision}</summary>
<blockquote>{row.source.quote}</blockquote><code>{row.source.id} [{row.source.start}, {row.source.end})</code></details>
{row.error && <p className="plan-problem">{row.error}</p>}{row.last_rejection && <p className="plan-problem">原复核失败:{row.last_rejection.message}</p>}
{row.user_note && <p>用户确认:{row.user_note}</p>}
<div className="requirement-actions"><button className="text-button" disabled={disabled} onClick={() => edit(row)}>修订此要求</button>
{row.proof_artifact_id && <button className="text-button" onClick={() => openArtifact(row.proof_artifact_id!)}><FileText size={13} />原复核记录</button>}</div>
{row.method === 'evidence' && <div className="plan-evidence"><label>选择实际依据 · {kinds[row.kind]}<select aria-label={`要求依据 ${row.title}`} disabled={disabled} value={picked[row.key] ?? ''} onChange={event => setPicked(values => ({ ...values, [row.key]: event.target.value }))}>
<option value="">选择此任务的原结果</option>{row.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}</select></label>
<button className="button secondary" disabled={disabled || !picked[row.key]} onClick={() => void mutate('requirement-proofs', { key: row.key, evidence_id: picked[row.key] })}><Check size={13} />复核所选证据</button></div>}
{row.method === 'user' && <div className="requirement-confirm"><label>实际体验与结论<textarea aria-label={`用户确认 ${row.title}`} rows={2} maxLength={1000} disabled={disabled} value={notes[row.key] ?? ''} onChange={event => setNotes(values => ({ ...values, [row.key]: event.target.value }))} /></label>
<button className="button secondary" disabled={disabled || !notes[row.key]?.trim()} onClick={() => void mutate('requirement-proofs', { key: row.key, note: notes[row.key] })}>记录用户确认</button></div>}
{row.method === 'not_requested' && <p className="record-footnote">检查未执行,不计为测试通过。</p>}
</li>)}</ol>
{!!view?.history?.length && <details className="requirement-history"><summary>原复核历史 · {view.history.length} 条</summary>{view.history.map(row => <p key={row.id}><button className="text-button" onClick={() => openArtifact(row.artifact_id)}>{row.key} · 修订 {row.revision} · {row.status === 'rejected' ? '未通过' : '已记录'}</button>{row.error && <span>{row.error}</span>}</p>)}</details>}
{draft && view && <Modal title="记录用户要求" description="选定用户原文、验收范围和复核方式;修订保留旧要求与原失败。" wide onClose={() => { if (!saving) setDraft(null); }}>
<form className="plan-editor requirement-editor" onSubmit={event => { event.preventDefault(); const rows = view.items.some(row => row.key === draft.key) ? view.items.map(row => row.key === draft.key ? clean(draft) : clean(row)) : [...view.items.map(clean), clean(draft)]; void mutate('requirements', { requirements: rows }); }}>
<fieldset disabled={saving} className="plan-editor-step">
<label>要求名称<input aria-label="要求名称" maxLength={100} required value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} /></label>
<label>验收条件<textarea aria-label="要求验收条件" rows={2} required maxLength={300} value={draft.criterion} onChange={event => setDraft({ ...draft, criterion: event.target.value })} /></label>
<label>用户原文来源<select aria-label="要求原文来源" value={draft.source.id} onChange={event => { const row = view.sources.find(value => value.id === event.target.value)!; setDraft({ ...draft, source: { kind: row.kind, id: row.id, start: 0, end: row.text.length } }); }}>{view.sources.map((row, i) => <option key={row.id} value={row.id}>{row.kind === 'goal' ? '原目标' : `追加要求 ${i}`} · {row.text.slice(0, 65)}</option>)}</select></label>
<blockquote className="requirement-quote">{source?.text.slice(draft.source.start, draft.source.end)}</blockquote>
<div className="requirement-offsets"><label>原文起点<input aria-label="原文起点" type="number" min={0} max={Math.max(0, (source?.text.length ?? 1) - 1)} value={draft.source.start} onChange={event => setDraft({ ...draft, source: { ...draft.source, start: Number(event.target.value) } })} /></label><label>原文终点<input aria-label="原文终点" type="number" min={draft.source.start + 1} max={source?.text.length} value={draft.source.end} onChange={event => setDraft({ ...draft, source: { ...draft.source, end: Number(event.target.value) } })} /></label></div>
<label>复核方式<select aria-label="要求复核方式" value={draft.method} onChange={event => setDraft({ ...draft, method: event.target.value as RequirementItem['method'], ...(event.target.value === 'not_requested' ? { kind: 'checks', checks: ['test', 'build'] } : {}) })}><option value="evidence">核对实际证据</option><option value="user">用户体验确认</option><option value="not_requested">按用户约定不执行检查</option></select></label>
{draft.method === 'evidence' && <><label>证据类别<select aria-label="要求证据类别" value={draft.kind} onChange={event => { const kind = event.target.value as TaskPlanStep['kind']; setDraft({ ...draft, kind, ...scope(kind) }); }}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
{['results', 'changes'].includes(draft.kind) && <label>文件范围(每行一项)<textarea aria-label="要求文件范围" required value={draft.paths?.join('\n') ?? ''} onChange={event => setDraft({ ...draft, paths: event.target.value.split('\n').filter(Boolean) })} /></label>}
{draft.kind === 'analysis' && <label>读取工具(逗号分隔)<input aria-label="要求读取工具" required value={draft.tools?.join(',') ?? ''} onChange={event => setDraft({ ...draft, tools: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{draft.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label="要求检查名称" required value={draft.checks?.join(',') ?? ''} onChange={event => setDraft({ ...draft, checks: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{draft.kind === 'browser' && <label>验收视口<select aria-label="要求验收视口" value={draft.viewport_width} onChange={event => setDraft({ ...draft, viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option></select></label>}</>}
</fieldset><div className="modal-actions"><button type="button" className="button secondary" disabled={saving} onClick={() => setDraft(null)}>取消</button><button className="button primary" disabled={saving}>保存要求</button></div>
</form></Modal>}
</section>;
}
@@ -0,0 +1,179 @@
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 { 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>
</> : <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,363 @@
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 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,288 @@
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 { 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,
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.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,521 @@
import fs from 'node:fs';
import path from 'node:path';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
import { spawn } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { createTwoFilesPatch, diffLines } from 'diff';
import { safePath } from '../server/files.mjs';
import { inspectProject } from './project-inspector.mjs';
import { gitArguments, gitEnvironment, runGit } from './git-process.mjs';
import { DeliveryReporter, verifiedCheck } from './delivery-report.mjs';
import { pendingDeliveryReview, resolveDeliveryReview } from '../shared/contracts/delivery-review.mjs';
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { currentBrowserVerification } from './browser/browser-manager.mjs';
import { assertBrowserResolved } from '../shared/contracts/browser.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
import { RequirementReview } from './tasks/requirement-review.mjs';
import { assertMcpResolved } from './tools/mcp-contract.mjs';
import { assertWorkersResolved, workerForProject } from '../shared/contracts/workers.mjs';
const at = () => new Date().toISOString();
const sha = value => createHash('sha256').update(value).digest('hex');
const conflict = message => Object.assign(new Error(message), { status: 409 });
const oid = value => /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(value);
const activeStates = new Set(['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting']);
export const DELIVERY_ACTIVE_STATES = [...activeStates];
const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
const digestFile = file => fs.existsSync(file) && fs.lstatSync(file).isFile() && !fs.lstatSync(file).isSymbolicLink() ? sha(fs.readFileSync(file)) : null;
const pidAlive = pid => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
function entries(text) {
return text.split('\0').filter(Boolean).map(line => {
const match = line.match(/^([0-7]{6}) ([a-f0-9]{40}(?:[a-f0-9]{24})?) ([0-3])\t(.+)$/s);
if (!match) throw conflict('Git索引格式未被当前交付器支持。');
return { mode: match[1], blob: match[2], stage: Number(match[3]), path: match[4], line };
});
}
function protectedIndex(stageText, flagText, paths) {
const chosen = new Set(paths);
return sha(JSON.stringify({
entries: entries(stageText).filter(item => !chosen.has(item.path)).map(item => item.line).sort(),
flags: flagText.split('\0').filter(line => line && !chosen.has(line.slice(2))).sort(),
}));
}
function validMessage(value) {
if (typeof value !== 'string' || !value.trim() || value.length > 1600 || value.includes('\0')
|| /^Workbench-(?:Delivery|Task|Session):/im.test(value)) throw new Error('提交说明需要1到1600个字符,不能包含工作台保留的trailer。');
return value.replaceAll('\r\n', '\n').trim();
}
function validAuthor(name, email) {
if (typeof name !== 'string' || !name.trim() || name.length > 120 || /[<>\r\n\0]/.test(name)
|| typeof email !== 'string' || email.length > 180 || !/^[^\s<>@\0]+@[^\s<>@\0]+$/.test(email)) throw new Error('Git署名需要有效的姓名和邮箱。');
return { name: name.trim(), email: email.trim() };
}
export class GitDelivery {
constructor(store, { redact = String, projectBusy = () => false, faultInjector = null } = {}) {
this.store = store; this.redact = redact; this.projectBusy = projectBusy; this.faultInjector = faultInjector;
this.active = new Map(); this.projects = new Map();
this.directory = path.join(store.directory, 'delivery');
this.hooksDirectory = path.join(this.directory, 'empty-hooks');
fs.mkdirSync(this.hooksDirectory, { recursive: true });
if (fs.lstatSync(this.directory).isSymbolicLink() || fs.lstatSync(this.hooksDirectory).isSymbolicLink()
|| fs.readdirSync(this.hooksDirectory).length) throw new Error('工作台Git执行目录需要普通空hooks目录。');
this.reporter = new DeliveryReporter(store, { redact });
}
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
projectActive(projectId) { return this.projects.has(projectId); }
git(project, args, options = {}) { return runGit(safePath(project), args, { hooksDirectory: this.hooksDirectory, ...options }); }
async needGit(project, args, options) {
let result;
try { result = await this.git(project, args, options); }
catch (error) {
if (error.code === 'ENOENT') throw conflict('本机未发现Git。请安装Git for Windows并重新打开工作台,再准备本地提交。');
throw error;
}
if (!result.ok) throw Object.assign(new Error(this.redact(result.error.trim() || 'Git操作未完成。')), { status: result.aborted ? 409 : 400, gitResult: result });
return result;
}
assertTask(session) {
assertMcpResolved(this.store, session.projectId);
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
if (!session.taskId || !session.runId) throw conflict('先发送一个项目任务,再准备本任务的Git交付。');
const task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
if (run.taskId !== task.id) throw conflict('当前Task和Run归属不一致。');
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) throw conflict('先应用或撤回待审查改动,再准备提交。');
if ([...this.store.core.tool.values()].some(value => value.taskId === task.id && value.requiresVerification)) throw conflict('先核对本任务结果未知的工具,再准备提交。');
if ([...this.store.core.delivery_job.values()].some(value => value.projectId === session.projectId && (value.requiresVerification || value.status === 'unknown'))) throw conflict('这个项目有结果未知的提交,先核对该结果;不会重放提交。');
return { task, run };
}
assertIdle(session, { exceptSessionId = null } = {}) {
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, exceptSessionId)) throw conflict('项目正在执行任务、检查或Git交付,请等待结束。');
}
async snapshot(project, { allowOwnLock = false } = {}) {
await verifyWorkspaceProject(this.store, project);
const root = safePath(project);
let top;
try { top = await this.needGit(project, ['rev-parse', '--show-toplevel']); }
catch (error) {
if (/not a git repository/i.test(error.message)) throw conflict('这个工程尚未启用独立Git,请先在工程目录建立Git基线,再准备交付。');
throw error;
}
if (normalize(top.text.trim()) !== normalize(root)) throw conflict('当前项目需要独立Git仓库,上级仓库不能作为交付基线。');
const configNames = ['core.autocrlf', 'core.eol', 'core.filemode', 'core.sparsecheckout', 'extensions.refstorage', 'user.name', 'user.email'];
const [head, ref, gitDirectory, index, stage, flags, inventory, ...configs] = await Promise.all([
this.needGit(project, ['rev-parse', '--verify', 'HEAD']),
this.git(project, ['symbolic-ref', '--quiet', 'HEAD']),
this.needGit(project, ['rev-parse', '--absolute-git-dir']),
this.needGit(project, ['rev-parse', '--path-format=absolute', '--git-path', 'index']),
this.needGit(project, ['ls-files', '--stage', '-z']),
this.needGit(project, ['ls-files', '-v', '-z']),
this.needGit(project, ['ls-files', '--cached', '--others', '--exclude-standard', '-z']),
...configNames.map(name => this.git(project, ['config', '--get', name])),
]);
const headId = head.text.trim(), reference = ref.text.trim();
if (!oid(headId) || !ref.ok || !/^refs\/heads\/[^\s\0]+$/.test(reference)) throw conflict('当前交付切片需要已有提交的命名分支;请先用Git建立基线分支。');
const gitDir = fs.realpathSync.native(gitDirectory.text.trim()), indexPath = path.resolve(index.text.trim());
if (normalize(path.dirname(indexPath)) !== normalize(gitDir) || !fs.existsSync(indexPath) || fs.lstatSync(indexPath).isSymbolicLink()
|| fs.statSync(indexPath).size > 16 * 1024 * 1024) throw conflict('当前Git索引位置、类型或大小未被交付器支持。');
for (const name of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'REBASE_HEAD', 'rebase-apply', 'rebase-merge', 'sequencer', 'BISECT_START']) {
if (fs.existsSync(path.join(gitDir, name))) throw conflict('Git正在合并、变基或定位问题;先完成该操作再交付。');
}
if (!allowOwnLock && fs.existsSync(indexPath + '.lock')) throw conflict('Git索引正在被其他操作锁定,请先核对该操作。');
const paths = [...new Set(inventory.text.split('\0').filter(Boolean))];
if (paths.length > 1000) throw conflict('工程超过当前1000文件快照上限,请缩小工程范围后交付。');
const attributes = await this.needGit(project, ['check-attr', '-z', 'filter', 'working-tree-encoding', '--stdin'], { input: paths.join('\0') + (paths.length ? '\0' : '') });
const attributeParts = attributes.text.split('\0').filter(Boolean);
for (let i = 0; i < attributeParts.length; i += 3) if (!['unspecified', 'unset'].includes(attributeParts[i + 2])) {
throw conflict('工程使用自定义Git内容过滤或工作树编码,当前交付器不执行这些转换:' + attributeParts[i]);
}
const config = Object.fromEntries(configNames.map((name, i) => [name, configs[i].ok ? configs[i].text.trim() : null]));
if (config['core.sparsecheckout'] === 'true') throw conflict('当前交付器不支持稀疏检出工程。');
const indexSha256 = digestFile(indexPath);
const digest = sha(JSON.stringify({ root, head: headId, reference, gitDir, indexPath, indexSha256,
stage: stage.text, flags: flags.text, config, attributes: attributes.text }));
return { head: headId, reference, branch: reference.slice(11), gitDir, indexPath, indexSha256,
stage: stage.text, flags: flags.text, config, attributesSha256: sha(attributes.text), digest };
}
async blob(project, relative, bytes, { write = false, signal } = {}) {
const result = await this.needGit(project, ['hash-object', ...(write ? ['-w'] : []), '--path=' + relative, '--stdin'], { input: bytes, signal });
const id = result.text.trim(); if (!oid(id)) throw new Error('Git没有返回有效的文件blob身份。'); return id;
}
baseBytes(session, change) {
const backup = path.join(this.store.directory, 'backups', session.id, change.id + '.txt');
const bytes = fs.existsSync(backup) ? fs.readFileSync(backup) : Buffer.from(change.baseContent, 'utf8');
if (sha(bytes) !== change.baseSha256) throw conflict('原始文件字节备份与提案基线不一致:' + change.path);
return bytes;
}
async selectedFiles(session, project, snapshot) {
const selected = new Map();
for (const change of session.changes.filter(value => value.taskId === session.taskId && value.status === 'applied')) {
const target = safePath(project, change.path);
let ancestor = project.root;
for (const segment of change.path.replaceAll('\\', '/').split('/').filter(Boolean)) {
ancestor = path.join(ancestor, segment);
if (fs.lstatSync(ancestor).isSymbolicLink()) throw conflict('交付路径经过链接,需要使用实际普通文件路径重新审查:' + change.path);
}
if (!fs.lstatSync(target).isFile() || fs.lstatSync(target).isSymbolicLink()) throw conflict('交付路径需要普通文件:' + change.path);
const relative = path.relative(project.root, fs.realpathSync.native(target)).replaceAll('\\', '/');
if (/[\r\n\t\0]/.test(relative)) throw conflict('交付文件名不能包含换行或控制分隔符。');
if (!selected.has(relative)) selected.set(relative, []);
selected.get(relative).push(change);
}
if (!selected.size || selected.size > 32) throw conflict('当前任务需要1到32个已应用且归属明确的文件;旧版未记录Task归属的提案需要重新审查。');
const stageEntries = entries(snapshot.stage), result = [];
for (const [relative, chain] of selected) {
const latest = chain.at(-1), bytes = fs.readFileSync(safePath(project, relative));
if (sha(bytes) !== latest.sha256) throw conflict('文件在应用后已经变化,需要重新审查:' + relative);
for (let i = 1; i < chain.length; i++) if (chain[i].baseSha256 !== chain[i - 1].sha256 || !chain[i].baseExists) throw conflict('连续提案中混入其他修改,需要单独核对:' + relative);
const headRecord = (await this.needGit(project, ['ls-tree', '-z', snapshot.head, '--', relative])).text.split('\0').filter(Boolean);
if (headRecord.length > 1) throw conflict('交付路径没有唯一Git文件身份:' + relative);
const match = headRecord[0]?.match(/^([0-7]{6}) blob ([a-f0-9]{40}(?:[a-f0-9]{24})?)\t(.+)$/s);
if (headRecord.length && (!match || !['100644', '100755'].includes(match[1]) || match[3] !== relative)) throw conflict('链接、子模块或特殊文件不能直接交付:' + relative);
const mode = match?.[1] ?? '100644', beforeBlob = match?.[2] ?? null;
const indexed = stageEntries.filter(item => item.path === relative);
if (indexed.length && (indexed.length !== 1 || indexed[0].stage !== 0 || indexed[0].mode !== mode || indexed[0].blob !== beforeBlob)) throw conflict('选中文件已有暂存修改或冲突,提交会混入其他工作:' + relative);
const flag = snapshot.flags.split('\0').find(line => line.slice(2) === relative);
if (flag && flag[0] !== 'H') throw conflict('选中文件具有特殊Git索引标记,请先核对:' + relative);
const afterBlob = await this.blob(project, relative, bytes);
if (afterBlob === beforeBlob) continue;
let baseIndex = -1;
if (beforeBlob) {
for (let i = 0; i < chain.length; i++) {
if (chain[i].baseExists && await this.blob(project, relative, this.baseBytes(session, chain[i])) === beforeBlob) { baseIndex = i; break; }
}
if (baseIndex < 0) throw conflict('选中文件在本任务之前已有其他工作区修改,需要单独审查:' + relative);
} else if (chain[0].baseExists) throw conflict('这个未跟踪文件在任务之前已经存在,不能混入本任务提交:' + relative);
else baseIndex = 0;
const base = chain[baseIndex];
const diff = createTwoFilesPatch('a/' + relative, 'b/' + relative, base.baseContent, latest.content, '', '', { context: 3 });
const parts = diffLines(base.baseContent, latest.content);
result.push({ path: relative, changeIds: chain.slice(baseIndex).map(value => value.id), mode, beforeBlob, afterBlob,
baseSha256: base.baseSha256, sha256: latest.sha256, reason: latest.reason,
additions: parts.filter(part => part.added).reduce((sum, part) => sum + part.count, 0),
deletions: parts.filter(part => part.removed).reduce((sum, part) => sum + part.count, 0), diff: this.redact(diff) });
}
if (!result.length) throw conflict('当前任务的文件内容已在Git HEAD中,没有新的交付改动。');
if (Buffer.byteLength(result.map(file => file.diff).join('\n'), 'utf8') > 1024 * 1024) throw conflict('提交差异超过1MB预览上限,请缩小本次任务。');
return result.sort((a, b) => a.path.localeCompare(b.path));
}
async plan(session, options = {}, { source = 'user' } = {}) {
assertWorkersResolved(this.store, session.projectId);
if (workerForProject(this.store, session.projectId)) throw conflict('受限子任务不能独立Git提交;请在父任务审查合并后交付。');
const idleOptions = { exceptSessionId: source === 'agent' ? session.id : null };
this.assertIdle(session, idleOptions); const { task, run } = this.assertTask(session);
const identity = { taskId: task.id, runId: run.id }, project = this.store.project(session.projectId);
const snapshot = await this.snapshot(project), inspection = await inspectProject(project);
const check = verifiedCheck(this.store, session, inspection);
if (!check) {
const previous = this.store.core.check_job.get(task.verification.checkJobId);
if (previous?.status === 'passed' && task.verification.status === 'passed') {
previous.stale = true; previous.staleReason = 'Git交付核对发现源码或检查日志证据失效。';
task.verification = { ...task.verification, status: 'stale', reason: previous.staleReason };
this.store.save(session, { type: 'check.evidence_stale', detail: { jobId: previous.id } });
}
throw conflict('提交需要与当前源码一致、日志完整且测试数量明确的通过记录;请先执行工程检查。');
}
if (!check.sourceFingerprint) {
check.sourceFingerprint = inspection.sourceFingerprint;
task.verification = { ...task.verification, sourceFingerprint: inspection.sourceFingerprint };
}
assertBrowserResolved(this.store, session.projectId);
const browser = await currentBrowserVerification(this.store, session, inspection);
if (browser.required && browser.status !== 'passed') throw conflict('本任务已配置页面验收,请先取得当前源码与构建的实际浏览器断言通过记录。');
const taskPlan = await new TaskPlanManager(this.store).assertReady(session, { inspection });
const requirements = await new RequirementReview(this.store).assertReady(session, { inspection });
const files = await this.selectedFiles(session, project, snapshot);
const name = options.authorName ?? snapshot.config['user.name'] ?? 'Agent Workbench';
const email = options.authorEmail ?? snapshot.config['user.email'] ?? 'local@agent-workbench.invalid';
const author = { ...validAuthor(name, email), source: options.authorName || options.authorEmail ? 'explicit' : snapshot.config['user.name'] && snapshot.config['user.email'] ? 'git-config' : 'workbench-local' };
const message = validMessage(options.message ?? '完成:' + task.goal.replace(/\s+/g, ' ').slice(0, 90));
const second = await this.snapshot(project);
if (snapshot.digest !== second.digest || identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('准备提交期间工程或任务已变化,请重新预览。');
this.assertIdle(session, idleOptions); this.assertTask(session);
await new TaskPlanManager(this.store).assertReady(session, { expectedBinding: taskPlan.binding_sha256 });
await new RequirementReview(this.store).assertReady(session, { expectedBinding: requirements.binding_sha256 });
const diffArtifact = this.store.artifactStore.write(session, run, files.map(file => file.diff).join('\n'), { kind: 'delivery-diff', mediaType: 'text/plain' });
this.store.core.artifact.set(diffArtifact.id, diffArtifact);
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id, status: 'planned', createdAt: at(),
message, author, files, paths: files.map(file => file.path), snapshot, preparedBy: source, fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint,
checkJobId: check.id, checkSummary: check.results.map(value => ({ name: value.name, command: value.command, exitCode: value.exitCode, tests: value.tests, logArtifactId: value.logArtifactId })),
...(taskPlan.configured ? { taskPlanId: taskPlan.plan_id, taskPlanRevision: taskPlan.revision, taskPlanBindingSha256: taskPlan.binding_sha256 } : {}),
...(requirements.configured ? { requirementBindingSha256: requirements.binding_sha256 } : {}),
...(browser.required ? { browserJobId: browser.jobId, browserPlanId: browser.planId, browserBuildSha256: browser.buildSha256 } : {}),
protectedIndexSha256: protectedIndex(snapshot.stage, snapshot.flags, files.map(file => file.path)), diffArtifactId: diffArtifact.id,
policy: { name: 'local-reviewed-snapshot', hooks: 'disabled', signing: 'unsigned', remote: 'none',
note: '工作台生成本地普通提交,保留其他暂存与工作区改动;本次不执行仓库hooks和GPG签名。' } };
const previousReview = pendingDeliveryReview(this.store, session);
if (previousReview && source === 'user') {
const previousJob = this.store.core.delivery_job.get(previousReview.jobId);
if (previousReview.status === 'accepted' && (!previousJob || previousJob.requiresVerification || activeStates.has(previousJob.status))) throw conflict('原Git预览正在执行或结果待核对,请处理原结果后再准备。');
previousReview.status = 'superseded';
const currentRun = this.store.core.run.get(session.runId);
currentRun.review = { ...currentRun.review, kind: 'git_delivery', planId: plan.id, status: 'pending' };
}
return this.store.putRecord('delivery_plan', session, plan, 'delivery.plan');
}
discardPlan(session, id) {
this.assertIdle(session);
const plan = this.store.owned('delivery_plan', id, session.id);
const job = this.store.core.delivery_job.get(plan.jobId);
const unused = plan.status === 'planned' || plan.status === 'accepted' && job && !job.requiresVerification && !activeStates.has(job.status) && job.status !== 'completed';
if (plan.taskId !== session.taskId || plan.runId !== session.runId || !unused) throw conflict('只有当前Task/Run尚未发布或已确认未发布的Git预览可以撤回。');
resolveDeliveryReview(this.store, session, plan, 'discarded');
plan.status = 'discarded'; plan.discardedAt = at();
this.store.save(session, { type: 'delivery.plan_discarded', detail: { planId: id } });
return plan;
}
async start(session, planId) {
this.assertIdle(session); this.assertTask(session);
const plan = this.store.owned('delivery_plan', planId, session.id);
if (plan.taskId !== session.taskId || plan.runId !== session.runId || plan.status !== 'planned') throw conflict('提交计划已使用或不属于当前Task/Run,请重新预览。');
const controller = new AbortController();
const job = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: plan.taskId, runId: plan.runId, planId: plan.id,
status: 'queued', startedAt: at(), finishedAt: null, parent: plan.snapshot.head, branch: plan.snapshot.branch, paths: plan.paths,
sourceFingerprint: plan.sourceFingerprint, checkJobId: plan.checkJobId, message: plan.message, author: plan.author,
expectedCommit: null, commit: null, requiresVerification: false, originalSessionStatus: session.status, ownerPid: process.pid };
const active = { controller, sessionId: session.id, projectId: session.projectId, promise: null };
this.active.set(job.id, active); this.projects.set(session.projectId, job.id);
try {
plan.status = 'accepted'; plan.jobId = job.id;
this.store.putRecord('delivery_job', session, job, 'delivery.queued');
active.promise = this.execute(session, plan, job, controller.signal).finally(() => { this.active.delete(job.id); this.projects.delete(session.projectId); });
active.promise.catch(() => {});
return { job, promise: active.promise };
} catch (error) { this.active.delete(job.id); this.projects.delete(session.projectId); throw error; }
}
async checkpoint(session, job, phase) {
this.store.save(session, { type: 'delivery.' + phase, detail: { jobId: job.id, status: job.status } });
await this.faultInjector?.(phase, job);
}
async verifyBrowserDelivery(session, plan, inspection) {
await new RequirementReview(this.store).assertReady(session, { inspection, expectedBinding: plan.requirementBindingSha256 ?? null });
await new TaskPlanManager(this.store).assertReady(session, { inspection, expectedBinding: plan.taskPlanBindingSha256 ?? null });
assertBrowserResolved(this.store, session.projectId);
const browser = await currentBrowserVerification(this.store, session, inspection);
if (browser.required && (browser.status !== 'passed' || browser.jobId !== plan.browserJobId || browser.buildSha256 !== plan.browserBuildSha256)
|| !browser.required && plan.browserJobId) throw conflict('页面验收在Git预览后变化或已失效,请重新验证并准备交付。');
}
async execute(session, plan, job, signal) {
const project = this.store.project(session.projectId);
let lockOwned = false, keepLock = false;
try {
await this.faultInjector?.('queued', job);
const snapshot = await this.snapshot(project), inspection = await inspectProject(project);
signal.throwIfAborted();
if (session.taskId !== plan.taskId || session.runId !== plan.runId || snapshot.digest !== plan.snapshot.digest || inspection.fingerprint !== plan.fingerprint) throw conflict('提交预览后工程、Git索引或Task/Run已变化,没有执行提交。');
if (!verifiedCheck(this.store, session, inspection)) throw conflict('提交前检查证据已失效,请重新运行工程检查。');
await this.verifyBrowserDelivery(session, plan, inspection);
const selected = await this.selectedFiles(session, project, snapshot);
if (JSON.stringify(selected) !== JSON.stringify(plan.files)) throw conflict('当前文件与已审核提交清单不一致。');
signal.throwIfAborted();
job.status = 'preparing'; session.status = 'running';
job.indexPath = snapshot.indexPath; job.indexBeforeSha256 = snapshot.indexSha256;
job.lockPath = snapshot.indexPath + '.lock'; job.lockMarkerSha256 = sha('Agent Workbench index lock ' + job.id + '\n');
await this.checkpoint(session, job, 'preparing');
fs.writeFileSync(job.lockPath, 'Agent Workbench index lock ' + job.id + '\n', { flag: 'wx', mode: 0o600 }); lockOwned = true;
await this.checkpoint(session, job, 'index_locked');
if (digestFile(job.indexPath) !== snapshot.indexSha256) throw conflict('锁定索引前Git暂存区已经变化。');
const directory = path.join(this.directory, job.id); fs.mkdirSync(directory);
const deliveryIndex = path.join(directory, 'commit.index'), nextIndex = path.join(directory, 'next.index');
fs.copyFileSync(job.indexPath, nextIndex);
await this.needGit(project, ['read-tree', snapshot.head], { env: { GIT_INDEX_FILE: deliveryIndex }, signal });
for (const file of plan.files) {
const bytes = fs.readFileSync(safePath(project, file.path));
if (sha(bytes) !== file.sha256 || await this.blob(project, file.path, bytes, { write: true, signal }) !== file.afterBlob) throw conflict('准备提交对象时文件内容变化:' + file.path);
}
const indexInfo = plan.files.map(file => file.mode + ' ' + file.afterBlob + '\t' + file.path + '\0').join('');
for (const indexFile of [deliveryIndex, nextIndex]) await this.needGit(project, ['update-index', '-z', '--index-info'], { input: indexInfo, env: { GIT_INDEX_FILE: indexFile }, signal });
const nextBytes = fs.readFileSync(nextIndex); job.indexAfterSha256 = sha(nextBytes);
fs.writeFileSync(job.lockPath, nextBytes);
const handle = fs.openSync(job.lockPath, 'r+'); try { fs.fsyncSync(handle); } finally { fs.closeSync(handle); }
job.tree = (await this.needGit(project, ['write-tree'], { env: { GIT_INDEX_FILE: deliveryIndex }, signal })).text.trim();
if (!oid(job.tree)) throw new Error('Git交付树没有有效身份。');
const message = plan.message + '\n\nWorkbench-Delivery: ' + job.id + '\nWorkbench-Task: ' + job.taskId + '\nWorkbench-Session: ' + job.sessionId + '\n';
const date = at();
job.expectedCommit = (await this.needGit(project, ['commit-tree', job.tree, '-p', snapshot.head], { input: message, signal,
env: { GIT_AUTHOR_NAME: plan.author.name, GIT_AUTHOR_EMAIL: plan.author.email, GIT_COMMITTER_NAME: plan.author.name,
GIT_COMMITTER_EMAIL: plan.author.email, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date } })).text.trim();
if (!oid(job.expectedCommit)) throw new Error('Git提交对象没有有效身份。');
job.status = 'prepared'; await this.checkpoint(session, job, 'prepared');
signal.throwIfAborted();
await this.publishReference(project, session, plan, job, signal);
job.status = 'committed'; job.commit = job.expectedCommit; await this.checkpoint(session, job, 'committed');
await this.finishPublished(project, session, plan, job);
lockOwned = false; job.status = 'reporting'; job.requiresVerification = false;
job.summary = '已生成并核对本地提交;任务文件、实际检查和其他工作区/暂存改动均已保留。';
} catch (error) {
keepLock = !!job.referenceAttempted;
job.status = keepLock ? 'unknown' : signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed';
job.requiresVerification = keepLock;
job.summary = this.redact(keepLock ? 'Git引用可能已更新,需要核对实际结果;不会再次提交。' + ' ' + error.message : error.message);
} finally {
if (lockOwned && !keepLock) this.releaseOwnedLock(job);
job.stopRequested = signal.aborted; job.finishedAt = at(); session.status = job.originalSessionStatus;
if (job.status === 'reporting') resolveDeliveryReview(this.store, session, plan, 'committed', job);
await this.checkpoint(session, job, 'finished');
}
if (job.status === 'reporting') {
try {
const inspection = await inspectProject(project);
job.status = 'completed';
await this.reporter.create(session, { job, inspection });
} catch (error) {
job.status = 'completed'; job.reportError = this.redact(error.message);
this.store.save(session, { type: 'delivery.report_failed', detail: { jobId: job.id } });
}
}
return job;
}
async publishReference(project, session, plan, job, signal) {
const child = spawn('git', gitArguments(safePath(project), ['update-ref', '-m', 'Agent Workbench delivery ' + job.id, '--stdin'], this.hooksDirectory),
{ env: gitEnvironment(), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
job.refProcessPid = child.pid ?? null;
let output = '', errors = '', commitSent = false, preparedResolve;
const prepared = new Promise(resolve => { preparedResolve = resolve; });
child.stdin.on('error', () => {});
child.stdout.on('data', bytes => { output += bytes.toString('utf8'); if (output.includes('prepare: ok')) preparedResolve(true); });
child.stderr.on('data', bytes => { errors = (errors + bytes.toString('utf8')).slice(-8000); });
const done = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', code => resolve(code)); });
done.catch(() => {});
const timer = setTimeout(() => child.kill(), 15000);
const stop = () => { if (!commitSent && !child.stdin.writableEnded) child.stdin.end('abort\n'); };
signal.addEventListener('abort', stop, { once: true });
try {
await this.checkpoint(session, job, 'ref_started');
child.stdin.write('start\nupdate HEAD ' + job.expectedCommit + ' ' + plan.snapshot.head + '\nprepare\n');
const ready = await Promise.race([prepared, done.then(() => false)]);
if (!ready) throw conflict(errors.trim() || 'Git没有锁定原HEAD,未发布提交。');
const actualRef = (await this.needGit(project, ['symbolic-ref', '--quiet', 'HEAD'])).text.trim();
if (actualRef !== plan.snapshot.reference || digestFile(job.indexPath) !== job.indexBeforeSha256) throw conflict('Git锁定后当前分支或索引与提交计划不同,未发布提交。');
const inspection = await inspectProject(project);
if (inspection.sourceFingerprint !== plan.sourceFingerprint || !verifiedCheck(this.store, session, inspection)) throw conflict('Git锁定后源码或实际检查已经变化,未发布提交。');
await this.verifyBrowserDelivery(session, plan, inspection);
await this.checkpoint(session, job, 'ref_prepared');
signal.throwIfAborted();
job.status = 'publishing'; job.referenceAttempted = true;
await this.checkpoint(session, job, 'publishing');
commitSent = true; child.stdin.end('commit\n');
const code = await done;
if (code !== 0 || !output.includes('commit: ok')) throw new Error(this.redact(errors.trim() || 'Git发布未返回确认结果。'));
} finally {
if (!commitSent && !child.stdin.writableEnded) child.stdin.end('abort\n');
await done.catch(() => {});
job.refProcessPid = null;
clearTimeout(timer); signal.removeEventListener('abort', stop);
}
}
async verifyPublished(project, plan, job) {
if (!oid(job.expectedCommit ?? '') || !oid(job.tree ?? '')) throw conflict('提交缺少持久对象身份,不能猜测或重放。');
const [head, ref, tree, parents, commit, changed] = await Promise.all([
this.needGit(project, ['rev-parse', 'HEAD']), this.git(project, ['symbolic-ref', '--quiet', 'HEAD']),
this.needGit(project, ['rev-parse', job.expectedCommit + '^{tree}']),
this.needGit(project, ['rev-list', '--parents', '-n', '1', job.expectedCommit]),
this.needGit(project, ['cat-file', 'commit', job.expectedCommit]),
this.needGit(project, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', plan.snapshot.head, job.expectedCommit]),
]);
if (head.text.trim() !== job.expectedCommit || ref.text.trim() !== plan.snapshot.reference) throw conflict('当前HEAD或分支与本次预期提交不同,需要人工核对引用变化。');
if (tree.text.trim() !== job.tree || parents.text.trim() !== job.expectedCommit + ' ' + plan.snapshot.head
|| !commit.text.endsWith('Workbench-Delivery: ' + job.id + '\nWorkbench-Task: ' + job.taskId + '\nWorkbench-Session: ' + job.sessionId + '\n')) throw conflict('实际提交对象、父节点或任务身份与本次计划不同。');
if (JSON.stringify(changed.text.split('\0').filter(Boolean).sort()) !== JSON.stringify(plan.paths.slice().sort())) throw conflict('实际Git提交路径超出本次审核范围。');
for (const file of plan.files) {
const actual = (await this.needGit(project, ['ls-tree', '-z', job.expectedCommit, '--', file.path])).text;
if (actual !== file.mode + ' blob ' + file.afterBlob + '\t' + file.path + '\0') throw conflict('实际提交文件与已审核快照不同:' + file.path);
}
return true;
}
async finishPublished(project, session, plan, job) {
// Inspect our exact index/lock bytes before Git reads an externally damaged
// index. Recheck after verifying the commit before publishing the index.
const beforeIndex = digestFile(job.indexPath), beforeLock = digestFile(job.lockPath);
if (beforeIndex === job.indexAfterSha256) {
if (fs.existsSync(job.lockPath)) throw conflict('索引已发布但仍有其他锁,请核对该操作。');
} else if (beforeIndex !== job.indexBeforeSha256 || beforeLock !== job.indexAfterSha256) {
throw conflict('提交已存在,但索引或遗留锁已被其他操作修改,保留现场。');
}
await this.verifyPublished(project, plan, job);
if (normalize(fs.realpathSync.native(path.dirname(job.indexPath))) !== normalize(plan.snapshot.gitDir)) throw conflict('Git索引目录的实际位置已变化,保留本次现场。');
if (digestFile(job.indexPath) === job.indexAfterSha256) {
// An exit after the atomic index rename is recoverable without rewriting.
if (fs.existsSync(job.lockPath)) throw conflict('索引已发布但仍有其他锁,请核对该操作。');
} else {
if (digestFile(job.indexPath) !== job.indexBeforeSha256 || digestFile(job.lockPath) !== job.indexAfterSha256) throw conflict('提交已存在,但索引或遗留锁已被其他操作修改,保留现场。');
fs.renameSync(job.lockPath, job.indexPath);
}
await this.checkpoint(session, job, 'index_published');
const [stage, flags, inspection] = await Promise.all([this.needGit(project, ['ls-files', '--stage', '-z']), this.needGit(project, ['ls-files', '-v', '-z']), inspectProject(project)]);
job.indexPreserved = protectedIndex(stage.text, flags.text, plan.paths) === plan.protectedIndexSha256;
job.workspacePreserved = inspection.sourceFingerprint === plan.sourceFingerprint;
if (!job.indexPreserved || !job.workspacePreserved) throw conflict('提交已经存在,但工作区或无关索引条目发生变化,需要核对实际结果。');
job.commit = job.expectedCommit;
}
releaseOwnedLock(job) {
if (!job.lockPath || !fs.existsSync(job.lockPath)) return;
const actual = digestFile(job.lockPath);
if (actual === job.lockMarkerSha256 || actual === job.indexAfterSha256) fs.unlinkSync(job.lockPath);
}
async reconcile(session, jobId) {
this.assertIdle(session);
const job = this.store.owned('delivery_job', jobId, session.id), plan = this.store.owned('delivery_plan', job.planId, session.id);
if (job.status === 'completed') return job;
if (!['unknown', 'interrupted', 'failed', 'stale', 'cancelled'].includes(job.status)) throw conflict('提交仍在执行,请等待结束后核对。');
if (job.ownerPid !== process.pid && pidAlive(job.ownerPid) || pidAlive(job.refProcessPid)) throw conflict('原提交进程可能仍在运行,先等待实际进程结束。');
const project = this.store.project(session.projectId);
const reservation = { sessionId: session.id, projectId: session.projectId, controller: new AbortController(), promise: Promise.resolve() };
this.active.set(job.id, reservation); this.projects.set(session.projectId, job.id);
reservation.promise = this.reconcileOwned(session, job, plan, project).finally(() => { this.active.delete(job.id); this.projects.delete(session.projectId); });
reservation.promise.catch(() => {});
return reservation.promise;
}
async reconcileOwned(session, job, plan, project) {
const currentIndex = (await this.needGit(project, ['rev-parse', '--path-format=absolute', '--git-path', 'index'])).text.trim();
if (normalize(currentIndex) !== normalize(plan.snapshot.indexPath) || job.indexPath && normalize(job.indexPath) !== normalize(currentIndex)) throw conflict('项目Git索引位置已变化,不能修复旧索引。');
const head = (await this.needGit(project, ['rev-parse', 'HEAD'])).text.trim();
if (head === job.expectedCommit) {
await this.finishPublished(project, session, plan, job); job.status = 'completed'; job.requiresVerification = false;
job.summary = '已核对中断前的实际提交并修复本次索引发布;没有重新执行提交。';
resolveDeliveryReview(this.store, session, plan, 'committed', job);
} else if (head === plan.snapshot.head && (await this.needGit(project, ['symbolic-ref', '--quiet', 'HEAD'])).text.trim() === plan.snapshot.reference) {
if (job.lockPath && fs.existsSync(job.lockPath)) {
if (digestFile(job.indexPath) !== job.indexBeforeSha256 || ![job.lockMarkerSha256, job.indexAfterSha256].includes(digestFile(job.lockPath))) throw conflict('遗留索引锁与原基线不同,不能删除其他操作的锁。');
this.releaseOwnedLock(job);
}
job.status = 'interrupted'; job.requiresVerification = false; job.summary = '已核对原HEAD,本次预期提交未挂到当前分支;本次遗留锁已清理,没有重放。需要新预览才能提交。';
} else throw conflict('Git引用与保存的结果不一致,无法确认提交;保留需核对状态,不会重放。');
job.reconciledAt = at(); this.store.save(session, { type: 'delivery.reconciled', detail: { jobId: job.id, status: job.status } });
if (job.status === 'completed' && session.taskId === job.taskId) await this.reporter.create(session, { job });
return job;
}
async report(session, { source = 'user' } = {}) {
this.assertIdle(session, { exceptSessionId: source === 'agent' ? session.id : null });
const id = randomUUID(), reservation = { sessionId: session.id, projectId: session.projectId, controller: new AbortController(), promise: null };
this.active.set(id, reservation); this.projects.set(session.projectId, id);
reservation.promise = (async () => {
const inspection = await inspectProject(this.store.project(session.projectId));
reservation.controller.signal.throwIfAborted();
return this.reporter.create(session, { inspection });
})().finally(() => { this.active.delete(id); this.projects.delete(session.projectId); });
reservation.promise.catch(() => {});
return reservation.promise;
}
async stop(sessionId, jobId) {
if (jobId) this.store.owned('delivery_job', jobId, sessionId);
const values = [...this.active.entries()].filter(([id, value]) => value.sessionId === sessionId && (!jobId || id === jobId));
for (const [, value] of values) value.controller.abort(new Error('用户停止Git交付'));
await Promise.all(values.map(([, value]) => value.promise));
}
async stopAll() { await Promise.all([...new Set([...this.active.values()].map(value => value.sessionId))].map(id => this.stop(id))); }
}
@@ -0,0 +1,190 @@
import { randomUUID } from 'node:crypto';
import { TaskPlanManager } from './task-plan-manager.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { taskContract } from '../../shared/contracts/task-control.mjs';
import { taskPlanInput, planHash, planError } from '../../shared/contracts/task-plans.mjs';
import { readText } from '../../server/files.mjs';
import { FileResults } from './file-results.mjs';
const same = (a, b) => planHash(a) === planHash(b);
const now = () => new Date().toISOString();
const checkKeys = (value, keys) => {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !keys.includes(key)))
throw planError('要求复核包含未声明字段。', 'input', 400);
};
const requiredText = (value, max) => {
if (typeof value !== 'string' || !value.trim() || value.length > max || value.includes('\0')) throw planError('请填写有效的要求或复核说明。', 'input', 400);
return value.trim();
};
export function requirementSources(task) {
return [{ kind: 'goal', id: task.id, text: task.goal, at: task.createdAt ?? null },
...(task.instructions ?? []).filter(row => row.source !== 'review-action').map(row => ({ kind: 'instruction', id: row.id, text: row.content, at: row.createdAt ?? row.at ?? null }))]
.map(row => ({ ...row, sha256: planHash({ kind: row.kind, id: row.id, text: row.text }) }));
}
function itemInput(value, sources) {
checkKeys(value, ['key', 'title', 'criterion', 'source', 'kind', 'tools', 'paths', 'checks', 'viewport_width', 'actions', 'method']);
checkKeys(value.source, ['kind', 'id', 'start', 'end']);
const original = sources.find(row => row.kind === value.source.kind && row.id === value.source.id);
const { start, end } = value.source;
if (!original || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end <= start || end > original.text.length)
throw planError('要求来源必须是当前Task用户原文的有效范围。', 'input', 400);
const method = value.method ?? 'evidence';
if (!['evidence', 'user', 'not_requested'].includes(method)) throw planError('复核方式无效。', 'input', 400);
const { source, method: ignored, ...fields } = value;
// Reuse the existing bounded evidence scopes; a statement alone never passes.
const step = taskPlanInput({ expected_revision: 0, steps: [{ ...fields, depends_on: [] }] }).steps[0];
if (method === 'not_requested' && step.kind !== 'checks') throw planError('仅检查约定可记录为未执行。', 'input', 400);
return { ...step, method, source: { ...source, quote: original.text.slice(start, end), sourceSha256: original.sha256, at: original.at } };
}
const ledgerContract = row => ({ schemaVersion: 1, kind: 'task-requirements', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
taskId: row.taskId, runId: row.runId, revision: row.revision, parentId: row.parentId, items: row.items, sources: row.sources, createdAt: row.createdAt });
const proofContract = row => ({ schemaVersion: 1, kind: 'requirement-proof', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
taskId: row.taskId, runId: row.runId, key: row.key, requirementSha256: row.requirementSha256, requirementRevision: row.requirementRevision,
evidenceId: row.evidenceId, outcome: row.outcome, sourceFingerprint: row.sourceFingerprint, status: row.status, error: row.error,
note: row.note, createdAt: row.createdAt });
// This ledger lives on the existing Task. It delegates all engineering proof
// checks to TaskPlanManager and grants no tool, command or file permissions.
export class RequirementReview {
constructor(store, { planner = new TaskPlanManager(store), redact = String } = {}) { this.store = store; this.planner = planner; this.redact = redact; }
current(session) { return this.store.owned('task', session.taskId, session.id).requirementRevisions?.at(-1) ?? null; }
verifyRecord(session, row, kind, contract) {
if (row.sessionId !== session.id || row.projectId !== session.projectId || row.taskId !== session.taskId) throw planError('要求记录不属于当前项目和Task。');
const original = this.planner.artifact(session, row.contractArtifactId, kind, row.taskId, row.runId);
if (original.artifact.sha256 !== row.contractSha256 || original.text !== JSON.stringify(contract(row))) throw planError('要求或复核记录与原工件不一致。');
}
write(session, run, row, kind, contract) {
const artifact = this.store.artifactStore.write(session, run, contract(row), { kind });
this.store.core.artifact.set(artifact.id, artifact);
return { ...row, contractArtifactId: artifact.id, contractSha256: artifact.sha256 };
}
async evidence(session, item, id, inspection) {
if (item.kind === 'results') {
const result = new FileResults(this.store).verify(session, id, { current: false });
if (result.taskId !== session.taskId || !item.paths.every(file => result.files.some(row => row.path === file)))
throw planError('成果凭据不属于当前Task或未覆盖要求文件。');
const files = result.files.filter(file => item.paths.includes(file.path));
for (const file of files) if (readText(this.store.project(session.projectId), file.path).sha256 !== file.sha256)
throw planError('当前要求的成果文件SHA已变化。', 'stale');
const artifact = this.store.owned('artifact', result.contractArtifactId, session.id);
return { kind: 'file_result', id: result.id, runId: result.runId, scope: 'current_requirement_files',
files: files.map(({ path, sha256, origin }) => ({ path, sha256, origin })),
artifacts: [{ id: artifact.id, kind: artifact.kind, runId: artifact.runId, sha256: artifact.sha256, bytes: artifact.bytes }] };
}
const outcome = await this.planner.evidence(session, item, id, { inspection });
if (item.kind === 'analysis') {
const record = this.store.owned('tool', id, session.id);
const result = JSON.parse(this.planner.artifact(session, record.resultArtifactId, 'tool-result', record.taskId, record.runId).text);
if (record.tool === 'read_file' && (!result.sha256 || readText(this.store.project(session.projectId), result.path).sha256 !== result.sha256))
throw planError('原读取对应旧文件SHA,请使用当前文件的实际读取。', 'stale');
if (record.tool === 'inspect_project' && result.sourceFingerprint !== inspection.sourceFingerprint)
throw planError('原工程观察对应旧源码输入。', 'stale');
}
return outcome;
}
save(session, input) { return this.planner.mutate(session, 'user', async () => {
checkKeys(input, ['expected_revision', 'requirements']);
const { task, run } = this.planner.task(session), previous = this.current(session), revision = previous?.revision ?? 0;
if (previous) this.verifyRecord(session, previous, 'task-requirements', ledgerContract);
if (input.expected_revision !== revision) throw planError('要求修订已变化,请刷新后保存。', 'stale');
if (revision >= 24 || !Array.isArray(input.requirements) || !input.requirements.length || input.requirements.length > 24)
throw planError('每个Task最多24项要求与24次修订。', 'input', 400);
const sources = requirementSources(task), items = input.requirements.map(value => itemInput(value, sources));
if (new Set(items.map(row => row.key)).size !== items.length || previous?.items.some(row => !items.some(item => item.key === row.key)))
throw planError('要求ID需唯一;原要求不能删除,可修订并保留原记录。', 'input', 400);
if (JSON.stringify(items).length > 24000) throw planError('要求范围过大,请缩小Task。', 'input', 400);
for (const item of items) {
if (item.method === 'not_requested' && taskContract(task).checks !== 'skip') throw planError('当前用户约定没有跳过检查,不能标为按约定未执行。');
const old = previous?.items.find(row => row.key === item.key);
const { revision: oldRevision, ...oldContent } = old ?? {};
item.revision = old && same(oldContent, item) ? oldRevision : (oldRevision ?? 0) + 1;
}
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
if (session.taskId !== task.id || session.runId !== run.id || this.current(session)?.id !== previous?.id || !same(sources, requirementSources(task)))
throw planError('保存期间原任务、来源或要求已变化。', 'stale');
const row = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
revision: revision + 1, parentId: previous?.id ?? null, items, sources, createdAt: now() }, 'task-requirements', ledgerContract);
(task.requirementRevisions ??= []).push(row);
this.store.save(session, { type: 'task.requirements_saved', detail: { id: row.id, revision: row.revision } });
return row;
}); }
async inspect(session, { candidates = false, inspection = null } = {}) {
const { task, run } = this.planner.task(session), ledger = this.current(session), sources = requirementSources(task);
const base = { configured: !!ledger, task_id: task.id, revision: ledger?.revision ?? 0, sources, items: [], all_resolved: false, binding_sha256: null,
note: '证据核对只证明所选范围;模型完成答复不等于业务验收。' };
if (!ledger) return { ...base, status: 'not_recorded', unreviewed_sources: sources.map(row => row.id) };
try { this.verifyRecord(session, ledger, 'task-requirements', ledgerContract); }
catch (error) { return { ...base, status: 'unverified', error: this.redact(error.message) }; }
const unreviewed = sources.filter(row => !ledger.sources.some(old => old.id === row.id && old.sha256 === row.sha256)).map(row => row.id);
const items = [], proofs = task.requirementProofs ?? [];
for (const item of ledger.items) {
const source = sources.find(row => row.id === item.source.id && row.kind === item.source.kind);
const proof = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item) && row.status === 'verified');
const attempt = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item));
let status = 'pending', error = null, outcome = null;
try {
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('原用户来源已变化。', 'stale');
if (item.method === 'not_requested') {
if (taskContract(task).checks !== 'skip') throw planError('当前检查约定已变化。', 'stale');
status = 'not_requested';
} else if (proof) {
this.verifyRecord(session, proof, 'requirement-proof', proofContract);
const sourceRead = item.kind === 'analysis' && this.store.core.tool.get(proof.evidenceId)?.tool === 'read_file';
if (item.kind === 'analysis' || item.method === 'user') {
inspection ??= await inspectProject(this.store.project(session.projectId));
if (!inspection.scope.complete || !sourceRead && proof.sourceFingerprint !== inspection.sourceFingerprint) throw planError('复核后源码输入已变化。', 'stale');
}
if (item.method !== 'user') {
outcome = await this.evidence(session, item, proof.evidenceId, inspection);
if (!same(outcome, proof.outcome)) throw planError('实际记录与原复核结果不一致。', 'stale');
}
status = item.method === 'user' ? 'user_confirmed' : 'evidence_verified';
} else if (attempt?.status === 'rejected') status = 'failed';
} catch (cause) { status = cause.code === 'stale' ? 'stale' : 'unverified'; error = this.redact(cause.message); }
items.push({ ...item, status, error, evidence: outcome, proof_id: proof?.id ?? null, proof_artifact_id: proof?.contractArtifactId ?? null,
user_note: status === 'user_confirmed' ? proof.note : null,
last_rejection: attempt?.status === 'rejected' ? { id: attempt.id, message: attempt.error, at: attempt.createdAt } : null,
...(candidates && item.method === 'evidence' ? { candidates: this.planner.candidates(session, item) } : {}) });
}
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('核对期间Task/Run或要求已变化。', 'stale');
const resolved = !unreviewed.length && items.every(row => ['evidence_verified', 'user_confirmed', 'not_requested'].includes(row.status));
return { ...base, items, unreviewed_sources: unreviewed, status: resolved ? 'resolved' : 'incomplete', all_resolved: resolved,
history: proofs.map(row => ({ id: row.id, key: row.key, revision: row.requirementRevision, status: row.status, error: row.error, at: row.createdAt, artifact_id: row.contractArtifactId })),
contract_artifact_id: ledger.contractArtifactId, contract_sha256: ledger.contractSha256,
binding_sha256: resolved ? planHash({ ledger: ledger.contractSha256, proofs: items.map(row => [row.key, row.proof_id, row.status, row.evidence]) }) : null };
}
verify(session, input) { return this.planner.mutate(session, 'user', async () => {
checkKeys(input, ['expected_revision', 'key', 'evidence_id', 'note']);
const { task, run } = this.planner.task(session), ledger = this.current(session);
if (!ledger || ledger.revision !== input.expected_revision) throw planError('要求修订已变化,请刷新后复核。', 'stale');
this.verifyRecord(session, ledger, 'task-requirements', ledgerContract);
const item = ledger.items.find(row => row.key === input.key);
if (!item || item.method === 'not_requested') throw planError('请选择需要复核的当前要求。');
if ((task.requirementProofs?.length ?? 0) >= 128) throw planError('复核记录已到上限,请缩小任务。');
if (item.method === 'user' ? input.evidence_id !== undefined : input.note !== undefined) throw planError('用户确认和原证据核对不能混用。', 'input', 400);
const note = item.method === 'user' ? requiredText(input.note, 1000) : null;
let outcome = null, inspection = null, error = null;
try {
const source = requirementSources(task).find(row => row.kind === item.source.kind && row.id === item.source.id);
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('用户要求来源已变化。', 'stale');
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
inspection = await inspectProject(this.store.project(session.projectId));
if (!inspection.scope.complete) throw planError('源码范围不完整,不能复核。');
if (item.method !== 'user') outcome = await this.evidence(session, item, input.evidence_id, inspection);
} catch (cause) { error = this.redact(cause.message); }
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('复核期间任务或要求已变化。', 'stale');
const proof = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
key: item.key, requirementSha256: planHash(item), requirementRevision: item.revision, evidenceId: input.evidence_id ?? null,
sourceFingerprint: inspection?.sourceFingerprint ?? null, outcome, status: error ? 'rejected' : 'verified', error, note, createdAt: now() }, 'requirement-proof', proofContract);
(task.requirementProofs ??= []).push(proof);
this.store.save(session, { type: error ? 'task.requirement_rejected' : 'task.requirement_verified', detail: { id: proof.id, key: item.key } });
return { status: error ? 'error' : 'completed', proof_id: proof.id, ...(error ? { message: error } : {}) };
}); }
async assertReady(session, { inspection = null, expectedBinding = undefined } = {}) {
const view = await this.inspect(session, { inspection });
if (view.configured && !view.all_resolved) throw planError('用户要求仍有待复核、失效或未审阅来源,请先核对要求与证据。', 'stale');
if (expectedBinding !== undefined && expectedBinding !== view.binding_sha256) throw planError('Git预览后的要求或证据已变化,请重新预览。', 'stale');
return view;
}
}
@@ -0,0 +1,929 @@
import { validateRuntimeBudgets } from '../core/models/runtime-settings.mjs';
import fs from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { listFiles, readText, proposeFile, proposePatch, applyChange } from './files.mjs';
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
import { inspectProject } from '../core/project-inspector.mjs';
import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
import { publicEngineJob } from '../shared/contracts/engines.mjs';
import { publicEngineRun, verifyEngineInput, originalEngineRun } from '../shared/contracts/engine-execution.mjs';
import { resolvePurgeSource,resolveOriginalPurgeSource,ORIGINAL_PURGE_KIND } from '../core/engines/purge-strategy.mjs';
import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
import { ConfigImporter } from '../core/models/config-import.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
import { companionGateway } from './companion-gateway.mjs';
import { inspectOperations } from './operations.mjs';
import { validateModelWaitSettings } from '../core/models/request-deadline.mjs';
import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs';
import { localDirectories } from './local-directories.mjs';
import { readInstallationProgress } from '../core/desktop/installation-progress.mjs';
export function createSessionPublisher(clients) {
return session => {
const snapshot = JSON.stringify({ kind: 'session', seq: session.eventSeq, session });
// Large source/Run receipts stay in the session API. Repeatedly queueing
// them on SSE can disconnect a healthy reader before it receives a cursor.
const data = Buffer.byteLength(snapshot) <= 64 * 1024 ? snapshot : JSON.stringify({ kind: 'session_changed', seq: session.eventSeq,
sessionId: session.id, projectId: session.projectId, revision: session.revision });
const payload = (session.eventSeq ? 'id: ' + session.eventSeq + '\n' : '') + 'data: ' + data + '\n\n';
for (const response of clients) {
if (response.destroyed || response.writableEnded || response.writableLength > 2 * 1024 * 1024) { response.destroy(); clients.delete(response); }
else response.write(payload);
}
};
}
function cursorNumber(value) {
if (value === undefined || value === null || value === '') return 0;
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw new Error('事件游标无效。');
return Number(value);
}
export function createRequestHandler({ appDirectory, server, store, provider, runtime, token, clients, started, getPort, exampleProject, shutdown }) {
const host = () => hostAuthority({ appDirectory, server, store, provider, runtime });
const research = [
{ id: 'overview', title: '统一机制报告', file: 'RESEARCH.md', description: '研究结论、证据与本产品采用的独立设计。' },
{ id: 'cursor', title: 'Cursor:执行与编辑', file: 'research/CURSOR-MECHANISMS.md', description: '工具能力、执行事件、取消、恢复与文本改动。' },
{ id: 'context', title: 'Claude Code:上下文与恢复', file: 'research/CONTEXT-RECOVERY.md', description: '压缩预算、摘要校验、会话链与未完成调用。' },
{ id: 'tools', title: 'Claude Code:工具循环', file: 'research/TOOL-LOOP.md', description: '参数校验、队列、并发安全与权限判断。' },
];
const memories = new ProjectMemoryManager(store);
function json(response, value, status = 200) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff' });
response.end(JSON.stringify(value));
}
async function body(request, maximum=2*1024*1024) {
if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw Object.assign(new Error('请求需要 JSON。'), { status: 415 });
const chunks = []; let length = 0;
for await (const chunk of request) {
length += chunk.length;
if (length > maximum) throw Object.assign(new Error('请求超过允许大小。'), { status: 413 });
chunks.push(chunk);
}
let input;
try { input = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); } catch { throw Object.assign(new Error('请求 JSON 无效。'), { status: 400 }); }
if (!input || typeof input !== 'object' || Array.isArray(input)) throw Object.assign(new Error('请求需要 JSON 对象。'), { status: 400 });
return input;
}
function allowRequest(request, url) {
const actualPort = getPort();
const allowed = ['127.0.0.1:' + actualPort, 'localhost:' + actualPort];
if (!allowed.includes(request.headers.host)) throw Object.assign(new Error('服务仅接受本地工作台地址。'), { status: 421 });
const origin = request.headers.origin;
if (origin && !allowed.map(host => 'http://' + host).includes(origin)) throw Object.assign(new Error('请求来源不属于本地工作台。'), { status: 403 });
if (url.pathname.startsWith('/api/') && !['/api/health', '/api/bootstrap'].includes(url.pathname)) {
const supplied = request.headers['x-workbench-token'] || (url.pathname === '/api/events' ? url.searchParams.get('token') : '');
if (supplied !== token) throw Object.assign(new Error('请重新打开工作台以更新连接。'), { status: 403 });
}
}
return async (request, response) => {
try {
response.setHeader('Referrer-Policy', 'no-referrer');
response.setHeader('X-Frame-Options', 'DENY');
// Scripts and API requests belong to this workbench origin. Inline styles
// are limited to the existing React layout; model text never becomes HTML.
response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
const actualPort = getPort();
if (server && (!server.listening || server.address().port !== actualPort)) throw new Error('本地执行宿主已经变化,请重新连接工作台。');
const url = new URL(request.url, 'http://127.0.0.1:' + actualPort);
allowRequest(request, url);
const method = request.method;
const route = url.pathname;
if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: server?.workbenchReady !== false, uptimeMs: Date.now() - started });
if (route.startsWith('/api/companion')) {
const gateway = companionGateway({ appDirectory, server, store, provider, runtime });
if (method === 'GET' && route === '/api/companion') return json(response, gateway.status());
if (method === 'POST' && route === '/api/companion/start') return json(response, await gateway.start(await body(request)));
if (method === 'POST' && route === '/api/companion/close') { const value = await body(request); if (Object.keys(value).length) throw Object.assign(new Error('关闭手机连接不接受额外字段。'), { status: 400 }); return json(response, await gateway.close()); }
if (method === 'POST' && route === '/api/companion/pair') return json(response, await gateway.pairing(await body(request)));
const revoke = route.match(/^\/api\/companion\/devices\/([a-f0-9-]+)\/revoke$/);
if (method === 'POST' && revoke) {
const value = await body(request);
if (Object.keys(value).length !== 1 || !Number.isSafeInteger(value.revision)) throw Object.assign(new Error('设备撤销需要原登记修订。'), { status: 400 });
return json(response, gateway.revoke(revoke[1], value.revision));
}
if (method === 'GET' && route === '/api/companion/certificate') {
const certificate = gateway.tls.publicCertificate();
response.writeHead(200, { 'Content-Type': 'application/pkix-cert', 'Content-Disposition': 'attachment; filename="Agent-Workbench-Mobile-CA.cer"', 'Cache-Control': 'no-store' });
return response.end(certificate.bytes);
}
return json(response, { error: '手机连接管理操作不存在。' }, 404);
}
if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge')));
if (method === 'GET' && route === '/api/host/status') return json(response, host().status());
if (method === 'GET' && route === '/api/installation/status') return json(response, { ...readInstallationProgress({ appRoot: appDirectory, dataRoot: store.directory }), runningVersion: APP_VERSION });
if (method === 'POST' && route === '/api/host/windows/register') return json(response, host().registerWindow(await body(request)));
if (method === 'POST' && route === '/api/host/windows/unregister') {
const input = await body(request); const result = host().unregisterWindow(input); runtime.browsing?.disconnect(input.windowId); return json(response, result);
}
if (method === 'POST' && /^\/api\/browsing-desktop\/(poll|complete|validate)$/.test(route)) {
const input = await body(request, 12 * 1024 * 1024), owner = input.owner, registered = host().windows?.get(owner?.windowId);
if (!registered || ['windowId','pid','createdAt','instanceId','runtimeIdentity'].some(key => registered[key] !== owner[key])) throw Object.assign(new Error('原桌面进程登记已变化。'), { status: 403 });
runtime.workbenchOrigin = 'http://127.0.0.1:' + actualPort; const manager = runtime.browsingManager(); manager.workbenchOrigin = runtime.workbenchOrigin;
if (route.endsWith('/poll')) return json(response, manager.poll(owner.windowId, input.states));
if (route.endsWith('/validate')) {
const pending = manager.active.get(input.id);
if (!pending || pending.job.windowId !== owner.windowId || pending.nonce !== input.nonce || !pending.job.dispatchedAt) throw Object.assign(new Error('原动作已经停止或授权已撤销。'), { status: 409 });
return json(response, { valid: true });
}
return json(response, manager.complete(owner.windowId, input));
}
if (method === 'POST' && route === '/api/host/stop') {
const result = await host().stop(await body(request)); json(response, result); setTimeout(shutdown, 100); return;
}
if (!['GET', 'HEAD'].includes(method) && server?.workbenchHostAuthority?.stopping) throw Object.assign(new Error('执行宿主正在停止,请等待所属操作结束。'), { status: 409 });
const skillsMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/skills(?:\/(toggle|refresh|content))?$/i);
if (skillsMatch) {
const registry = runtime.skillRegistry(), projectId = skillsMatch[1], action = skillsMatch[2];
if (method === 'GET' && !action) return json(response, registry.view(projectId));
if (method === 'GET' && action === 'content') return json(response, registry.content(projectId, url.searchParams.get('id'), Number(url.searchParams.get('revision'))));
if (method === 'POST') {
if (workerForProject(store, projectId)) throw workerConflict('受限子项目不能修改Skills登记,请返回父项目。');
const input = await body(request);
if (!action) return json(response, registry.register(projectId, input), 201);
if (action === 'toggle') return json(response, registry.toggle(projectId, input));
if (action === 'refresh') return json(response, registry.refresh(projectId, input), 201);
}
}
const mcpMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/mcp(?:\/(configure))?$/i);
if (mcpMatch) {
const registry = runtime.mcpRegistry(), projectId = mcpMatch[1];
if (method === 'GET' && !mcpMatch[2]) return json(response, registry.view(projectId));
if (method === 'POST') { if (workerForProject(store, projectId)) throw workerConflict('受限子项目不能修改MCP登记,请返回父项目。'); const input = await body(request);
return json(response, mcpMatch[2] ? registry.configure(projectId, input) : registry.register(projectId, input), mcpMatch[2] ? 200 : 201); }
}
const projectMemoryMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/memories$/i);
if (projectMemoryMatch && method === 'GET') {
const includeExpired = url.searchParams.get('include_expired') !== '0';
return json(response, await memories.list(projectMemoryMatch[1], { includeExpired }));
}
const sessionMemoryMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories$/i);
if (sessionMemoryMatch && method === 'GET') {
const session = store.session(sessionMemoryMatch[1]);
const includeExpired = url.searchParams.get('include_expired') !== '0';
return json(response, await memories.list(session.projectId, { includeExpired }));
}
const sessionMemoryArchiveMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)\/memories\/([a-f0-9-]+)\/archive$/i);
if (sessionMemoryArchiveMatch && method === 'POST') {
const session = store.session(sessionMemoryArchiveMatch[1]);
if (workerForProject(store, session.projectId)) throw workerConflict('受限子任务不能修改项目记忆,请返回父项目。');
await body(request);
return json(response, memories.archive(session, sessionMemoryArchiveMatch[2]));
}
if (sessionMemoryMatch && method === 'POST') {
const session = store.session(sessionMemoryMatch[1]);
if (workerForProject(store, session.projectId)) throw workerConflict('受限子任务不能修改项目记忆,请返回父项目。');
const input = await body(request);
return json(response, await memories.create(session, input), 201);
}
if (route.startsWith('/api/model-center')) {
const hub = provider.modelHub(store);
const importer = () => hub.importer ??= new ConfigImporter(hub);
if (method === 'GET' && route === '/api/model-center') return json(response, hub.view());
if (method === 'GET' && route === '/api/model-center/network-diagnostics') return json(response, hub.networkDiagnostics().view());
const networkStop = route.match(/^\/api\/model-center\/network-diagnostics\/([a-f0-9-]{36})\/stop$/i);
if (method === 'POST' && networkStop) return json(response, await hub.networkDiagnostics().stop(networkStop[1], await body(request)));
if (method === 'POST' && route === '/api/model-center/network-diagnostics') {
if (runtime.hasActivity()) throw Object.assign(new Error('请等待当前任务或诊断结束,再开始新的连接诊断。'), { status: 409 });
return json(response, hub.networkDiagnostics().start(await body(request)), 201);
}
if (method === 'GET' && route === '/api/model-center/selection') return json(response, {
config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView(),
});
if (method === 'GET' && route === '/api/model-center/credentials') return json(response, hub.vault().view(hub));
if (method === 'GET' && route === '/api/model-center/imports') return json(response, importer().discover());
if (method === 'POST') {
const input = await body(request);
if (route === '/api/model-center/toggle') return json(response, hub.toggle(input.id, input.enabled));
if (runtime.hasActivity() || hub.networkChecks?.active.size) throw Object.assign(new Error('请等待正在运行的任务或连接诊断结束,再修改或测试模型配置。'), { status: 409 });
if (route === '/api/model-center/runtime-budgets') {
store.saveConfig(validateRuntimeBudgets(input));
return json(response, { config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView() });
}
if (route === '/api/model-center/mode') {
if (!input || Object.keys(input).length !== 1 || !['demo', 'compatible'].includes(input.mode)) throw new Error('请选择离线演示或真实模型模式。');
store.saveConfig({ mode: input.mode });
return json(response, { config: { ...store.config, hasKey: provider.hasKey() }, modelSelection: hub.selectionView() });
}
if (route === '/api/model-center/wait-settings') {
store.saveConfig(validateModelWaitSettings(input, store.config));
return json(response, { center: hub.view(), config: { ...store.config, hasKey: provider.hasKey() } });
}
if (route === '/api/model-center/credentials') return json(response, hub.manageCredential(input));
if (route === '/api/model-center/native-parameters') return json(response, hub.setNativeParameters(input));
if (route === '/api/model-center/connections') return json(response, hub.upsert(input), 201);
if (route === '/api/model-center/pools') return json(response, hub.pool(input), 201);
if (route === '/api/model-center/select') return json(response, { center: hub.select(input, { mode: 'compatible' }), config: { ...store.config, hasKey: provider.hasKey() } });
if (route === '/api/model-center/import-preview') return json(response, importer().preview(input.source, String(input.path ?? '')));
if (route === '/api/model-center/import-apply') return json(response, importer().apply(input.previewId, input.autoSync, input.persistCredentials));
if (route === '/api/model-center/import-toggle') return json(response, importer().toggle(input.id, input.enabled));
if (route === '/api/model-center/import-sync') return json(response, { results: importer().sync(), center: hub.view() });
if (route === '/api/model-center/probe') {
return json(response, await hub.probe(input.id, input.scope ?? 'text'));
}
}
}
if (method === 'GET' && route === '/api/operations') {
return json(response, inspectOperations({ store, provider, runtime, server, appDirectory, version: APP_VERSION, parameters: url.searchParams }));
}
if (method === 'GET' && route === '/api/bootstrap') {
const hub = provider.modelHub(store);
return json(response, {
token, version: APP_VERSION, config: { ...store.config, hasKey: provider.hasKey() },
modelSelection: hub.selectionView(),
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
environment: executionEnvironment(),
projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null,
capabilities: { environmentPreparation:'sealed-npm-ci-in-owned-worktree',environmentDiagnostics:'node-python-runtime-and-dependency-bytes',workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', latestToolFeedback: 'sealed-original-result-fields', changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-and-python-counted-jobs', pythonChecks: 'bound-interpreter-and-structured-results', browserChecks: 'sealed-static-build-and-real-edge-assertions', projectInspection: 'bounded-source-and-git', projectMemory: 'project-scoped-source-fingerprint-and-expiry', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
});
}
if (method === 'GET' && route === '/api/diagnostics') {
const selected = url.searchParams.get('session');
const session = selected ? store.session(selected) : null;
return json(response, {
version: APP_VERSION, environment: executionEnvironment(),
connection: { mode: store.config.mode, endpoint: store.config.baseUrl, model: store.config.model, hasKey: provider.hasKey(), lastRequest: provider.lastRequest ?? null },
storage: store.storageInfo(),
projectCache: runtime.projectIndexer().status(session ? store.project(session.projectId) : undefined),
session: session ? { ...sessionSnapshot(session, store.project(session.projectId), store.config, value => provider.redact(value)), execution: store.executionSnapshot(session) } : null,
});
}
if (route === '/api/project-cache') {
if (method === 'GET') return json(response, runtime.projectIndexer().status());
if (method === 'POST') {
const input = await body(request);
if (!input || Object.keys(input).length !== 1 || typeof input.enabled !== 'boolean') throw new Error('仅接受enabled缓存开关。');
return json(response, runtime.projectIndexer().configure(input.enabled));
}
}
if (method === 'GET' && route === '/api/research/availability') return json(response, runtime.researchManager().availability());
if (method === 'GET' && route === '/api/engines/deepseek/availability') return json(response, runtime.engineManager().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
if (method === 'GET' && route === '/api/engines/deepseek/controlled-availability') return json(response, runtime.engineRunner().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
if (method === 'GET' && route === '/api/engines/purge/source') {
const root=url.searchParams.has('root')?url.searchParams.get('root'):undefined;
if(url.searchParams.get('kind')===ORIGINAL_PURGE_KIND)return json(response,resolveOriginalPurgeSource(appDirectory,root,
runtime.engineRunner().availability(url.searchParams.has('harnessRoot')?url.searchParams.get('harnessRoot'):undefined)));
if(url.searchParams.has('kind')&&url.searchParams.get('kind')!=='purge-prompt-experiment')throw Object.assign(new Error('未知 Purge 策略。'),{status:400});
return json(response,resolvePurgeSource(appDirectory,root));
}
if (method === 'GET' && route === '/api/events') {
const cursor = Math.max(cursorNumber(url.searchParams.get('after')), cursorNumber(request.headers['last-event-id']));
if (cursor > store.eventCursor) throw Object.assign(new Error('事件游标超出当前历史,请重新加载工作台。'), { status: 409 });
response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
const history = store.eventsAfter(cursor, { limit: 500 });
for (const entry of history.events) response.write('id: ' + entry.seq + '\ndata: ' + JSON.stringify({ kind: 'session_changed', ...entry }) + '\n\n');
clients.add(response); response.write('data: ' + JSON.stringify({ kind: 'ready', eventCursor: store.eventCursor, replayIncomplete: history.hasMore }) + '\n\n');
const heartbeat = setInterval(() => response.write(': heartbeat\n\n'), 20000);
request.on('close', () => { clearInterval(heartbeat); clients.delete(response); });
return;
}
if (method === 'GET' && route === '/api/events/history') {
const selected = url.searchParams.get('session'); if (selected) store.session(selected);
return json(response, store.eventsAfter(cursorNumber(url.searchParams.get('after')), { sessionId: selected,
limit: url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 100 }));
}
const artifactMatch = route.match(/^\/api\/artifacts\/([a-f0-9-]+)$/);
if (method === 'GET' && artifactMatch) {
const artifact = store.owned('artifact', artifactMatch[1], url.searchParams.get('session'));
if (url.searchParams.get('download') === '1') {
const extension = artifact.mediaType === 'application/json' ? '.json' : artifact.mediaType === 'text/markdown' ? '.md' : '.txt';
response.writeHead(200, { 'Content-Type': artifact.mediaType + '; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-' + artifact.kind + '-' + artifact.id + extension + '"' });
response.end(store.artifactStore.readBytes(artifact)); return;
}
const text = store.artifactStore.read(artifact), offset = cursorNumber(url.searchParams.get('offset'));
const limit = Math.min(64000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 16000);
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length });
}
if (method === 'POST' && route === '/api/projects') {
const input = await body(request);
if (typeof input.root !== 'string' || input.root.length > 2000) throw new Error('请输入项目文件夹的完整路径。');
return json(response, store.addProject(input.root), 201);
}
const cacheMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/index-cache$/);
if (cacheMatch && ['GET', 'DELETE'].includes(method)) {
const project = store.project(cacheMatch[1]);
await verifyWorkspaceProject(store, project);
if (method === 'DELETE') {
const input = await body(request);
if (!input || Object.keys(input).length) throw new Error('清除派生缓存不接受路径或其他字段。');
return json(response, runtime.projectIndexer().clear(project));
}
return json(response, runtime.projectIndexer().status(project));
}
if (method === 'GET' && route === '/api/local-directories') return json(response, await localDirectories(url.searchParams.get('path') || ''));
if (method === 'GET' && route === '/api/local-file-preview-access') return json(response, runtime.filePreviews?.access(url.searchParams.get('url') || '') || { allowed: false });
const filePreview = route.match(/^\/api\/projects\/([a-f0-9-]+)\/file-previews(?:\/([a-f0-9-]+))?$/);
if (filePreview) {
const project = store.project(filePreview[1]);
if (method === 'POST' && !filePreview[2]) {
const input = await body(request);
if (Object.keys(input).some(key => key !== 'path')) throw new Error('文件预览只接受项目相对路径。');
return json(response, await runtime.localFilePreviews().start(project, input.path), 201);
}
if (method === 'DELETE' && filePreview[2]) {
const input = await body(request);
if (Object.keys(input).length) throw new Error('关闭预览不接受额外字段。');
return json(response, runtime.filePreviews ? await runtime.filePreviews.close(project.id, filePreview[2]) : { closed: true });
}
}
const projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file|inspection|code-index|code-query)$/);
if (method === 'GET' && projectMatch) {
const project = store.project(projectMatch[1]);
await verifyWorkspaceProject(store, project);
if (projectMatch[2] === 'inspection') return json(response, await inspectProject(project));
if (['code-index', 'code-query'].includes(projectMatch[2])) {
const indexer = runtime.projectIndexer(), index = await indexer.refresh(project);
return json(response, projectMatch[2] === 'code-index' ? indexer.summary(index) : indexer.query(index,
{ query: url.searchParams.get('query') ?? '', kind: url.searchParams.get('kind') ?? 'all', limit: url.searchParams.has('limit') ? Number(url.searchParams.get('limit')) : 30 }));
}
return json(response, projectMatch[2] === 'files'
? listFiles(project, url.searchParams.get('path') || '', 7, 1200)
: readText(project, url.searchParams.get('path') || ''));
}
if (method === 'GET' && route === '/api/sessions') return json(response, store.listSessions());
if (method === 'POST' && route === '/api/sessions') {
const input = await body(request);
if (workerForProject(store, input.projectId)) throw workerConflict('隔离项目使用原受限子会话,请从父协作打开。');
await verifyWorkspaceProject(store, store.project(input.projectId));
return json(response, store.publicSession(store.createSession(input.projectId)), 201);
}
const sessionMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)(?:\/(.*))?$/);
if (sessionMatch) {
const id = sessionMatch[1], action = sessionMatch[2] ?? '';
const session = store.session(id);
if (action === 'input-attachments') {
if (method === 'GET') return json(response,runtime.inputAttachments().list(session));
if (workerForProject(store,session.projectId)) throw workerConflict('截图附件请在父任务中添加。');
if (method === 'POST') return json(response,runtime.inputAttachments().upload(session,await body(request,3*1024*1024)),201);
}
const inputImage = action.match(/^input-attachments\/([a-f0-9-]+)(?:\/(image|original))?$/);
if (inputImage) {
const manager=runtime.inputAttachments();
if(method==='DELETE'&&!inputImage[2]) { await body(request);return json(response,manager.remove(session,inputImage[1])); }
if(method==='GET'&&inputImage[2]) {
const {row,artifact,bytes}=manager.read(session,inputImage[1],{original:inputImage[2]==='original'});
const download=inputImage[2]==='original'||url.searchParams.get('download')==='1';
response.writeHead(200,{'Content-Type':artifact.mediaType,'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Content-SHA256':artifact.sha256,
...(download?{'Content-Disposition':'attachment; filename="workbench-input-'+row.id+(artifact.mediaType==='image/png'?'.png':'.jpg')+'"'}:{})});
response.end(bytes);return;
}
}
if (method === 'POST' && workerForProject(store, session.projectId)
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|requirements|requirement-proofs|file-results|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
if (method === 'GET' && action === 'evaluations') return json(response,runtime.evaluationManager().view(session));
if (method === 'POST' && action === 'evaluations') {
const batch=await runtime.evaluationManager().plan(session,await body(request));
return json(response,{batch,session:store.publicSession(session)},201);
}
const evaluation=action.match(/^evaluations\/([a-f0-9-]+)\/(prepare|baseline|start|seal|adopt|finalize|retain|stop|report)$/);
if (evaluation) {
const manager=runtime.evaluationManager();
if (method==='GET' && evaluation[2]==='report') {
const batch=manager.own(session,evaluation[1]);
return json(response,manager.readReport(session,batch,manager.sample(batch,url.searchParams.get('sampleId'))));
}
if (method==='POST' && evaluation[2]!=='report') {
const input=await body(request);
if (!input || typeof input!=='object' || Array.isArray(input) || !/^[a-f0-9]{64}$/.test(input.fingerprint??'') || Object.keys(input).some(key=>!['fingerprint','sampleId'].includes(key))) throw workerConflict('评测操作需要原计划指纹,只接受固定样本身份。');
const batch=manager.own(session,evaluation[1],input.fingerprint);
let result;
if(evaluation[2]==='stop'){await runtime.stop(session.id);result=batch;}
else if(evaluation[2]==='finalize')result=await manager.finalize(session,batch.id,input.fingerprint);
else if(evaluation[2]==='retain')result=manager.retain(session,batch.id,input.fingerprint);
else result=await manager[evaluation[2]](session,batch.id,input.fingerprint,input.sampleId);
return json(response,{batch:result.batch??result,session:store.publicSession(session)},result.promise?202:200);
}
}
if (method === 'GET' && action === 'collaborations') return json(response, runtime.workerManager().view(session));
if (method === 'POST' && action === 'collaborations') {
const group = await runtime.workerManager().plan(session, await body(request));
return json(response, { group, session: store.publicSession(session) }, 201);
}
const collaboration = action.match(/^collaborations\/([a-f0-9-]+)\/(prepare|start|stop|collect|merge|finalize|discard|reconcile|acknowledge|collection|evidence)$/);
if (collaboration) {
const manager = runtime.workerManager();
if (method === 'GET' && ['collection', 'evidence'].includes(collaboration[2])) {
const group = manager.own(session, collaboration[1], null, { current: false });
return json(response, collaboration[2] === 'collection' ? await manager.readCollection(session, group) : manager.readEvidence(session, group));
}
if (method === 'POST' && !['collection', 'evidence'].includes(collaboration[2])) {
const input = await body(request);
if (Object.keys(input).some(key => !['fingerprint', 'workerId', 'evidenceSha256', 'retain'].includes(key))) throw workerConflict('协作操作字段无效,不能添加命令或模型配置。');
const group = manager.own(session, collaboration[1], input.fingerprint);
if (group.evaluation && ['prepare','start','collect','merge','finalize'].includes(collaboration[2])) throw workerConflict('这个协作属于固定评测,请返回评测样本执行。');
let result;
if (collaboration[2] === 'prepare') result = manager.prepare(session, group.id, input.fingerprint);
else if (collaboration[2] === 'start') result = manager.start(session, group.id, input.fingerprint, input.workerId ?? null);
else if (collaboration[2] === 'stop') { await runtime.stop(session.id); result = group; }
else if (collaboration[2] === 'collect') result = manager.collect(session, group.id, input.fingerprint);
else if (collaboration[2] === 'merge') result = manager.prepareMerge(session, group.id, input.fingerprint);
else if (collaboration[2] === 'finalize') result = await manager.finalize(session, group.id, input.fingerprint);
else if (collaboration[2] === 'discard') result = manager.discard(session, group.id, input.fingerprint);
else if (collaboration[2] === 'reconcile') result = manager.reconcile(session, group.id, input.fingerprint);
else result = await manager.acknowledge(session, group.id, input.fingerprint, input.evidenceSha256, input.retain === true);
return json(response, { group: result.group ?? result, session: store.publicSession(session) }, result.promise ? 202 : 200);
}
}
if (method === 'GET' && !action) return json(response, store.publicSession(session));
if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session));
if (method === 'GET' && action === 'engine-runs') return json(response, [...store.core.engine_run.values()].filter(job => job.sessionId === id).slice(-30).map(publicEngineRun));
const engineRun = action.match(/^engine-runs\/([a-f0-9-]+)\/(input|report|download)$/);
if (method === 'GET' && engineRun) {
const job = store.owned('engine_run', engineRun[1], id);
const text = engineRun[2] === 'input' ? store.artifactStore.read(verifyEngineInput(store, session, job)) : originalEngineRun(store, session, job);
if (engineRun[2] !== 'download') {
const artifact = store.owned('artifact', engineRun[2] === 'input' ? job.inputArtifactId : job.reportArtifactId, id);
const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 4000);
if (!limit || offset > text.length) throw Object.assign(new Error('原引擎记录的读取位置或页长超出范围。'), { status: 400 });
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length });
}
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', ...(engineRun[2] === 'download' ? { 'Content-Disposition': 'attachment; filename="agent-workbench-engine-run-' + job.id + '.json"' } : {}) });
response.end(text); return;
}
if (method === 'GET' && action === 'mcp/jobs') return json(response, runtime.mcpRegistry().jobs(session));
if (method === 'POST' && action === 'mcp/probe') {
const started = runtime.mcpRegistry().start(session, await body(request));
return json(response, { job: started.job, session: store.publicSession(session) }, 202);
}
if (method === 'POST' && action === 'mcp/stop') { await body(request); await runtime.mcpRegistry().stop(session.id); return json(response, store.publicSession(session)); }
const mcpReport = action.match(/^mcp\/jobs\/([a-f0-9-]+)\/(report|input|evidence|acknowledge)$/i);
if (mcpReport && method === 'GET' && mcpReport[2] === 'report') return json(response, runtime.mcpRegistry().report(session, mcpReport[1]));
if (mcpReport && method === 'GET' && mcpReport[2] === 'input') return json(response, runtime.mcpRegistry().input(session, mcpReport[1]));
if (mcpReport && method === 'GET' && mcpReport[2] === 'evidence') return json(response, runtime.mcpRegistry().evidence(session, mcpReport[1]));
if (mcpReport && method === 'POST' && mcpReport[2] === 'acknowledge') {
const input = await body(request);
if (input.confirm !== true || typeof input.evidence_sha256 !== 'string' || Object.keys(input).some(key => !['confirm', 'evidence_sha256'].includes(key))) throw Object.assign(new Error('核对外部结果需要显式确认及当前记录指纹;状态仍保留unknown。'), { status: 400 });
return json(response, runtime.mcpRegistry().acknowledge(session, mcpReport[1], input.evidence_sha256));
}
if (method === 'GET' && action === 'engines') {
const manager = runtime.engineManager();
return json(response, { availability: manager.availability(), jobs: manager.jobs(session).map(publicEngineJob) });
}
if (method === 'POST' && action === 'engines/jobs') {
const started = runtime.engineManager().start(session, await body(request));
return json(response, { job: publicEngineJob(started.job), session: store.publicSession(session) }, 202);
}
if (method === 'POST' && action === 'engines/stop') { await runtime.engineManager().stop(id); return json(response, store.publicSession(session)); }
const engineJob = action.match(/^engines\/jobs\/([a-f0-9-]+)(?:\/(report|download))?$/);
if (method === 'GET' && engineJob) {
const manager = runtime.engineManager(), job = store.owned('engine_job', engineJob[1], id);
if (engineJob[2]) {
if (!job.reportArtifactId) throw Object.assign(new Error('这次引擎检查尚未封存原记录,请等待检查结束。'), { status: 409 });
const text = manager.originalReport(session, job), artifact = store.owned('artifact', job.reportArtifactId, id);
if (engineJob[2] === 'download') {
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-engine-' + job.id + '.json"' });
response.end(text); return;
}
const offset = cursorNumber(url.searchParams.get('offset'));
const limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 4000);
if (!limit || offset > text.length) throw Object.assign(new Error('原记录的读取位置或页长超出范围。'), { status: 400 });
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset,
totalCharacters: text.length, truncated: offset + limit < text.length });
}
if (job.reportArtifactId) manager.originalReport(session, job); else manager.inputFor(session, job);
return json(response, publicEngineJob(job));
}
if (method === 'GET' && action === 'research') {
const manager = runtime.researchManager(); return json(response, { availability: manager.availability(), targets: manager.targets(session), jobs: manager.jobs(session) });
}
if (method === 'GET' && action === 'task-checkpoints') return json(response, runtime.checkpointManager().list(session));
if (method === 'POST' && action === 'task-checkpoints') {
const input = await body(request);
if (Object.keys(input).some(key => !['taskId', 'runId'].includes(key)) || input.taskId !== session.taskId || input.runId !== session.runId) throw Object.assign(new Error('检查点的原任务或运行已变化,请刷新当前任务。'), { status: 409 });
const checkpoint = await runtime.checkpointManager().create(session);
return json(response, { checkpoint, session: store.publicSession(session) }, 201);
}
const checkpointMatch = action.match(/^task-checkpoints\/([a-f0-9-]+)(?:\/(resume))?$/i);
if (checkpointMatch && method === 'GET' && !checkpointMatch[2]) return json(response, await runtime.checkpointManager().inspect(session, checkpointMatch[1]));
if (checkpointMatch && method === 'POST' && checkpointMatch[2] === 'resume') {
const input = await body(request);
if (Object.keys(input).some(key => key !== 'sha256') || typeof input.sha256 !== 'string') throw Object.assign(new Error('检查点续接需要已核对的原SHA256。'), { status: 400 });
await runtime.checkpointManager().resume(session, checkpointMatch[1], input.sha256, runtime);
return json(response, store.publicSession(session), 202);
}
if (method === 'GET' && action === 'task-plan') {
const taskId = session.taskId, runId = session.runId;
if (url.searchParams.has('taskId') && url.searchParams.get('taskId') !== taskId) throw Object.assign(new Error('所选任务已变化,请刷新当前任务计划。'), { status: 409 });
const plan = await runtime.taskPlanner().inspect(session);
if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('核对期间任务已变化,请刷新当前计划。'), { status: 409 });
return json(response, plan);
}
if (method === 'GET' && action === 'requirements') {
if (url.searchParams.get('taskId') !== session.taskId) throw Object.assign(new Error('所选任务已变化,请刷新要求与证据。'), { status: 409 });
return json(response, await runtime.requirementReview().inspect(session, { candidates: true }));
}
if (method === 'POST' && ['requirements', 'requirement-proofs'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (!taskId || !runId || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('原任务或运行已变化,未修改其他任务要求。'), { status: 409 });
const manager = runtime.requirementReview();
const result = action === 'requirements' ? await manager.save(session, input) : await manager.verify(session, input);
const requirements = await manager.inspect(session, { candidates: true });
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('保存结果属于原任务,请刷新当前任务。'), { status: 409 });
return json(response, { session: store.publicSession(session), requirements, ...(action === 'requirement-proofs' ? { verification: result } : {}) });
}
if (method === 'GET' && action === 'file-results') return json(response, runtime.fileResults().inspect(session, { path: url.searchParams.get('path') }));
if (method === 'POST' && ['file-results', 'file-results/complete'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('任务或运行已切换,未修改其他任务成果。'), { status: 409 });
if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('工程仍有活动,请等待原操作结束后核对。'), { status: 409 });
await verifyWorkspaceProject(store, store.project(session.projectId));
if (taskId !== session.taskId || runId !== session.runId || runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('核对期间任务或工程活动已变化。'), { status: 409 });
if (action === 'file-results/complete') {
if (Object.keys(input).length) throw Object.assign(new Error('结束任务不接受额外完成结论。'), { status: 400 });
await runtime.completeFileResults(session);
} else runtime.fileResults().record(session, input, { source: 'user' });
return json(response, { session: store.publicSession(session), ...runtime.fileResults().inspect(session) });
}
if (method === 'POST' && ['task-plans', 'task-proofs'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (typeof taskId !== 'string' || typeof runId !== 'string' || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('提交的任务或运行已变化,未修改其他任务计划。'), { status: 409 });
const manager = runtime.taskPlanner();
const result = action === 'task-plans' ? await manager.plan(session, input) : await manager.verify(session, input);
const plan = await manager.inspect(session);
if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('保存结果属于原任务,请刷新所选任务。'), { status: 409 });
return json(response, { session: store.publicSession(session), plan, ...(action === 'task-proofs' ? { verification: result } : {}) }, action === 'task-plans' ? 201 : 200);
}
if (method === 'GET' && action === 'browser') {
const manager = runtime.browserManager(), available = manager.availability();
return json(response, { availability: { status: available.status, engine: available.engine, playwrightVersion: available.playwrightVersion, message: available.message },
builds: manager.builds(store.project(session.projectId)), plans: manager.plans(session), jobs: manager.jobs(session) });
}
if (method === 'POST' && action === 'browser-plans') {
await runtime.browserManager().plan(session, await body(request)); return json(response, store.publicSession(session), 201);
}
if (method === 'POST' && action === 'browser-jobs') {
const input = await body(request), started = runtime.browserManager().start(session, input.planId);
if (started.reused) await started.promise;
return json(response, store.publicSession(session), 202);
}
const browserJob = action.match(/^browser-jobs\/([a-f0-9-]+)(?:\/(stop|acknowledge|record))?$/);
if (browserJob && method === 'POST' && ['stop', 'acknowledge'].includes(browserJob[2])) {
const input = await body(request); store.owned('browser_job', browserJob[1], id);
if (browserJob[2] === 'stop') await runtime.browserManager().stop(id, browserJob[1]);
else runtime.browserManager().acknowledge(session, browserJob[1], input.fingerprint);
return json(response, store.publicSession(session));
}
if (browserJob && method === 'GET') {
const job = store.owned('browser_job', browserJob[1], id);
if (browserJob[2] === 'record') {
verifyBrowserJob(store, session, job); const artifact = store.owned('artifact', job.resultArtifactId, id), text = store.artifactStore.read(artifact);
const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 8000);
if (!limit || offset > text.length) throw Object.assign(new Error('浏览器原结果分页范围无效。'), { status: 400 });
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length });
}
if (!browserJob[2]) { if (job.resultArtifactId) verifyBrowserJob(store, session, job); else runtime.browserManager().planFor(session, job.planId); return json(response, job); }
}
const browserImage = action.match(/^browser-jobs\/([a-f0-9-]+)\/images\/([a-f0-9-]+)$/);
if (method === 'GET' && browserImage) {
const job = store.owned('browser_job', browserImage[1], id); verifyBrowserJob(store, session, job);
const image = job.screenshots.find(value => value.artifactId === browserImage[2]);
if (!image) throw Object.assign(new Error('图片不属于这次浏览器检查。'), { status: 404 });
const artifact = store.owned('artifact', image.artifactId, id);
response.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
...(url.searchParams.get('download') === '1' ? { 'Content-Disposition': 'attachment; filename="workbench-browser-' + job.id + '-' + image.label + '.png"' } : {}) });
response.end(store.artifactStore.readBytes(artifact)); return;
}
if (method === 'POST' && action === 'research/targets') {
const target = await runtime.researchManager().register(session, await body(request));
return json(response, { target, session: store.publicSession(session) }, 201);
}
if (method === 'POST' && action === 'research/jobs') {
const input = await body(request);
if (input.refresh !== undefined && typeof input.refresh !== 'boolean') throw Object.assign(new Error('重新分析选项需要布尔值。'), { status: 400 });
const started = runtime.researchManager().start(session, input.targetId, input.operation, { source: 'user', refresh: input.refresh === true });
return json(response, { job: started.job, session: store.publicSession(session) }, 202);
}
if (method === 'POST' && action === 'research/stop') { await runtime.researchManager().stop(id); return json(response, store.publicSession(session)); }
const researchJob = action.match(/^research\/jobs\/([a-f0-9-]+)(?:\/(evidence|raw|download))?$/);
if (method === 'GET' && researchJob) {
const manager = runtime.researchManager(), job = store.owned('research_job', researchJob[1], id);
if (!researchJob[2]) return json(response, job);
if (researchJob[2] === 'evidence') return json(response, manager.readEvidence(session, job.id, { pointer: url.searchParams.get('pointer') ?? '/normalized_result',
offset: cursorNumber(url.searchParams.get('offset')), limit: Math.min(16000, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 4000)), maximumMessageBytes: 100000 }));
if (researchJob[2] === 'raw') {
const text = manager.originalDocument(session, job, 'raw'), offset = cursorNumber(url.searchParams.get('offset')),
limit = Math.min(16000, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 4000));
return json(response, { content: text.slice(offset, offset + limit), offset, next_offset: Math.min(text.length, offset + limit),
total_characters: text.length, truncated: offset + limit < text.length, source_document_sha256: job.raw.documentSha256 });
}
const kind = url.searchParams.get('kind') ?? 'bundle', original = manager.originalDocument(session, job, kind);
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-rea-' + job.id + '.json"' });
response.end(original); return;
}
if (method === 'GET' && action === 'workspaces') return json(response, store.executionSnapshot(session).workspaces);
if (method === 'POST' && action === 'workspaces') {
const input = await body(request);
return json(response, await runtime.workspaceManager().prepare(session, input.label), 201);
}
const workspace = action.match(/^workspaces\/([a-f0-9-]+)(?:\/(create|reconcile|acknowledge|discard|open|stop))?$/);
if (workspace && method === 'GET' && !workspace[2]) return json(response, store.owned('workspace', workspace[1], id));
if (workspace && method === 'POST' && workspace[2]) {
const input = await body(request), record = store.owned('workspace', workspace[1], id);
if (workspace[2] === 'open') {
if (record.status !== 'ready') throw Object.assign(new Error('工作区尚未完整确认,请先核对创建结果。'), { status: 409 });
const project = store.project(record.childProjectId), child = store.session(record.childSessionId);
await verifyWorkspaceProject(store, project);
if (child.projectId !== project.id || child.archived) throw Object.assign(new Error('原工作区会话已归档或归属变化,请从项目栏打开该项目的当前会话。'), { status: 409 });
return json(response, { workspace: record, project, session: store.publicSession(child) });
}
const manager = runtime.workspaceManager();
if (workspace[2] === 'create') await manager.start(session, record.id, input.fingerprint);
else if (workspace[2] === 'reconcile') await manager.reconcile(session, record.id, input.fingerprint);
else if (workspace[2] === 'acknowledge') await manager.acknowledge(session, record.id, input.fingerprint, input.observationFingerprint);
else if (workspace[2] === 'discard') manager.discard(session, record.id, input.fingerprint);
else await manager.stop(id);
return json(response, record, workspace[2] === 'create' ? 202 : 200);
}
if (method === 'GET' && action === 'context-plans') {
const runId = url.searchParams.get('run'); if (runId) store.owned('run', runId, id);
return json(response, [...store.core.context_plan.values()].filter(plan => plan.sessionId === id && (!runId || plan.runId === runId)).slice(-100));
}
const contextPlan = action.match(/^context-plans\/([a-f0-9-]+)(?:\/(history))?$/);
if (method === 'GET' && contextPlan) {
const plan = store.owned('context_plan', contextPlan[1], id);
if (!contextPlan[2]) return json(response, plan);
if (!plan.historyIndexArtifactId) return json(response, { planId: plan.id, groups: [], offset: 0, totalGroups: 0, truncated: false });
const artifact = store.owned('artifact', plan.historyIndexArtifactId, id);
if (artifact.sha256 !== plan.historyIndexSha256) throw new Error('历史索引身份与请求计划不一致。');
const index = JSON.parse(store.artifactStore.read(artifact));
if (index.kind !== 'request-history-index' || index.sessionId !== id || index.projectId !== session.projectId || index.taskId !== plan.taskId) throw new Error('历史索引不属于这个任务。');
const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(50, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 12));
return json(response, { planId: plan.id, groups: index.archivedGroups.slice(offset, offset + limit), offset,
totalGroups: index.archivedGroups.length, truncated: offset + limit < index.archivedGroups.length });
}
if (method === 'POST' && action === 'change-sets') {
const input = await body(request); await runtime.changeSetManager().prepare(session, input.changeIds);
return json(response, store.publicSession(session), 201);
}
const changeSet = action.match(/^change-sets\/([a-f0-9-]+)(?:\/(apply|reconcile|rollback|discard|acknowledge|stop))?$/);
if (changeSet && method === 'GET' && !changeSet[2]) return json(response, store.owned('change_set', changeSet[1], id));
if (changeSet && method === 'POST' && changeSet[2]) {
const input = await body(request), manager = runtime.changeSetManager();
if (changeSet[2] === 'apply') await manager.start(session, changeSet[1], input.fingerprint);
else if (changeSet[2] === 'reconcile') await manager.reconcile(session, changeSet[1]);
else if (changeSet[2] === 'rollback') await manager.rollback(session, changeSet[1], input.fingerprint);
else if (changeSet[2] === 'discard') manager.discard(session, changeSet[1], input.fingerprint);
else if (changeSet[2] === 'acknowledge') manager.acknowledge(session, changeSet[1], input.fingerprint, input.observationFingerprint);
else { store.owned('change_set', changeSet[1], id); await manager.stop(id); }
return json(response, store.publicSession(session), changeSet[2] === 'apply' ? 202 : 200);
}
if (method === 'POST' && action === 'delivery-plans') {
const input = await body(request);
await runtime.gitDelivery().plan(session, input);
return json(response, store.publicSession(session), 201);
}
if (method === 'POST' && action === 'delivery-jobs') {
const input = await body(request);
await runtime.gitDelivery().start(session, input.planId);
return json(response, store.publicSession(session), 202);
}
const discardedDeliveryPlan = action.match(/^delivery-plans\/([a-f0-9-]+)\/discard$/);
if (method === 'POST' && discardedDeliveryPlan) {
await body(request); runtime.gitDelivery().discardPlan(session, discardedDeliveryPlan[1]);
return json(response, store.publicSession(session));
}
const deliveryJob = action.match(/^delivery-jobs\/([a-f0-9-]+)(?:\/(stop|reconcile))?$/);
if (deliveryJob && method === 'GET' && !deliveryJob[2]) return json(response, store.owned('delivery_job', deliveryJob[1], id));
if (deliveryJob && method === 'POST' && deliveryJob[2]) {
await body(request);
if (deliveryJob[2] === 'stop') await runtime.gitDelivery().stop(id, deliveryJob[1]);
else await runtime.gitDelivery().reconcile(session, deliveryJob[1]);
return json(response, store.publicSession(session));
}
if (method === 'POST' && action === 'delivery-reports') {
await body(request); await runtime.gitDelivery().report(session);
return json(response, store.publicSession(session), 201);
}
if (method === 'GET' && action === 'browsing') return json(response, runtime.browsingManager().snapshot(session));
const browsingImage = action.match(/^browsing\/observations\/([a-f0-9-]+)\/image$/);
if (method === 'GET' && browsingImage) {
const observation = store.owned('browsing_observation', browsingImage[1], id), artifact = store.owned('artifact', observation.screenshotArtifactId, id);
if (artifact.kind !== 'browsing-screenshot' || artifact.sha256 !== observation.screenshotSha256) throw new Error('原页面截图身份无法核对。');
const bytes = store.artifactStore.readBytes(artifact); response.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': bytes.length, 'Cache-Control': 'no-store', 'X-Content-SHA256': artifact.sha256 }); return response.end(bytes);
}
if (method === 'POST' && action === 'browsing/tabs') {
runtime.workbenchOrigin = 'http://127.0.0.1:' + actualPort; runtime.browsingManager().workbenchOrigin = runtime.workbenchOrigin;
await runtime.browsingManager().open(session, await body(request)); return json(response, store.publicSession(session), 201);
}
const browsingTab = action.match(/^browsing\/tabs\/([a-f0-9-]+)\/(observe|act|close|clear)$/);
if (method === 'POST' && browsingTab) {
const input = await body(request), manager = runtime.browsingManager(), tabId = browsingTab[1];
if (browsingTab[2] === 'observe') await manager.observe(session, tabId);
else if (browsingTab[2] === 'act') { const { approved, ...operation } = input; await manager.act(session, tabId, operation, { approved }); }
else { if (input.approved !== true) throw Object.assign(new Error('关闭/撤销需要明确确认。'), { status: 400 }); await manager.close(session, tabId, { clear: browsingTab[2] === 'clear' }); }
return json(response, store.publicSession(session));
}
const browsingAck = action.match(/^browsing\/actions\/([a-f0-9-]+)\/acknowledge$/);
if (method === 'POST' && browsingAck) {
const input = await body(request); if (input.approved !== true) throw Object.assign(new Error('请先核对原页面和回执,再明确保留未知结果。'), { status: 400 });
runtime.browsingManager().acknowledge(session, browsingAck[1]); return json(response, store.publicSession(session));
}
if (method === 'POST' && action === 'preview-plans') {
await runtime.previewManager().plan(session, await body(request)); return json(response, store.publicSession(session), 201);
}
if (method === 'POST' && action === 'preview-jobs') {
const input = await body(request);
if (!input || Array.isArray(input) || Object.keys(input).some(key => !['planId','fingerprint','approved'].includes(key))) throw Object.assign(new Error('预览启动只接受原计划身份和明确审批。'), { status: 400 });
await runtime.previewManager().start(session, input.planId, input.fingerprint, { approved: input.approved }); return json(response, store.publicSession(session), 202);
}
const previewJob = action.match(/^preview-jobs\/([a-f0-9-]+)\/(stop|reconcile)$/);
if (method === 'POST' && previewJob) {
const input = await body(request), manager = runtime.previewManager();
store.owned('preview_job', previewJob[1], id);
if (previewJob[2] === 'stop') await manager.stop(id, previewJob[1]); else await manager.reconcile(session, previewJob[1], input.fingerprint);
return json(response, store.publicSession(session));
}
if (method === 'POST' && action === 'environment-diagnostics') {
await body(request); await runtime.environmentManager().diagnose(session);
return json(response,store.publicSession(session),201);
}
if (method === 'POST' && action === 'environment-plans') {
await runtime.environmentManager().plan(session,await body(request));
return json(response,store.publicSession(session),201);
}
if (method === 'POST' && action === 'environment-jobs') {
const input=await body(request);
if(!input || Array.isArray(input) || Object.keys(input).some(key=>!['planId','fingerprint','approved'].includes(key))) throw Object.assign(new Error('依赖执行只接受原计划身份与明确审批。'),{status:400});
await runtime.environmentManager().start(session,input.planId,input.fingerprint,{approved:input.approved});
return json(response,store.publicSession(session),202);
}
const environmentJob=action.match(/^environment-jobs\/([a-f0-9-]+)\/(stop|reconcile)$/);
if(method==='POST' && environmentJob) {
const input=await body(request),manager=runtime.environmentManager();
if(environmentJob[2]==='stop')await manager.stop(session.id,environmentJob[1]);
else await manager.reconcile(session,environmentJob[1],input.fingerprint);
return json(response,store.publicSession(session));
}
if (method === 'POST' && action === 'check-plans') {
const input = await body(request);
if (runtime.isActive(id)) throw Object.assign(new Error('任务或检查正在执行,请等待结束后再准备检查。'), { status: 409 });
await runtime.checkRunner().plan(session, input.names);
return json(response, store.publicSession(session), 201);
}
if (method === 'POST' && action === 'check-jobs') {
const input = await body(request);
await runtime.checkRunner().start(session, input.planId);
return json(response, store.publicSession(session), 202);
}
const checkJob = action.match(/^check-jobs\/([a-f0-9-]+)(?:\/(stop))?$/);
if (checkJob && method === 'GET' && !checkJob[2]) return json(response, store.owned('check_job', checkJob[1], id));
if (checkJob && method === 'POST' && checkJob[2] === 'stop') {
await body(request); await runtime.checkRunner().stop(id, checkJob[1]);
return json(response, store.publicSession(session));
}
const runMatch = action.match(/^runs\/([a-f0-9-]+)$/);
if (method === 'GET' && runMatch) return json(response, store.owned('run', runMatch[1], session.id));
if (method === 'GET' && action === 'export') {
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8',
'Content-Disposition': 'attachment; filename="agent-workbench-session-' + id + '.json"' });
response.end(JSON.stringify({ schemaVersion: 1, executionSchemaVersion: 1, exportedAt: new Date().toISOString(), project: store.project(session.projectId), session, execution: store.executionSnapshot(session) }, null, 2));
return;
}
if (method === 'POST' && action === 'messages') {
const input = await body(request);
runtime.start(id, input.content,false,{attachmentIds:input.attachmentIds??[]});
return json(response, store.publicSession(session), 202);
}
if (method === 'POST' && action === 'resume') {
const input = await body(request);
runtime.resume(id, input.content);
return json(response, store.publicSession(session), 202);
}
if(method==='POST'&&action==='resume-preview')return json(response,runtime.budgetResumes().prepare(session,await body(request)),201);
if(method==='POST'&&action==='resume-budget'){runtime.resumeBudget(id,await body(request));return json(response,store.publicSession(session),202);}
if (method === 'POST' && action === 'continue-reviewed') {
await body(request); runtime.continueReviewed(id);
return json(response, store.publicSession(session), 202);
}
if (method === 'POST' && action === 'stop') {
await body(request); await runtime.stop(id);
return json(response, store.publicSession(session));
}
if (method === 'POST' && action === 'archive') {
await body(request);
if (runtime.isActive(id)) throw new Error('请先停止执行中的任务。');
session.archived = true; store.save(session);
return json(response, { archived: true });
}
const approval = action.match(/^approvals\/([a-f0-9-]+)$/);
if (method === 'POST' && approval) {
const input = await body(request);
runtime.decide(id, approval[1], input.allow === true);
return json(response, store.publicSession(session));
}
const change = action.match(/^changes\/([a-f0-9-]+)\/(apply|reject)$/);
if (method === 'POST' && change) {
await body(request);
if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('项目正在执行任务或检查,请等待结束或停止后再审查文件改动。'), { status: 409 });
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
await verifyWorkspaceProject(store, store.project(session.projectId));
if (change[2] === 'apply') applyChange(store, session, change[1]);
else {
const item = session.changes.find(candidate => candidate.id === change[1]);
if (!item || !['pending', 'conflict'].includes(item.status)) throw new Error('改动无法撤回。');
assertProposalUnsealed(store, item);
item.status = 'rejected';
if (session.status === 'needs_review' && !session.changes.some(candidate => ['pending', 'conflict'].includes(candidate.status))) session.status = 'completed';
store.save(session);
}
return json(response, store.publicSession(session));
}
if (method === 'POST' && ['proposals', 'patch-proposals'].includes(action)) {
const input = await body(request);
if (runtime.workers?.projectActive(session.projectId) || runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId) || runtime.changeSets?.projectActive(session.projectId) || runtime.workspaces?.projectActive(session.projectId)) throw Object.assign(new Error('协作、工程检查、Git交付、文件批次或工作区正在执行,请等待结束后再编辑文件。'), { status: 409 });
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
await verifyWorkspaceProject(store, store.project(session.projectId));
if (action === 'patch-proposals') proposePatch(store, session, input);
else proposeFile(store, session, input);
return json(response, store.publicSession(session), 201);
}
}
if (method === 'POST' && route === '/api/config') {
const input = await body(request);
if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务或检查,再改变模型连接。'), { status: 409 });
if (!['demo', 'compatible'].includes(input.mode)) throw new Error('请选择有效运行模式。');
const config = {
mode: input.mode, baseUrl: String(input.baseUrl || '').trim(), model: String(input.model || '').trim(),
contextLimit: Math.trunc(Math.max(1000, Math.min(200000, Number(input.contextLimit) || 16000))),
maxSteps: Math.trunc(Math.max(1, Math.min(30, Number(input.maxSteps) || 12))),
maxOutputTokens: Math.trunc(Math.max(256, Math.min(16000, Number(input.maxOutputTokens) || 2048))),
...validateModelWaitSettings(input, store.config),
maxRunDurationMs: Math.trunc(Math.max(1000, Math.min(3600000, Number(input.maxRunDurationMs) || store.config.maxRunDurationMs))),
maxRunTokens: Math.trunc(Math.max(1000, Math.min(2000000, Number(input.maxRunTokens) || store.config.maxRunTokens))),
maxTaskTokens: Math.trunc(Math.max(1000, Math.min(10000000, Number(input.maxTaskTokens) || store.config.maxTaskTokens))),
};
provider.validate(config);
if (Object.hasOwn(input, 'apiKey') && (typeof input.apiKey !== 'string' || input.apiKey.length > 16000)) throw new Error('模型凭据格式无效。');
if (provider.hub) provider.hub.select({ type: 'legacy' }, config);
else store.saveConfig(config);
if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey);
return json(response, { ...store.config, hasKey: provider.hasKey() });
}
if (method === 'POST' && route === '/api/config/models') {
const input = await body(request);
if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务或检查,再测试新的模型连接。'), { status: 409 });
const config = { ...store.config, baseUrl: String(input.baseUrl || store.config.baseUrl), mode: 'demo' };
return json(response, { models: await provider.models(config, Object.hasOwn(input, 'apiKey') ? String(input.apiKey).trim() : provider.apiKey) });
}
if (method === 'POST' && route === '/api/config/test') {
const input = await body(request);
if (runtime.hasActivity()) throw Object.assign(new Error('请先停止正在运行的任务或检查,再测试模型连接。'), { status: 409 });
const config = { ...store.config, baseUrl: String(input.baseUrl || store.config.baseUrl), model: String(input.model || store.config.model), mode: 'compatible' };
provider.validate(config);
const startedAt = Date.now();
const native = nativeParameterSettings('chat-completions', config.nativeParameters ?? {}, config.outputTokenField);
const result = await provider.request(config, '/chat/completions', { model: config.model, stream: false, [native.outputTokenField]: 64, ...native.nativeParameters,
messages: [{ role: 'user', content: 'Connection check. Reply with OK.' }] }, undefined,
Object.hasOwn(input, 'apiKey') ? String(input.apiKey).trim() : provider.apiKey);
if (!result.choices?.[0]?.message) throw new Error('模型服务响应中缺少 choices[0].message。');
return json(response, { ok: true, model: config.model, durationMs: Date.now() - startedAt, attempts: provider.lastRequest?.attempts ?? 1 });
}
if (method === 'GET' && route === '/api/research') return json(response, research.map(({ file, ...item }) => item));
const report = route.match(/^\/api\/research\/([a-z]+)$/);
if (method === 'GET' && report) {
const document = research.find(item => item.id === report[1]);
if (!document) throw new Error('研究报告不存在。');
const file = path.join(appDirectory, 'docs', document.file);
if (!fs.existsSync(file)) throw Object.assign(new Error('这份原研究报告缺失,请核对完整发行文件。'), { status: 404 });
const bytes = fs.readFileSync(file);
return json(response, { title: document.title, content: bytes.toString('utf8'), sha256: createHash('sha256').update(bytes).digest('hex') });
}
if (method === 'POST' && route === '/api/shutdown') {
await body(request);
const authority = host(), identity = authority.identity();
const result = await authority.stop({ ...identity, confirmation: 'stop-owned-host' }); json(response, result);
setTimeout(shutdown, 100); return;
}
if (route.startsWith('/api/')) return json(response, { error: '接口不存在。' }, 404);
if (method !== 'GET' && method !== 'HEAD') return json(response, { error: '请求方法不支持。' }, 405);
const staticRoot = path.join(appDirectory, 'dist-client');
const requested = decodeURIComponent(route).replace(/^\/+/, '');
let file = path.resolve(staticRoot, requested || 'index.html');
if (!file.startsWith(staticRoot + path.sep)) throw new Error('文件路径无效。');
if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) {
if (path.extname(requested)) return json(response, { error: '资源不存在。' }, 404);
file = path.join(staticRoot, 'index.html');
}
if (!fs.existsSync(file)) return json(response, { error: '请先构建工作台界面。' }, 503);
const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2' };
response.writeHead(200, { 'Content-Type': mime[path.extname(file)] || 'application/octet-stream', 'X-Content-Type-Options': 'nosniff',
'Cache-Control': file.endsWith('index.html') ? 'no-store' : 'public, max-age=3600' });
if (method === 'HEAD') response.end(); else fs.createReadStream(file).pipe(response);
} catch (error) {
if (!response.headersSent) json(response, { error: provider.redact(error.message ?? String(error)), diagnostic: error.diagnostic ?? null }, error.status ?? (error.diagnostic ? 502 : 400));
else response.destroy();
}
};
}
@@ -0,0 +1,933 @@
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 { 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;
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;
}
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);
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);
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;
}
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 (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;
try {
const args = JSON.parse(call.function.arguments);
validateToolArgs(tool, args);
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)));
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' });
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) {
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');
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,83 @@
// Task intent is retained independently of short follow-ups and system actions.
import { changeRequirement, requestedFilePaths, negatedFileAction } from './file-intent.mjs';
export const isContinuation = content => /^(?:请)?(?:继续(?:完成|执行|开发|原任务|这个任务)?|接着(?:完成|执行)?|continue(?:\s+(?:the\s+)?(?:task|work))?)[。.!!\s]*$/i.test(String(content).trim());
export function isDiagnosticQuestion(content) {
const text = String(content).trim();
if (/(?:请|帮我|继续|需要|先).{0,12}(?:修复|修改|修一下|改一下|解决|实现|开发|重跑)|(?:^|[,,;;。])\s*(?:请你?|帮我|先|继续|然后|再|并|顺便)*\s*(?:修复|修改|修一下|改一下|解决|实现|开发|执行|运行|重跑)|(?:^|\band\b)\s*(?:please )?(?:fix|implement|change|rerun)\b/i.test(text)) return false;
return /(?:怎么回事|什么原因|为什么.{0,30}(?:报错|失败|错误|异常|超时)|(?:错误|报错|失败|异常|超时).{0,20}(?:怎么|为什么|什么|原因|意思|解释|情况)|(?:解释|分析|看看).{0,12}(?:错误|报错|失败|异常)|(?:用的|使用的|调用的).{0,8}(?:哪个|什么)模型)|\b(?:what (?:went wrong|happened)|why did .{0,40}fail)\b/i.test(text);
}
export function taskContract(task, lookup = () => null) {
if (task.contract?.schemaVersion === 1) return task.contract;
let original = task;
const seen = new Set();
while (isContinuation(original.goal) && original.previousTaskId && !seen.has(original.id)) {
seen.add(original.id);
const previous = lookup(original.previousTaskId);
if (!previous || previous.sessionId !== task.sessionId || previous.projectId !== task.projectId) break;
original = previous;
}
const goal = original.contract?.goal ?? original.goal;
const skip = /无需(?:任何)?测试|不(?:需要|用|要)(?:进行|做|运行)?测试|\b(?:no tests?(?: needed|required)?|without (?:running )?tests?)\b/i.test(goal);
const required = !skip && /(?:运行|执行|通过|修复|补充|添加).{0,12}(?:测试|工程检查)|\b(?:run|pass|fix|add)\b.{0,24}\b(?:tests?|checks?)\b/i.test(goal);
const file = hasFileDeliveryRequest(goal);
return { schemaVersion: 1, goal, kind: file ? 'file' : 'general', checks: skip ? 'skip' : required ? 'required' : 'unspecified',
...(original.id !== task.id ? { inheritedFromTaskId: original.id } : {}) };
}
function hasFileDeliveryRequest(goal) {
// Do not connect a past-tense modifier ("保存的原工件") to a later
// prohibition ("不修改文件") and turn a read into a delivery requirement.
const clauses = String(goal).split(/[,,;;。\n]|而是|但是|\bbut\b/i);
const action = /(?:创建|新建|保存|写入|修改|重写|修复|调整|替换)(?!的|过的|好的|后的|下来的).{0,60}?(?:文件|HTML|[\w-]+\.(?:html?|txt|svg|md)\b)|\b(?:create|modify|rewrite|fix|change|replace)\b.{0,60}?\b(?:file|html|svg)\b/ig;
return clauses.some(clause => [...clause.matchAll(action)].some(match => {
const prefix = clause.slice(0, match.index);
return !negatedFileAction(prefix);
}));
}
export function updateTaskContract(task, instruction) {
const current = taskContract(task);
if (hasFileDeliveryRequest(instruction)) current.kind = 'file';
// Only an explicit new user instruction changes the check policy.
if (/无需(?:任何)?测试|不(?:需要|用|要)(?:进行|做|运行)?测试|\b(?:no tests?|without (?:running )?tests?)\b/i.test(instruction)) current.checks = 'skip';
else if (/(?:运行|执行|通过|修复|补充|添加).{0,12}(?:测试|工程检查)|\b(?:run|pass|fix|add)\b.{0,24}\b(?:tests?|checks?)\b/i.test(instruction)) current.checks = 'required';
task.contract = current;
task.constraints = (task.constraints ?? []).filter(value => value !== '用户明确要求无需测试;不得自动扩大为工程测试任务。');
if (current.checks === 'skip') task.constraints.push('用户明确要求无需测试;不得自动扩大为工程测试任务。');
}
export const DIAGNOSTIC_TOOLS = new Set(['diagnose_environment','inspect_session', 'inspect_project', 'list_files', 'read_file', 'search_files', 'read_artifact', 'inspect_task_plan', 'read_browser_result', 'read_registered_skill',
'inspect_engine_checks', 'list_research_targets', 'read_research_evidence']);
export const AUTOMATIC_CHECK_TOOLS = new Set(['plan_checks', 'run_checks', 'plan_browser', 'run_browser']);
DIAGNOSTIC_TOOLS.add('inspect_browser_tabs');
export function taskToolAllowed(task, run, tool, args = {}) {
if (run.purpose === 'diagnostic') return DIAGNOSTIC_TOOLS.has(tool);
if (taskContract(task).checks !== 'skip') return true;
if (AUTOMATIC_CHECK_TOOLS.has(tool)) return false;
return tool !== 'run_command' || !/(?:\b(?:test|pytest|vitest|jest|mocha|playwright)\b|--test\b)/i.test(args.command ?? '');
}
export function settleAppliedTask(store, session) {
const task = store.core.task.get(session.taskId);
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) return;
const applied = session.changes.filter(change => change.status === 'applied' && (!task || !change.taskId || change.taskId === task.id));
if (!applied.length) return;
if (!task) { if (!session.taskId) session.status = 'completed'; return; }
const contract = taskContract(task, id => store.core.task.get(id));
const demand = changeRequirement(task), recent = applied.filter(change => change.taskId === task.id && (!demand.after || change.createdAt >= demand.after && change.appliedAt >= demand.after));
const paths = new Set(applied.map(change => change.path));
const targets = requestedFilePaths([contract.goal, ...(task.instructions ?? []).filter(item => item.source !== 'review-action').map(item => item.content)].join('\n'));
if (targets.some(path => !paths.has(path)) || demand.required && (!recent.length || demand.paths.some(path => !recent.some(change => change.path === path)))) {
session.status = 'paused';
store.message(session, 'system', '文件已应用,但当前目标的文件范围或追加修改要求尚未满足,请按原目标继续核对。');
return;
}
task.delivery = { status: 'files_applied', paths: applied.map(change => change.path), at: new Date().toISOString(),
checks: contract.checks === 'skip' ? 'not_requested' : task.verification?.status ?? 'not_configured' };
session.status = contract.checks === 'required' || task.currentTaskPlanId || task.requirementRevisions?.length || ['failed', 'stale', 'unknown', 'unverified'].includes(task.verification?.status) && contract.checks !== 'skip'
? 'paused' : 'completed';
if (contract.checks === 'skip') store.message(session, 'system', '文件已审查并应用:' + task.delivery.paths.join('、') + '。按照原要求未运行测试,可在文件列表打开结果。');
}
@@ -0,0 +1,401 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import https from 'node:https';
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes, randomUUID, createCipheriv, createDecipheriv, X509Certificate } from 'node:crypto';
import { fixture, call, until, workspace } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { installUpgrade } from '../src/server/hot-upgrade.mjs';
import { createTask, createRun } from '../src/shared/contracts/execution.mjs';
import http from 'node:http';
import { CompanionGateway } from '../src/server/companion-gateway.mjs';
import { DeviceRegistry } from '../src/core/companion/device-registry.mjs';
import { CompanionTLS } from '../src/core/companion/tls-authority.mjs';
import { approvalBinding, companionHash } from '../src/shared/contracts/companion.mjs';
import { InputAttachments } from '../src/core/context/input-attachments.mjs';
import { PNG } from 'pngjs';
function setup(t) {
const value = fixture(t), host = { instanceId: randomUUID(), ownerId: randomUUID(), userSid: 'fixture-current-user', pid: process.pid, createdAt: new Date().toISOString() };
let clock = Date.now();
const registry = new DeviceRegistry(value.store, () => host, { clock: () => clock });
const grant = { projectIds: [value.project.id], permissions: { observe: true, approve: false, stop: false }, expiresInHours: 24 };
registry.initialize();
return { ...value, registry, grant, host, advance: ms => { clock += ms; } };
}
function testSealing() {
// This explicit dependency is confined to tests. Product code always uses
// Windows CurrentUser DPAPI and has no plaintext/non-Windows fallback.
const key = randomBytes(32);
return { protect: (bytes, entropy) => {
const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(entropy);
const encrypted = Buffer.concat([cipher.update(bytes), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), encrypted]);
}, unprotect: (bytes, entropy) => {
const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12)); decipher.setAuthTag(bytes.subarray(12, 28)); decipher.setAAD(entropy);
return Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]);
} };
}
async function running(t) {
const f = setup(t), runtime = { waiters: new Map(), decide() { throw new Error('No approval'); }, async stop() {} };
const appDirectory = path.join(f.root, 'app'); fs.mkdirSync(path.join(appDirectory, 'dist-client'), { recursive: true });
fs.writeFileSync(path.join(appDirectory, 'dist-client', 'mobile.html'), '<!doctype html><title>Test mobile entry</title>');
fs.writeFileSync(path.join(appDirectory, 'dist-client', 'mobile-assets.json'), '[]');
const gateway = new CompanionGateway({ store: f.store, runtime, appDirectory, identity: () => f.host, redact: value => String(value).replaceAll('fixture-secret', '[REDACTED]') },
{ tlsOptions: testSealing(), allowLoopback: true });
f.onCleanup(() => gateway.close());
assert.equal(gateway.status().enabled, false);
await gateway.start({ address: '127.0.0.1', port: 0 });
const ca = gateway.registry.read().tls.certificate;
const request = (route, data, { cookie = '', origin = gateway.origin, headers = {} } = {}) => new Promise((resolve, reject) => {
const req = https.request(gateway.origin + route, { ca, servername: '', method: data === undefined ? 'GET' : 'POST', headers: {
...(cookie ? { Cookie: cookie } : {}), ...(origin ? { Origin: origin } : {}), ...(data === undefined ? {} : { 'Content-Type': 'application/json' }), Connection: 'close', ...headers } }, res => {
const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8'); let body; try { body = JSON.parse(text); } catch { body = text; }
resolve({ status: res.statusCode, headers: res.headers, body,bytes:Buffer.concat(chunks) });
});
}); req.on('error', reject); req.end(data === undefined ? undefined : JSON.stringify(data));
});
async function pair(grant = f.grant) {
const ticket = await gateway.pairing(grant), token = new URLSearchParams(new URL(ticket.url).hash.slice(1)).get('pair');
const result = await request('/mobile-api/pair', { token, name: '测试iPhone' });
assert.equal(result.status, 201, JSON.stringify(result.body));
const cookie = result.headers['set-cookie'][0].split(';')[0]; return { ticket, token, cookie, device: result.body.device };
}
return { ...f, gateway, runtime, request, pair };
}
test('observe-only device authority cannot read, configure or clear project parsing caches', async t => {
const f = await running(t), paired = await f.pair();
assert.equal((await f.request('/mobile-api/projects', undefined, { cookie: paired.cookie })).status, 200);
for (const route of ['/api/project-cache', '/api/projects/' + f.project.id + '/index-cache', '/mobile-api/project-cache', '/mobile-api/projects/' + f.project.id + '/index-cache']) {
for (const data of [undefined, { enabled: false }]) assert.equal((await f.request(route, data, { cookie: paired.cookie })).status, 404);
}
assert.equal(fs.existsSync(path.join(f.data, 'cache', 'project-index')), false);
});
test('pairing is short lived, single-use, generation-bound and validates exact permissions', t => {
const f = setup(t), pair = f.registry.pair(f.grant, 'generation');
assert.match(pair.token, /^[A-Za-z0-9_-]{43}$/);
assert.throws(() => f.registry.consume(pair.token, 'phone', 'other'), /无效/);
const accepted = f.registry.consume(pair.token, 'phone', 'generation');
assert.equal(f.registry.authenticate(accepted.token).id, accepted.device.id);
assert.throws(() => f.registry.consume(pair.token, 'phone', 'generation'), /无效/);
const next = f.registry.pair(f.grant, 'generation'); f.advance(120001);
assert.throws(() => f.registry.consume(next.token, 'phone', 'generation'), /过期/);
assert.throws(() => f.registry.pair({ ...f.grant, permissions: { ...f.grant.permissions, execute: true } }, 'g'), /字段/);
assert.throws(() => f.registry.pair({ ...f.grant, projectIds: [randomUUID()] }, 'g'), /项目/);
});
test('device transaction failure neither consumes the ticket nor leaves a credential', t => {
const f = setup(t), pair = f.registry.pair(f.grant, 'g');
f.store.storage.faultInjector = () => { throw new Error('disk fixture'); };
assert.throws(() => f.registry.consume(pair.token, 'phone', 'g'), /disk fixture/);
assert.equal(f.registry.view().devices.length, 0);
f.store.storage.faultInjector = null;
assert.equal(f.registry.consume(pair.token, 'phone', 'g').device.name, 'phone');
});
test('devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority', t => {
const f = setup(t), pair = f.registry.pair(f.grant, 'g'), accepted = f.registry.consume(pair.token, 'phone', 'g');
const device = f.registry.authenticate(accepted.token);
assert.throws(() => f.registry.authorize(device, randomUUID()), /权限/);
assert.throws(() => f.registry.authorize(device, f.project.id, 'stop'), /权限/);
const rotated = f.registry.rotate(device);
assert.throws(() => f.registry.authenticate(accepted.token), /轮换/);
const current = f.registry.authenticate(rotated); f.registry.revoke(current.id, current.revision);
assert.throws(() => f.registry.authenticate(rotated), /撤销/);
const fresh = f.registry.consume(f.registry.pair(f.grant, 'g').token, 'other', 'g'); f.advance(25 * 3600000);
assert.throws(() => f.registry.authenticate(fresh.token), /到期/);
f.host.instanceId = randomUUID(); assert.throws(() => f.registry.authenticate(fresh.token), /宿主/);
});
test('persistent registry stores hashes and a bounded audit, never raw credentials', t => {
const f = setup(t), ticket = f.registry.pair(f.grant, 'g'), accepted = f.registry.consume(ticket.token, 'iPhone', 'g');
const text = JSON.stringify(f.store.storage.meta('mobileCompanion'));
assert.ok(!text.includes(ticket.token) && !text.includes(accepted.token));
const nextHost = { ...f.host, instanceId: randomUUID() };
const registry = new DeviceRegistry(f.store, () => nextHost);
assert.equal(registry.authenticate(accepted.token).name, 'iPhone');
assert.ok(!JSON.stringify(registry.view()).includes('credentialHash'));
});
test('real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint', async t => {
const f = await running(t), first = f.gateway.tls.publicCertificate();
assert.equal(new X509Certificate(first.bytes).ca, true);
assert.equal(companionHash(first.bytes), first.sha256);
assert.equal((await f.request('/')).status, 200);
const record = f.gateway.registry.read().tls;
assert.ok(!Buffer.from(record.ciphertext, 'base64').toString('utf8').includes('pkcs8'));
const origin = f.gateway.origin; await f.gateway.close();
await f.gateway.start({ address: '127.0.0.1', port: Number(new URL(origin).port) });
assert.equal(f.gateway.tls.publicCertificate().sha256, first.sha256);
assert.equal((await f.request('/')).status, 200);
});
test('TLS sealing failure leaves listener closed and no plaintext or successful TLS registration', async t => {
const f = setup(t), tls = new CompanionTLS(f.registry, { protect() { throw new Error('fixture encryption failure'); } });
await assert.rejects(tls.material('127.0.0.1'), /encryption/);
assert.equal(f.registry.read().tls, undefined);
});
test('HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks', async t => {
const f = await running(t), ticket = await f.gateway.pairing(f.grant), token = new URLSearchParams(new URL(ticket.url).hash.slice(1)).get('pair');
assert.match(ticket.qr, /^data:image\/png;base64,/);
const attempts = await Promise.all([f.request('/mobile-api/pair', { token, name: 'first' }), f.request('/mobile-api/pair', { token, name: 'second' })]);
assert.deepEqual(attempts.map(value => value.status).sort(), [201, 401]);
const accepted = attempts.find(value => value.status === 201);
assert.match(accepted.headers['set-cookie'][0], /; Secure; HttpOnly; SameSite=Strict/);
assert.equal((await f.request('/mobile-api/pair', { token, name: 'third' }, { origin: 'https://unrelated.invalid' })).status, 403);
assert.equal((await f.request('/', undefined, { headers: { Host: 'localhost:443' } })).status, 421);
});
test('gateway never exposes management routes, arbitrary assets or unpaired project data', async t => {
const f = await running(t);
assert.equal((await f.request('/mobile-api/projects')).status, 401);
const { cookie } = await f.pair();
for (const route of ['/api/bootstrap', '/api/config', '/index.html', '/assets/desktop.js', '/src/server/index.mjs', '/mobile-api/config', '/mobile-api/projects?expand=all']) {
const result = await f.request(route, undefined, { cookie }); assert.ok(result.status >= 400, route);
assert.ok(!JSON.stringify(result.body).includes('Workbench-Token'));
}
for (const action of ['requirements', 'requirement-proofs']) {
const route = '/mobile-api/sessions/' + f.session.id + '/' + action;
assert.equal((await f.request(route, undefined, { cookie })).status, 404);
assert.equal((await f.request(route, { expected_revision: 0, note: 'attempted remote acceptance' }, { cookie })).status, 404);
}
});
test('authorized project events paginate from original seq without leaking other project events or payloads', async t => {
const f = await running(t), otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot);
const otherProject = f.store.addProject(otherRoot), other = f.store.createSession(otherProject.id);
for (let i = 0; i < 7; i++) { f.store.save(other, { detail: { secret: 'fixture-secret' } }); f.store.save(f.session); }
const { cookie } = await f.pair(); let after = 0, events = [];
for (let i = 0; i < 20; i++) {
const page = await f.request('/mobile-api/events?after=' + after + '&limit=2', undefined, { cookie }); assert.equal(page.status, 200);
events.push(...page.body.events); after = page.body.nextCursor;
if (!page.body.hasMore) break;
}
assert.ok(events.length >= 8); assert.equal(new Set(events.map(event => event.seq)).size, events.length);
assert.ok(events.every(event => event.projectId === f.project.id && !Object.hasOwn(event, 'payload')));
assert.equal((await f.request('/mobile-api/sessions/' + other.id, undefined, { cookie })).status, 403);
const projects = await f.request('/mobile-api/projects', undefined, { cookie });
assert.equal(projects.body.length, 1); assert.equal(projects.body[0].root, undefined);
});
test('remote task projection excludes raw model history, host configuration, tool input and credentials', async t => {
const f = await running(t); f.session.providerMessages.push({ role: 'system', content: 'private-model-history' });
f.session.events.push({ id: randomUUID(), label: 'check', input: { token: 'private-input' }, output: 'fixture-secret' }); f.store.save(f.session);
const { cookie } = await f.pair(), result = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie });
assert.equal(result.status, 200); const text = JSON.stringify(result.body);
assert.ok(!text.includes('private-model-history') && !text.includes('private-input') && !text.includes('fixture-secret'));
assert.equal(result.body.events.at(-1).output, '[REDACTED]');
});
test('permission checks apply to direct remote mutation, not only UI controls', async t => {
const f = await running(t), { cookie } = await f.pair();
f.session.taskId = randomUUID(); f.session.runId = randomUUID(); f.store.save(f.session);
const result = await f.request('/mobile-api/sessions/' + f.session.id + '/stop', { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, { cookie });
assert.equal(result.status, 403);
});
test('approval fingerprint and exact task/revision are bound; duplicate requests never execute twice', async t => {
const f = await running(t), grant = { ...f.grant, permissions: { observe: true, approve: true, stop: true } }, { cookie } = await f.pair(grant);
f.session.taskId = randomUUID(); f.session.runId = randomUUID();
const approval = { id: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, projectId: f.project.id, command: 'echo owned', reason: 'fixture', status: 'pending' };
f.session.approvals.push(approval); f.runtime.waiters.set(approval.id, { sessionId: f.session.id, runId: f.session.runId }); f.store.save(f.session);
let calls = 0;
f.runtime.decide = (_session, _approval, allow) => { calls++; assert.equal(allow, true); approval.status = 'approved'; f.runtime.waiters.delete(approval.id); f.store.save(f.session); };
const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision, approvalId: approval.id, fingerprint: approvalBinding(f.session, approval), allow: true };
const route = '/mobile-api/sessions/' + f.session.id + '/approve';
assert.equal((await f.request(route, { ...value, fingerprint: '0'.repeat(64) }, { cookie })).status, 409);
const results = await Promise.all([f.request(route, value, { cookie }), f.request(route, value, { cookie })]);
assert.ok(results.every(result => result.status === 200)); assert.equal(calls, 1);
assert.equal((await f.request(route, { ...value, allow: false }, { cookie })).status, 409);
});
test('unknown original operation is recorded and never replayed after response failure', async t => {
const f = await running(t), { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: false, stop: true } });
f.session.taskId = randomUUID(); f.session.runId = randomUUID(); f.store.save(f.session);
let calls = 0; f.runtime.stop = async () => { calls++; throw new Error('fixture interrupted receipt'); };
const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, route = '/mobile-api/sessions/' + f.session.id + '/stop';
assert.equal((await f.request(route, value, { cookie })).status, 409);
const retry = await f.request(route, value, { cookie }); assert.equal(retry.body.status, 'unknown'); assert.equal(calls, 1);
const me = await f.request('/mobile-api/me', undefined, { cookie });
assert.equal(me.body.operations.at(-1).status, 'unknown'); assert.equal(me.body.operations.at(-1).requestId, value.requestId);
assert.ok(!JSON.stringify(me.body).includes('credentialHash') && !JSON.stringify(me.body).includes('"hash"'));
});
test('revocation and gateway closure reject old access without invoking runtime stop', async t => {
const f = await running(t), { cookie, device } = await f.pair(); let stopped = 0; f.runtime.stop = () => { stopped++; };
f.gateway.revoke(device.id, device.revision);
assert.equal((await f.request('/mobile-api/projects', undefined, { cookie })).status, 401);
await f.gateway.close(); assert.equal(stopped, 0); assert.equal(f.gateway.status().enabled, false);
});
test('rate limits reject pairing brute force and do not persist candidate secrets', async t => {
const f = await running(t); let last;
for (let i = 0; i < 9; i++) last = await f.request('/mobile-api/pair', { token: randomBytes(32).toString('base64url'), name: 'phone' });
assert.equal(last.status, 429); assert.equal(f.gateway.registry.view().devices.length, 0);
});
test('real Windows CurrentUser DPAPI persists only a sealed CA and reopens it', { skip: process.platform !== 'win32' }, async t => {
const f = setup(t), tls = new CompanionTLS(f.registry);
await tls.material('127.0.0.1'); const hash = tls.publicCertificate().sha256;
await new CompanionTLS(f.registry).material('127.0.0.1');
assert.equal(tls.publicCertificate().sha256, hash);
});
function realRuntime(f, command) {
const provider = new Provider(), runtime = new Runtime(f.store, provider);
provider.complete = async (_config, messages) => ({ message: messages.some(value => value.role === 'tool') ? { role: 'assistant', content: '本地夹具完成。' }
: { role: 'assistant', content: '', tool_calls: [call('owned-mobile-command', 'run_command', { command, reason: '原Runtime手机审批夹具' })] }, usage: null });
f.gateway.runtime = runtime; f.onCleanup(() => runtime.stopAll()); return runtime;
}
const fixtureCommand = source => (process.platform === 'win32' ? '& ' : '') + '"' + process.execPath + '" -e "' + source + '"';
test('mobile approval executes the original Runtime command exactly once and rejects the later desktop decision', async t => {
const f = await running(t), runtime = realRuntime(f, fixtureCommand("require('node:fs').appendFileSync('phone-approved.txt','one\\n')"));
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
runtime.start(f.session.id, '只运行这个自有夹具命令。');
await until(() => f.session.status === 'awaiting_approval');
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie }), approval = before.body.approvals[0];
const value = { requestId: randomUUID(), taskId: before.body.taskId, runId: before.body.runId, revision: before.body.revision,
approvalId: approval.id, fingerprint: approval.fingerprint, allow: true };
const route = '/mobile-api/sessions/' + f.session.id + '/approve';
const results = await Promise.all([f.request(route, value, { cookie }), f.request(route, value, { cookie })]);
assert.ok(results.every(value => value.status === 200));
assert.throws(() => runtime.decide(f.session.id, approval.id, true), /过期/);
await until(() => !runtime.active.has(f.session.id));
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'phone-approved.txt'), 'utf8'), 'one\n');
assert.equal(f.session.events.filter(value => value.tool === 'run_command').length, 1);
assert.equal((await f.request(route, value, { cookie })).body.duplicate, true);
});
test('desktop rejection wins a concurrent mobile request and original command remains unexecuted', async t => {
const f = await running(t), runtime = realRuntime(f, fixtureCommand("require('node:fs').writeFileSync('should-not-exist.txt','no')"));
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
runtime.start(f.session.id, '原桌面和手机审批竞争夹具。'); await until(() => f.session.status === 'awaiting_approval');
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie }), approval = before.body.approvals[0];
const pending = f.request('/mobile-api/sessions/' + f.session.id + '/approve', { requestId: randomUUID(), taskId: before.body.taskId,
runId: before.body.runId, revision: before.body.revision, approvalId: approval.id, fingerprint: approval.fingerprint, allow: true }, { cookie });
runtime.decide(f.session.id, approval.id, false);
assert.equal((await pending).status, 409); await until(() => !runtime.active.has(f.session.id));
assert.equal(fs.existsSync(path.join(f.projectRoot, 'should-not-exist.txt')), false);
});
test('phone stop waits for the original process exit and prevents later heartbeats and command replay', async t => {
const f = await running(t), runtime = realRuntime(f, fixtureCommand("setInterval(()=>require('node:fs').appendFileSync('heartbeat.txt','x'),80)"));
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
runtime.start(f.session.id, '手机停止自有心跳进程。'); await until(() => f.session.status === 'awaiting_approval');
runtime.decide(f.session.id, f.session.approvals.at(-1).id, true);
await until(() => fs.existsSync(path.join(f.projectRoot, 'heartbeat.txt')));
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie });
const value = { requestId: randomUUID(), taskId: before.body.taskId, runId: before.body.runId, revision: before.body.revision };
const route = '/mobile-api/sessions/' + f.session.id + '/stop', result = await f.request(route, value, { cookie });
assert.equal(result.status, 200); assert.equal(runtime.active.has(f.session.id), false);
const bytes = fs.readFileSync(path.join(f.projectRoot, 'heartbeat.txt'));
await new Promise(resolve => setTimeout(resolve, 250));
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'heartbeat.txt')), bytes);
assert.equal((await f.request(route, value, { cookie })).body.duplicate, true);
assert.equal(f.session.events.filter(value => value.tool === 'run_command').length, 1);
});
test('Run replacement during parent-stop wait is rejected rather than stopping the new Run', async t => {
const f = setup(t), runtime = new Runtime(f.store, new Provider());
f.session.taskId = randomUUID(); f.session.runId = randomUUID(); const expected = { taskId: f.session.taskId, runId: f.session.runId };
let stopped = 0;
runtime.workers = { async stopParent() { f.session.runId = randomUUID(); runtime.active.set(f.session.id, { controller: { abort() { stopped++; } }, promise: Promise.resolve() }); } };
await assert.rejects(runtime.stop(f.session.id, expected), /已变化/); assert.equal(stopped, 0);
runtime.active.clear();
});
test('diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds', async t => {
const f = await running(t), task = createTask(f.session, '原差异及工件夹具', f.store.config);
const run = createRun(f.session, task, f.store.config);
f.store.core.task.set(task.id, task); f.store.core.run.set(run.id, run); f.session.taskId = task.id; f.session.runId = run.id;
const text = '+line\\n'.repeat(17000), change = { id: randomUUID(), taskId: f.session.taskId, sha256: companionHash('new file'), baseSha256: companionHash('old'), path: 'long/path.ts', diff: [{ value: text, added: true }] };
f.session.changes.push(change); f.store.save(f.session);
const report = f.store.artifactStore.write(f.session, null, '# 原报告\nfixture-secret\n', { kind: 'delivery-report-markdown', mediaType: 'text/markdown' });
const raw = f.store.artifactStore.write(f.session, null, 'never expose tool input', { kind: 'tool-result' });
f.store.core.artifact.set(report.id, report); f.store.core.artifact.set(raw.id, raw); f.store.save(f.session);
const { cookie } = await f.pair(); let assembled = '', offset = 0, hash;
for (let page = 0; page < 20; page++) {
const value = await f.request('/mobile-api/sessions/' + f.session.id + '/changes/' + change.id + '?offset=' + offset, undefined, { cookie }); assert.equal(value.status, 200);
assert.equal(value.body.sourceSha256, change.sha256); if (hash) assert.equal(value.body.sha256, hash); hash = value.body.sha256;
assembled += value.body.text; offset = value.body.nextOffset; if (!value.body.hasMore) break;
}
assert.equal(companionHash(assembled), hash); assert.ok(assembled.length > 100000);
const route = '/mobile-api/sessions/' + f.session.id + '/reports/';
const delivered = await f.request(route + report.id, undefined, { cookie }); assert.equal(delivered.status, 200);
assert.equal(delivered.body.sourceSha256, report.sha256); assert.equal(delivered.body.sha256, companionHash(delivered.body.text)); assert.equal(delivered.body.redacted, true);
assert.equal((await f.request(route + raw.id, undefined, { cookie })).status, 404);
fs.appendFileSync(path.join(f.store.artifactStore.root, report.relative), 'corrupt');
assert.equal((await f.request(route + report.id, undefined, { cookie })).status, 500);
});
test('hot upgrade refuses an active gateway and restores closed gateway ownership on failure', async t => {
const f = setup(t), provider = new Provider(), runtime = new Runtime(f.store, provider), server = http.createServer((_request, response) => response.end('old'));
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
f.onCleanup(() => new Promise(resolve => server.close(resolve)));
const context = { server, store: f.store, provider, runtime, token: 'test-upgrade-owned', clients: new Set(), started: Date.now() };
const gateway = { server: { listening: true }, busy: false }; server.workbenchCompanion = gateway;
assert.throws(() => installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }), /Close the mobile/);
gateway.server = null;
f.store.claimRuntime = () => { throw new Error('fixture upgrade failure'); };
assert.throws(() => installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }), /fixture upgrade failure/);
assert.equal(server.workbenchCompanion, gateway);
});
test('damaged device permissions or expiry fail closed and never overwrite the original registry', t => {
const f = setup(t), accepted = f.registry.consume(f.registry.pair(f.grant, 'g').token, 'phone', 'g');
const original = f.store.storage.meta('mobileCompanion');
for (const damage of [value => { value.devices[accepted.device.id].permissions.stop = 'true'; }, value => { value.devices[accepted.device.id].expiresAt = 'invalid'; }]) {
const changed = structuredClone(original); damage(changed); f.store.storage.setMeta('mobileCompanion', changed);
assert.throws(() => f.registry.authenticate(accepted.token), /原手机登记无法核对/);
assert.throws(() => f.registry.initialize(), /原手机登记无法核对/);
assert.deepEqual(f.store.storage.meta('mobileCompanion'), changed);
}
});
test('device revocation destroys its actual authenticated TLS connection', async t => {
const f = await running(t), { cookie, device } = await f.pair();
const agent = new https.Agent({ keepAlive: true, ca: f.gateway.registry.read().tls.certificate });
let socket;
await new Promise((resolve, reject) => {
const request = https.get(f.gateway.origin + '/mobile-api/me', { agent, servername: '', headers: { Cookie: cookie } }, response => {
socket = response.socket; response.resume(); response.on('end', resolve);
}); request.on('error', reject);
});
assert.ok(socket && !socket.destroyed); f.gateway.revoke(device.id, device.revision);
await until(() => socket.destroyed); agent.destroy();
});
test('companion observes only current Task screenshots, verifies original PNG bytes and loses access immediately on revoke',async t=>{
const f=await running(t),manager=new InputAttachments(f.store),png=new PNG({width:20,height:10});png.data.fill(255);
const row=manager.upload(f.session,{name:'工程截图.png',mediaType:'image/png',base64:PNG.sync.write(png).toString('base64')});
const run=f.store.beginRun(f.session,'Inspect',false,f.store.config,{inputAttachments:manager.validateSelection(f.session,[row.id])});
f.session.status='paused';f.store.finishRun(f.session,run,'context_limit');const id=f.store.core.task.get(run.taskId).attachmentIds[0];
const {cookie,device}=await f.pair(),route='/mobile-api/sessions/'+f.session.id+'/input-attachments/'+id;
const image=await f.request(route+'/image',undefined,{cookie});assert.equal(image.status,200);assert.equal(companionHash(image.bytes),row.sentSha256);
const original=await f.request(route+'/original',undefined,{cookie});assert.equal(original.status,200);assert.equal(companionHash(original.bytes),row.sha256);
const projection=await f.request('/mobile-api/sessions/'+f.session.id,undefined,{cookie});assert.equal(projection.body.inputAttachments[0].id,id);
assert.equal(projection.body.inputAttachments[0].originalArtifactId,undefined);assert.equal(projection.body.providerMessages,undefined);
const draft=manager.upload(f.session,{name:'draft.png',mediaType:'image/png',base64:PNG.sync.write(png).toString('base64')});
assert.equal((await f.request('/mobile-api/sessions/'+f.session.id+'/input-attachments/'+draft.id+'/image',undefined,{cookie})).status,404);
const other=f.store.createSession(f.project.id);assert.notEqual((await f.request('/mobile-api/sessions/'+other.id+'/input-attachments/'+id+'/image',undefined,{cookie})).status,200);
assert.equal((await f.request(route+'/image',{}, {cookie})).status,404);
f.registry.revoke(device.id,device.revision);assert.equal((await f.request(route+'/image',undefined,{cookie})).status,401);
});
test('mobile browser observation is current Task/project scoped, preserves original PNG and exposes no browser control or profile data',async t=>{
const f=await running(t),run=f.store.beginRun(f.session,'核对网页原观察',false,f.store.config);f.session.status='paused';f.store.finishRun(f.session,run);
const png=PNG.sync.write(new PNG({width:4,height:4})),artifact=f.store.artifactStore.write(f.session,run,png,{kind:'browsing-screenshot',mediaType:'image/png'});f.store.core.artifact.set(artifact.id,artifact);
const row={id:randomUUID(),sessionId:f.session.id,projectId:f.project.id,taskId:f.session.taskId,runId:f.session.runId,tabId:randomUUID(),url:'https://example.com/',title:'所属原页面',createdAt:new Date().toISOString(),revision:'original:1',screenshotArtifactId:artifact.id,screenshotSha256:artifact.sha256,scope:{complete:true}};
f.store.putRecord('browsing_observation',f.session,row,'browsing.fixture');const{cookie,device}=await f.pair(),route='/mobile-api/sessions/'+f.session.id+'/browser-observations/'+row.id+'/image';
const image=await f.request(route,undefined,{cookie});assert.equal(image.status,200);assert.deepEqual(image.bytes,png);assert.equal(image.headers['x-content-sha256'],artifact.sha256);
const projected=(await f.request('/mobile-api/sessions/'+f.session.id,undefined,{cookie})).body;assert.equal(projected.browserObservations[0].id,row.id);assert.equal(projected.browserObservations[0].screenshotArtifactId,undefined);assert.equal(projected.browsingProfiles,undefined);
assert.equal((await f.request(route,{}, {cookie})).status,404);assert.equal((await f.request('/mobile-api/sessions/'+f.session.id+'/browsing/tabs',{}, {cookie})).status,404);
const other=f.store.createSession(f.project.id);assert.notEqual((await f.request('/mobile-api/sessions/'+other.id+'/browser-observations/'+row.id+'/image',undefined,{cookie})).status,200);
f.registry.revoke(device.id,device.revision);assert.equal((await f.request(route,undefined,{cookie})).status,401);
});
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { fixture, launchWorkbench } from './helpers.mjs';
import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
test('requirements HTTP binds selection, enforces optimistic revisions, restores original proofs and leaves provider history untouched', async t => {
const f = fixture(t); beginPlanTask(f, '研究当前README.md,不修改。'); const read = completeRead(f), taskId = f.session.taskId, runId = f.session.runId;
const original = structuredClone(f.session.providerMessages); f.store.close();
let host = await launchWorkbench(t, f.data); const route = '/sessions/' + f.session.id;
const input = { taskId, runId, expected_revision: 0, requirements: [{ key: 'research', title: '研究原文件', criterion: '依据真实读取', kind: 'analysis', tools: ['read_file'], method: 'evidence',
source: { kind: 'goal', id: taskId, start: 0, end: 7 } }] };
await assert.rejects(host.api(route + '/requirements?taskId=wrong'), /所选任务/);
await assert.rejects(host.api(route + '/requirements', { ...input, runId: taskId }), /原任务或运行/);
const saved = await host.api(route + '/requirements', input); assert.equal(saved.requirements.items[0].status, 'pending');
await assert.rejects(host.api(route + '/requirements', input), /修订/);
const result = await host.api(route + '/requirement-proofs', { taskId, runId, expected_revision: 1, key: 'research', evidence_id: read.id });
assert.equal(result.requirements.all_resolved, true);
const before = await host.api(route + '/export'); await host.close(); host = await launchWorkbench(t, f.data);
const restored = await host.api(route + '/requirements?taskId=' + taskId); assert.equal(restored.all_resolved, true); assert.equal(restored.history.length, 1);
const after = await host.api(route + '/export'); assert.deepEqual(after.session.providerMessages, original); assert.deepEqual(before.session.providerMessages, original);
});
@@ -0,0 +1,172 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { fixture, compatibleFixture, call, completion, assertToolPairs } from './helpers.mjs';
import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
import { RequirementReview } from '../src/core/tasks/requirement-review.mjs';
import { TaskPlanManager } from '../src/core/tasks/task-plan-manager.mjs';
import { FileResults } from '../src/core/tasks/file-results.mjs';
import { DeliveryReporter, renderDeliveryMarkdown } from '../src/core/delivery-report.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { readText, proposeFile, applyChange } from '../src/server/files.mjs';
import { createDeliveryProject, applyDeliveryFix, deliveryGit } from './fixtures/delivery-project.mjs';
import { CheckRunner } from '../src/core/check-runner.mjs';
import { GitDelivery } from '../src/core/git-delivery.mjs';
const item = (f, fields = {}) => ({ key: 'review', title: '解释原工程', criterion: '有原读取与结论可供核对', kind: 'analysis', tools: ['read_file'], method: 'evidence',
source: { kind: 'goal', id: f.session.taskId, start: 0, end: f.store.core.task.get(f.session.taskId).goal.length }, ...fields });
const create = async (f, rows = [item(f)]) => { const manager = new RequirementReview(f.store); await manager.save(f.session, { expected_revision: 0, requirements: rows }); return manager; };
const verify = (f, manager, id, key = 'review', revision = 1) => manager.verify(f.session, { expected_revision: revision, key, evidence_id: id });
test('research evidence binds actual original bytes; model completion is not user acceptance', async t => {
const f = fixture(t); beginPlanTask(f, '只研究README.md,不修改参考文件。'); const read = completeRead(f);
const manager = await create(f); assert.equal((await manager.inspect(f.session)).items[0].status, 'pending');
assert.equal((await verify(f, manager, read.id)).status, 'completed');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.all_resolved, true);
assert.equal(f.session.changes.length, 0); assert.equal(f.store.core.check_job.size, 0);
assert.equal(view.items[0].source.quote, '只研究README.md,不修改参考文件。');
const report = await new DeliveryReporter(f.store).create(f.session);
assert.equal(report.report.requirements.items[0].status, 'evidence_verified');
assert.match(renderDeliveryMarkdown(report.report), /原目标|goal:/); assert.match(report.report.task.note, /不代替/);
});
test('same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision', async t => {
const f = fixture(t); beginPlanTask(f, '读取当前依据'); const read = completeRead(f), task = f.store.core.task.get(f.session.taskId);
task.instructions.push({ id: randomUUID(), source: 'user', content: '读取当前依据', createdAt: new Date().toISOString() });
const first = item(f), second = item(f, { key: 'second', source: { kind: 'instruction', id: task.instructions[0].id, start: 0, end: 6 } });
const manager = await create(f, [first, second]); await verify(f, manager, read.id); await verify(f, manager, read.id, 'second');
let view = await manager.inspect(f.session); assert.notEqual(view.items[0].source.sourceSha256, view.items[1].source.sourceSha256);
task.instructions.push({ id: randomUUID(), source: 'user', content: '新增要求', createdAt: new Date().toISOString() });
view = await manager.inspect(f.session); assert.equal(view.all_resolved, false); assert.equal(view.unreviewed_sources.length, 1);
assert.equal(view.items[0].status, 'evidence_verified');
await manager.save(f.session, { expected_revision: 1, requirements: [first, { ...second, criterion: '新增明确条件' }] });
view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.items[0].revision, 1);
assert.equal(view.items[1].status, 'pending'); assert.equal(view.items[1].revision, 2); assert.equal(task.requirementProofs.length, 2);
});
test('foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs', async t => {
const f = fixture(t); beginPlanTask(f); const old = completeRead(f);
f.store.core.task.get(f.session.taskId).status = 'completed';
beginPlanTask(f, '另一个任务的原目标'); const manager = await create(f);
assert.equal((await verify(f, manager, old.id)).status, 'error');
assert.equal((await verify(f, manager, 'a nonempty fabricated evidence')).status, 'error');
const foreign = fixture(t); beginPlanTask(foreign); const foreignRead = completeRead(foreign);
assert.equal((await verify(f, manager, foreignRead.id)).status, 'error');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'failed'); assert.equal(view.history.length, 3);
assert.ok(view.history.every(row => row.status === 'rejected'));
});
test('source changes invalidate prior proofs and cannot certify a read that was already stale at binding', async t => {
const f = fixture(t); beginPlanTask(f); const read = completeRead(f), manager = await create(f);
await verify(f, manager, read.id);
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nnew user content\n');
assert.equal((await manager.inspect(f.session)).items[0].status, 'stale');
assert.equal((await verify(f, manager, read.id)).status, 'error');
const current = completeRead(f); assert.equal((await verify(f, manager, current.id)).status, 'completed');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.history.length, 3);
});
test('missing or tampered artifacts never become evidence and original failures remain after recovery', async t => {
const f = fixture(t); beginPlanTask(f); const read = completeRead(f), manager = await create(f);
await verify(f, manager, read.id); const artifact = f.store.owned('artifact', read.resultArtifactId, f.session.id), original = artifact.sha256;
artifact.sha256 = '0'.repeat(64);
assert.equal((await manager.inspect(f.session)).items[0].status, 'unverified');
assert.equal((await verify(f, manager, read.id)).status, 'error');
artifact.sha256 = original;
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.history[1].status, 'rejected');
const proof = f.store.core.task.get(f.session.taskId).requirementProofs[0]; proof.requirementRevision++;
assert.equal((await manager.inspect(f.session)).items[0].status, 'unverified');
});
test('checks omitted by explicit agreement are reported as not executed and never passed', async t => {
const f = fixture(t); beginPlanTask(f, '只研究现有文件,无需测试。');
const manager = await create(f, [item(f, { kind: 'checks', tools: undefined, checks: ['test'], method: 'not_requested' })]);
let view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'not_requested'); assert.equal(view.items[0].proof_id, null);
assert.equal(f.store.core.check_job.size, 0);
f.store.core.task.get(f.session.taskId).contract.checks = 'required';
view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'stale'); assert.equal(view.all_resolved, false);
});
test('user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted', async t => {
const f = fixture(t); beginPlanTask(f); const manager = await create(f, [item(f, { method: 'user' })]);
await assert.rejects(verify(f, manager, randomUUID()), /不能混用/);
await manager.verify(f.session, { expected_revision: 1, key: 'review', note: '实际打开页面,确认中文说明与当前要求一致。' });
let view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'user_confirmed'); assert.equal(view.items[0].evidence, null);
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), 'new input');
view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'stale');
});
test('existing multi-file results keep provenance and invalidate only evidence whose files changed', async t => {
const f = fixture(t); beginPlanTask(f, '核对README.md已有成果,不修改,无需测试。');
fs.writeFileSync(path.join(f.projectRoot, 'notes.md'), 'existing notes');
const results = new FileResults(f.store);
const a = results.record(f.session, { files: [{ path: 'README.md', sha256: readText(f.project, 'README.md').sha256 }], reason: '核对现有说明' }, { source: 'user' });
const b = results.record(f.session, { files: [{ path: 'notes.md', sha256: readText(f.project, 'notes.md').sha256 }], reason: '核对现有笔记' }, { source: 'user' });
const manager = await create(f, [item(f, { kind: 'results', tools: undefined, paths: ['README.md'] }), item(f, { key: 'notes', kind: 'results', tools: undefined, paths: ['notes.md'] })]);
assert.equal((await verify(f, manager, a.result_id)).status, 'completed'); assert.equal((await verify(f, manager, b.result_id, 'notes')).status, 'completed');
fs.appendFileSync(path.join(f.projectRoot, 'notes.md'), ' changed');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.items[1].status, 'stale');
assert.equal(f.session.changes.length, 0);
});
test('unrelated additions preserve the checked file facts but remain visible as unreviewed user sources', async t => {
const f = fixture(t); beginPlanTask(f, '解释README.md'); const read = completeRead(f);
const manager = await create(f); await verify(f, manager, read.id);
fs.writeFileSync(path.join(f.projectRoot, 'unrelated.txt'), 'new unrelated input');
f.store.core.task.get(f.session.taskId).instructions.push({ id: randomUUID(), source: 'user', content: '还要研究另一文件。', createdAt: new Date().toISOString() });
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.all_resolved, false);
assert.equal(view.unreviewed_sources.length, 1);
});
test('actual Git preview and publication recheck changed requirement bindings without touching HEAD or the owner index', async t => {
const f = fixture(t); createDeliveryProject(f); applyDeliveryFix(f); f.session.status = 'paused';
const runner = new CheckRunner(f.store), delivery = new GitDelivery(f.store); f.onCleanup(() => runner.stopAll()); f.onCleanup(() => delivery.stopAll());
const checkPlan = await runner.plan(f.session), check = await (await runner.start(f.session, checkPlan.id)).promise; assert.equal(check.status, 'passed');
const requirement = item(f, { kind: 'checks', tools: undefined, checks: ['test', 'build'] }), manager = await create(f, [requirement]);
await assert.rejects(delivery.plan(f.session), /用户要求/);
await verify(f, manager, check.id); const preview = await delivery.plan(f.session); assert.match(preview.requirementBindingSha256, /^[a-f0-9]{64}$/);
const head = deliveryGit(f, ['rev-parse', 'HEAD']), indexFile = path.join(deliveryGit(f, ['rev-parse', '--absolute-git-dir']).trim(), 'index'), index = fs.readFileSync(indexFile);
await manager.save(f.session, { expected_revision: 1, requirements: [{ ...requirement, criterion: '新条件必须重新核对当前检查' }] });
const result = await (await delivery.start(f.session, preview.id)).promise;
assert.equal(result.status, 'stale'); assert.equal(deliveryGit(f, ['rev-parse', 'HEAD']), head); assert.deepEqual(fs.readFileSync(indexFile), index);
});
test('no-test file application and manual completion keep pending user requirements for explicit review', async t => {
const f = fixture(t); beginPlanTask(f, '修改README.md,无需测试。'); const read = completeRead(f), manager = await create(f);
const change = proposeFile(f.store, f.session, { path: 'README.md', content: '# new reviewed file\n', reason: '明确修改' });
applyChange(f.store, f.session, change.change_id); assert.equal(f.session.status, 'paused');
const runtime = new Runtime(f.store, new Provider());
await assert.rejects(runtime.completeFileResults(f.session), /用户要求/);
const currentRead = completeRead(f); assert.equal((await verify(f, manager, currentRead.id)).status, 'completed');
await runtime.completeFileResults(f.session); assert.equal(f.session.status, 'completed'); assert.equal(f.store.core.check_job.size, 0);
assert.notEqual(read.id, currentRead.id);
});
test('revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements', async t => {
const f = fixture(t); beginPlanTask(f); const manager = await create(f);
await assert.rejects(manager.save(f.session, { expected_revision: 1, requirements: [item(f, { source: { kind: 'goal', id: randomUUID(), start: 0, end: 1 } })] }), /来源/);
await assert.rejects(manager.save(f.session, { expected_revision: 1, requirements: [item(f, { status: 'verified' })] }), /未声明/);
await assert.rejects(manager.save(f.session, { expected_revision: 1, requirements: [item(f, { key: 'different' })] }), /不能删除/);
const race = await Promise.allSettled(['first', 'second'].map(criterion => manager.save(f.session, { expected_revision: 1, requirements: [item(f, { criterion })] })));
assert.equal(race.filter(row => row.status === 'fulfilled').length, 1);
assert.equal(f.store.core.task.get(f.session.taskId).requirementRevisions.length, 2);
});
test('requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit', async t => {
const f = fixture(t); beginPlanTask(f); const read = completeRead(f), manager = new RequirementReview(f.store);
assert.equal((await manager.assertReady(f.session)).configured, false);
await manager.save(f.session, { expected_revision: 0, requirements: [item(f)] });
await assert.rejects(manager.assertReady(f.session), /待复核/);
await verify(f, manager, read.id); const accepted = await manager.assertReady(f.session);
await manager.save(f.session, { expected_revision: 1, requirements: [item(f, { criterion: '新的业务要求' })] });
await assert.rejects(manager.assertReady(f.session, { expectedBinding: accepted.binding_sha256 }), /待复核|变化/);
const model = await compatibleFixture(t, () => ({ body: completion([], '所有要求均已完成。') }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-claim', baseUrl: model.baseUrl });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, '', true); await runtime.active.get(f.session.id).promise;
assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'requirements_incomplete'); assert.equal(f.session.status, 'paused');
assertToolPairs(f.session.providerMessages);
});
@@ -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...
✓ 1763 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-rfQBbeS_.css 174.80 kB │ gzip: 33.08 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-BOoKw0-X.js 425.42 kB │ gzip: 120.30 kB
✓ built in 3.43s
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...
✓ 1763 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-rfQBbeS_.css 174.80 kB │ gzip: 33.08 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-B7ntJVIS.js 425.39 kB │ gzip: 120.27 kB
✓ built in 1.21s
Mobile shell built: 3 allowed assets; API and project data are never cached.
Server bundle built.
@@ -0,0 +1,16 @@
{
"success": true,
"passed": [
"sandboxed actual Electron saves a sourced requirement",
"actual Electron verifies the original tool result",
"renderer reload restores the same Task and requirement proof"
],
"errors": [],
"screenshots": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\electron-4a37e4be-2efc-456d-9e5a-ca680ed17ac1\\verified.png"
],
"actualElectron": true,
"installationValidated": false,
"realModelRequests": 0,
"officialServiceTouched": false
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

@@ -0,0 +1,11 @@
{
"success": false,
"passed": [
"sandboxed actual Electron saves a sourced requirement",
"actual Electron verifies the original tool result"
],
"errors": [],
"screenshots": [],
"error": "page.screenshot: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - taking page screenshot\u001b[22m\n\u001b[2m - waiting for fonts to load...\u001b[22m\n\u001b[2m - fonts loaded\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-requirements-desktop.mjs:43:104",
"realModelRequests": 0
}
@@ -0,0 +1,4 @@
PASS sandboxed actual Electron saves a sourced requirement
PASS actual Electron verifies the original tool result
PASS renderer reload restores the same Task and requirement proof
{"root":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\electron-4a37e4be-2efc-456d-9e5a-ca680ed17ac1","success":true,"passed":["sandboxed actual Electron saves a sourced requirement","actual Electron verifies the original tool result","renderer reload restores the same Task and requirement proof"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\electron-4a37e4be-2efc-456d-9e5a-ca680ed17ac1\\verified.png"],"actualElectron":true,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
@@ -0,0 +1,3 @@
PASS sandboxed actual Electron saves a sourced requirement
PASS actual Electron verifies the original tool result
{"root":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\electron-7e0fe298-edd7-48f1-a2ec-40e15294f74b","success":false,"passed":["sandboxed actual Electron saves a sourced requirement","actual Electron verifies the original tool result"],"errors":[],"screenshots":[],"error":"page.screenshot: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - taking page screenshot\u001b[22m\n\u001b[2m - waiting for fonts to load...\u001b[22m\n\u001b[2m - fonts loaded\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-requirements-desktop.mjs:43:104","realModelRequests":0}
@@ -0,0 +1,4 @@
PASS sandboxed actual Electron saves a sourced requirement
PASS actual Electron verifies the original tool result
PASS renderer reload restores the same Task and requirement proof
{"root":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\electron-8a5229d8-9a77-4fc4-9b37-761e862695a5","success":true,"passed":["sandboxed actual Electron saves a sourced requirement","actual Electron verifies the original tool result","renderer reload restores the same Task and requirement proof"],"errors":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\electron-8a5229d8-9a77-4fc4-9b37-761e862695a5\\verified.png"],"actualElectron":true,"installationValidated":false,"realModelRequests":0,"officialServiceTouched":false}
@@ -0,0 +1,9 @@
✔ gateway never exposes management routes, arbitrary assets or unpaired project data (644.9017ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 953.5308
@@ -0,0 +1,61 @@
✔ observe-only device authority cannot read, configure or clear project parsing caches (1305.3369ms)
✔ pairing is short lived, single-use, generation-bound and validates exact permissions (640.1312ms)
✔ device transaction failure neither consumes the ticket nor leaves a credential (648.9181ms)
✔ devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority (672.2474ms)
✔ persistent registry stores hashes and a bounded audit, never raw credentials (1114.0935ms)
✔ real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint (866.472ms)
✔ TLS sealing failure leaves listener closed and no plaintext or successful TLS registration (1095.5589ms)
✔ HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks (953.9794ms)
✔ gateway never exposes management routes, arbitrary assets or unpaired project data (1092.5627ms)
✔ authorized project events paginate from original seq without leaking other project events or payloads (1237.462ms)
✔ remote task projection excludes raw model history, host configuration, tool input and credentials (906.6617ms)
✔ permission checks apply to direct remote mutation, not only UI controls (1757.3716ms)
✔ approval fingerprint and exact task/revision are bound; duplicate requests never execute twice (1085.0581ms)
✔ unknown original operation is recorded and never replayed after response failure (1016.793ms)
✔ revocation and gateway closure reject old access without invoking runtime stop (924.0904ms)
✔ rate limits reject pairing brute force and do not persist candidate secrets (788.4436ms)
✔ real Windows CurrentUser DPAPI persists only a sealed CA and reopens it (3429.0587ms)
✔ mobile approval executes the original Runtime command exactly once and rejects the later desktop decision (2305.1771ms)
✔ desktop rejection wins a concurrent mobile request and original command remains unexecuted (1675.3206ms)
✔ phone stop waits for the original process exit and prevents later heartbeats and command replay (2371.3219ms)
✔ Run replacement during parent-stop wait is rejected rather than stopping the new Run (670.9993ms)
✔ diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds (1060.1826ms)
✔ hot upgrade refuses an active gateway and restores closed gateway ownership on failure (721.4847ms)
✔ damaged device permissions or expiry fail closed and never overwrite the original registry (641.3472ms)
✔ device revocation destroys its actual authenticated TLS connection (970.6986ms)
✔ companion observes only current Task screenshots, verifies original PNG bytes and loses access immediately on revoke (1253.4173ms)
✔ mobile browser observation is current Task/project scoped, preserves original PNG and exposes no browser control or profile data (1072.6188ms)
✔ file targets exclude referenced inputs and prohibited subsequent modifications (1.5018ms)
✔ full actual read and existing receipt complete a no-test file task without fabricating changes, checks or commits (3473.4169ms)
✔ partial pages, partial lines, wrong hashes and failed reads cannot be adopted; contiguous full paging can (1997.4302ms)
✔ user edits and new requirements invalidate receipts, and a second task must explicitly adopt a source in its own project/session (1903.6369ms)
✔ adopting an unchanged file never satisfies an explicit modification or a new modification instruction (1562.9755ms)
✔ required checks and stale passing flags cannot be bypassed by current file receipts (938.0642ms)
✔ results plan proofs bind current file receipts while changes proofs still demand real applied change sets (1322.3399ms)
✔ duplicate receipts cannot create progress indefinitely or reset no-progress reads (4986.481ms)
✔ manual completion preserves the failed original run and refuses unknown operations (992.827ms)
✔ completion refuses active work, files changed during inspection and a newly selected task (808.9908ms)
✔ unrelated files cannot stand in for named output paths, nor can a late apply satisfy newer instructions with an old proposal (814.2171ms)
✔ delivery and mobile projections distinguish adopted bytes, new changes, no tests and no commit; mutations cannot rewrite receipts (1216.4968ms)
✔ requirements HTTP binds selection, enforces optimistic revisions, restores original proofs and leaves provider history untouched (5127.7483ms)
✔ research evidence binds actual original bytes; model completion is not user acceptance (1891.4099ms)
✔ same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision (1803.559ms)
✔ foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs (2790.8179ms)
✔ source changes invalidate prior proofs and cannot certify a read that was already stale at binding (1544.3777ms)
✔ missing or tampered artifacts never become evidence and original failures remain after recovery (1416.2902ms)
✔ checks omitted by explicit agreement are reported as not executed and never passed (602.3554ms)
✔ user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted (885.5988ms)
✔ existing multi-file results keep provenance and invalidate only evidence whose files changed (975.5431ms)
✔ unrelated additions preserve the checked file facts but remain visible as unreviewed user sources (978.5145ms)
✔ actual Git preview and publication recheck changed requirement bindings without touching HEAD or the owner index (5824.9473ms)
✔ no-test file application and manual completion keep pending user requirements for explicit review (1223.8036ms)
✔ revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements (621.3423ms)
✔ requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit (1779.9538ms)
ℹ tests 53
ℹ suites 0
ℹ pass 53
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 47974.2398
@@ -0,0 +1,19 @@
✔ requirements HTTP binds selection, enforces optimistic revisions, restores original proofs and leaves provider history untouched (5432.6239ms)
✔ research evidence binds actual original bytes; model completion is not user acceptance (1684.3552ms)
✔ same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision (1051.0276ms)
✔ foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs (1831.3458ms)
✔ source changes invalidate prior proofs and cannot certify a read that was already stale at binding (1610.4607ms)
✔ missing or tampered artifacts never become evidence and original failures remain after recovery (1206.5883ms)
✔ checks omitted by explicit agreement are reported as not executed and never passed (586.2787ms)
✔ user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted (922.7867ms)
✔ existing multi-file results keep provenance and invalidate only evidence whose files changed (970.6869ms)
✔ revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements (621.8505ms)
✔ requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit (1740.8363ms)
ℹ tests 11
ℹ suites 0
ℹ pass 11
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 12422.2244
@@ -0,0 +1,57 @@
✔ research evidence binds actual original bytes; model completion is not user acceptance (1552.1792ms)
✔ same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision (1505.9427ms)
✖ foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs (1575.1927ms)
✔ source changes invalidate prior proofs and cannot certify a read that was already stale at binding (1766.564ms)
✔ missing or tampered artifacts never become evidence and original failures remain after recovery (1364.0704ms)
✔ checks omitted by explicit agreement are reported as not executed and never passed (587.6487ms)
✔ user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted (838.4392ms)
✖ existing multi-file results keep provenance and invalidate only evidence whose files changed (681.4337ms)
✔ revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements (1050.4273ms)
✔ requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit (2379.0215ms)
ℹ tests 10
ℹ suites 0
ℹ pass 8
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13669.1366
✖ failing tests:
test at tests\requirement-review.test.mjs:46:1
✖ foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs (1575.1927ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'completed'
- 'error'
at TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/requirement-review.test.mjs:49:10)
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: 'completed',
expected: 'error',
operator: 'strictEqual',
diff: 'simple'
}
test at tests\requirement-review.test.mjs:97:1
✖ existing multi-file results keep provenance and invalidate only evidence whose files changed (681.4337ms)
Error: 成果核对需要1–8个文件和采用原因(最多600字)。
at planError (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/shared/contracts/task-plans.mjs:7:85)
at fileResultInput (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/shared/contracts/file-results.mjs:9:92)
at FileResults.record (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/core/tasks/file-results.mjs:82:18)
at TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/requirement-review.test.mjs:101:21)
at Test.runInAsyncScope (node:async_hooks:227:14)
at Test.run (node:internal/test_runner/test:1402:25)
at Test.processPendingSubtests (node:internal/test_runner/test:974:18)
at Test.postRun (node:internal/test_runner/test:1542:19)
at Test.run (node:internal/test_runner/test:1467:12)
at async Test.processPendingSubtests (node:internal/test_runner/test:974:7) {
status: 400,
code: 'input'
}
@@ -0,0 +1,103 @@
✔ reviewed application invalidates old checks, names current SHA and advances through a new approved check to Git preview (8006.2899ms)
✔ skip-tests, foreign task, unknown operations, diagnostic and parent review retain their boundaries (3220.3363ms)
✔ before the first change, real baseline failures persist across later reads; passed baselines and changed sources cannot certify delivery (8109.818ms)
✔ actual process exit at Git queued never replays a commit and can reconcile the durable result (11808.3151ms)
✔ actual process exit at Git preparing never replays a commit and can reconcile the durable result (12918.244ms)
✔ actual process exit at Git index_locked never replays a commit and can reconcile the durable result (13182.252ms)
✔ actual process exit at Git prepared never replays a commit and can reconcile the durable result (13064.7926ms)
✔ actual process exit at Git ref_prepared never replays a commit and can reconcile the durable result (15265.2045ms)
✔ actual process exit at Git publishing never replays a commit and can reconcile the durable result (14821.7252ms)
✔ actual process exit at Git committed never replays a commit and can reconcile the durable result (11758.6818ms)
✔ actual process exit at Git index_published never replays a commit and can reconcile the durable result (11993.3493ms)
✔ actual process exit at Git finished never replays a commit and can reconcile the durable result (11168.4683ms)
✔ an unknown Git result cannot overwrite an externally changed index or delete an unrelated lock (10687.9182ms)
✔ known publication with a later source edit retains the commit and marks the delivery for inspection (10220.836ms)
✔ CRLF normalization, multiple applied revisions and unrelated special index flags preserve exact bytes and ownership (11029.7137ms)
✔ adding new durable record kinds to an existing hot Store preserves all existing Maps and records (7124.7649ms)
✔ an unrelated owner deletion is fingerprinted and preserved while linked task paths are rejected (12273.1033ms)
✔ actual failed tests become a reviewed local commit and evidence report while preserving unrelated index and files (14986.7618ms)
✔ selected preexisting unstaged, staged and untracked owner edits cannot enter a task commit (15850.852ms)
Switched to a new branch 'owner-branch'
✔ source, unrelated stage and branch changes after review invalidate a commit plan without changing HEAD (20768.3053ms)
Switched to a new branch 'delivery-branch'
✔ a later Git metadata change keeps matching source evidence valid but a real source edit requires checks (10392.4505ms)
✔ a corrupt passed-check log and a pending proposal block Git delivery instead of inventing evidence (5908.2288ms)
HEAD is now at 1c86d9b Sealed delivery fixture baseline
✔ Git filters, merge state, detached HEAD and old task ownership are explicitly rejected (24210.8905ms)
✔ local snapshot commits disable repository hooks and signing and isolate the Git child environment (10676.0356ms)
✔ stopping before publication cancels safely; stopping after publication preserves the actual completed commit (17105.9465ms)
✔ delivery API confirms exactly one owned plan, serves verified reports and preserves results across restart (12250.777ms)
✔ the model can prepare an owned Git review and evidence report while publishing remains a separate user action (8615.1896ms)
✔ HTTP Git review pairs deferred calls, survives reload and never requests more work until the saved preview is resolved (9180.4959ms)
✔ a reviewed Git preview can be revised or withdrawn without publishing or losing the current Task (7990.9902ms)
✔ file targets exclude referenced inputs and prohibited subsequent modifications (1.5056ms)
✔ full actual read and existing receipt complete a no-test file task without fabricating changes, checks or commits (2359.7996ms)
✔ partial pages, partial lines, wrong hashes and failed reads cannot be adopted; contiguous full paging can (1395.2942ms)
✔ user edits and new requirements invalidate receipts, and a second task must explicitly adopt a source in its own project/session (967.5215ms)
✔ adopting an unchanged file never satisfies an explicit modification or a new modification instruction (807.7093ms)
✔ required checks and stale passing flags cannot be bypassed by current file receipts (853.3689ms)
✔ results plan proofs bind current file receipts while changes proofs still demand real applied change sets (742.6083ms)
✔ duplicate receipts cannot create progress indefinitely or reset no-progress reads (3041.4448ms)
✔ manual completion preserves the failed original run and refuses unknown operations (1035.5099ms)
✔ completion refuses active work, files changed during inspection and a newly selected task (881.6419ms)
✔ unrelated files cannot stand in for named output paths, nor can a late apply satisfy newer instructions with an old proposal (865.865ms)
✔ delivery and mobile projections distinguish adopted bytes, new changes, no tests and no commit; mutations cannot rewrite receipts (1183.0686ms)
✔ requirements HTTP binds selection, enforces optimistic revisions, restores original proofs and leaves provider history untouched (5294.9654ms)
✔ research evidence binds actual original bytes; model completion is not user acceptance (1324.8967ms)
✔ same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision (1606.5771ms)
✔ foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs (2233.3666ms)
✔ source changes invalidate prior proofs and cannot certify a read that was already stale at binding (1690.6911ms)
✔ missing or tampered artifacts never become evidence and original failures remain after recovery (1146.2097ms)
✔ checks omitted by explicit agreement are reported as not executed and never passed (727.3222ms)
✔ user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted (1081.7171ms)
✖ existing multi-file results keep provenance and invalidate only evidence whose files changed (1512.3997ms)
✔ revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements (1058.6528ms)
✔ requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit (2420.8938ms)
✔ task-plan HTTP mutations bind current Task/Run and retain original evidence through real host restart (4973.6443ms)
✔ concurrent stale HTTP plan revisions cannot replace conditions or attach proofs to a different plan (2940.7571ms)
✔ a real escaped long-file tool message keeps its proof identity within a tight request budget (1165.079ms)
✔ task plans reject fabricated completion, invalid scopes and cyclic or missing dependencies (0.4848ms)
✔ sealed plans retain goal, contract hash and original steps through SQLite reopen without executing tools (787.5938ms)
✔ proofs require original owned reads, honor dependencies and reject altered invocation arguments and bytes (1801.7125ms)
✔ new user requirements invalidate current proofs and reseal the same original operations in a new revision (1218.1294ms)
✔ applied change-set evidence binds reviewed current files and invalidates dependent steps after outside edits (1417.8683ms)
✔ actual npm checks are verified by original counted logs and current source, with failure history retained (6004.4712ms)
✔ real desktop and mobile browser proofs bind required actions and PNGs, rejecting source changes, a later failed plan and changed builds (10821.5301ms)
✔ Git delivery blocks incomplete plans and changed preview bindings, preserving HEAD and owner index before a fresh verified commit (11427.3762ms)
✔ the runtime supplies owned read IDs and completes a plan only after original step evidence verification (1959.9266ms)
✔ premature model completion pauses the original Task and resume preserves the existing plan without replay (2358.0371ms)
✔ plan operations participate in project activity and orderly shutdown (522.3303ms)
✔ actual process exit before plan save restores only committed plan evidence without replay (865.2045ms)
✔ actual process exit after plan save restores only committed plan evidence without replay (964.916ms)
✔ actual process exit before proof save restores only committed plan evidence without replay (1005.6862ms)
✔ actual process exit after proof save restores only committed plan evidence without replay (1156.9423ms)
ℹ tests 70
ℹ suites 0
ℹ pass 69
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 234908.2313
✖ failing tests:
test at tests\requirement-review.test.mjs:99:1
✖ existing multi-file results keep provenance and invalidate only evidence whose files changed (1512.3997ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'failed'
- 'evidence_verified'
at TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/requirement-review.test.mjs:108:57)
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: 'failed',
expected: 'evidence_verified',
operator: 'strictEqual',
diff: 'simple'
}
@@ -0,0 +1,20 @@
✔ research evidence binds actual original bytes; model completion is not user acceptance (1394.7013ms)
✔ same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision (1296.8304ms)
✔ foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs (1830.999ms)
✔ source changes invalidate prior proofs and cannot certify a read that was already stale at binding (1533.3651ms)
✔ missing or tampered artifacts never become evidence and original failures remain after recovery (1341.5835ms)
✔ checks omitted by explicit agreement are reported as not executed and never passed (555.3679ms)
✔ user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted (967.115ms)
✔ existing multi-file results keep provenance and invalidate only evidence whose files changed (2137.0822ms)
✔ unrelated additions preserve the checked file facts but remain visible as unreviewed user sources (972.5268ms)
✔ actual Git preview and publication recheck changed requirement bindings without touching HEAD or the owner index (6001.6743ms)
✔ revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements (685.7744ms)
✔ requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit (1659.4181ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 20571.3702
Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

@@ -0,0 +1,130 @@
{
"success": true,
"passed": [
"manual source selection creates pending requirement, never automatic acceptance",
"actual original read proof verified through UI",
"saved requirement and proof survive page refresh",
"requirement revision invalidates its proof and preserves original history",
"source mutation and stale original read are visible failures with preserved history",
"390px viewport keeps requirement controls usable without page overflow",
"late response for original Task cannot replace the newly selected task"
],
"screenshots": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5\\desktop-verified.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5\\desktop-stale.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5\\narrow-stale.png"
],
"errors": [],
"requirements": {
"configured": true,
"task_id": "933dee08-794b-4e39-84af-c7ed67ca62b7",
"revision": 2,
"sources": [
{
"kind": "goal",
"id": "933dee08-794b-4e39-84af-c7ed67ca62b7",
"text": "研究现有README.md,说明原工程依据,不修改参考文件。",
"at": "2026-11-04T02:29:35.261Z",
"sha256": "5228c1f5b051001b370ad2b9bcd7b33b0312b1c26a42cd094cd77ff2d6b23c0c"
}
],
"items": [
{
"key": "req_c0722d35",
"title": "解释当前工程的实际依据",
"criterion": "追加核对当前说明,旧复核记录保留",
"kind": "analysis",
"depends_on": [],
"tools": [
"read_file"
],
"method": "evidence",
"source": {
"kind": "goal",
"id": "933dee08-794b-4e39-84af-c7ed67ca62b7",
"start": 0,
"end": 30,
"quote": "研究现有README.md,说明原工程依据,不修改参考文件。",
"sourceSha256": "5228c1f5b051001b370ad2b9bcd7b33b0312b1c26a42cd094cd77ff2d6b23c0c",
"at": "2026-11-04T02:29:35.261Z"
},
"revision": 2,
"status": "evidence_verified",
"error": null,
"evidence": {
"kind": "tool",
"id": "692db770-0a5b-4ab1-929c-401e06f1ddab",
"runId": "7e7ba559-c871-42cf-b1d5-aecc9713e4b4",
"scope": "historical_read_operation",
"tool": "read_file",
"callId": "plan-read-6ba482c7-8d4a-4ceb-9b34-27171290181e",
"argsSha256": "7d6441497d2a000b8143602a7817c90abe7db88e139f89c062a1c36cfe0ad9d6",
"artifacts": [
{
"id": "037823a7-6503-45c6-a498-00a89f7246d1",
"kind": "tool-result",
"runId": "7e7ba559-c871-42cf-b1d5-aecc9713e4b4",
"sha256": "8ae1054bb2153ac6da69d5523004c1d6b600ea5199addfd45a7f57a82dd959be",
"bytes": 251
}
]
},
"proof_id": "877b6254-38c3-4c6d-bd85-8f8a73530130",
"proof_artifact_id": "5243af83-59a3-47a3-8894-aa72eda6f38c",
"user_note": null,
"last_rejection": {
"id": "63e57ce1-6e6d-4665-9eae-3a6eca94ef5e",
"message": "原读取对应旧文件SHA,请使用当前文件的实际读取。",
"at": "2026-11-04T02:29:40.352Z"
},
"candidates": [
{
"id": "692db770-0a5b-4ab1-929c-401e06f1ddab",
"status": "completed",
"label": "read_file",
"runId": "7e7ba559-c871-42cf-b1d5-aecc9713e4b4"
}
]
}
],
"all_resolved": true,
"binding_sha256": "45643c9b9687fe9e9bcd6057a23604bb7f55bbc4c6d876fd56413203784104f8",
"note": "证据核对只证明所选范围;模型完成答复不等于业务验收。",
"unreviewed_sources": [],
"status": "resolved",
"history": [
{
"id": "73383101-7b30-4c06-904a-ab883cd1619a",
"key": "req_c0722d35",
"revision": 1,
"status": "verified",
"error": null,
"at": "2026-11-04T02:29:38.685Z",
"artifact_id": "e4dc4f1e-9c1e-4091-84b7-635a1286cd3d"
},
{
"id": "877b6254-38c3-4c6d-bd85-8f8a73530130",
"key": "req_c0722d35",
"revision": 2,
"status": "verified",
"error": null,
"at": "2026-11-04T02:29:39.845Z",
"artifact_id": "5243af83-59a3-47a3-8894-aa72eda6f38c"
},
{
"id": "63e57ce1-6e6d-4665-9eae-3a6eca94ef5e",
"key": "req_c0722d35",
"revision": 2,
"status": "rejected",
"error": "原读取对应旧文件SHA,请使用当前文件的实际读取。",
"at": "2026-11-04T02:29:40.352Z",
"artifact_id": "e6112cac-766f-43c1-8f1d-d5203861fd17"
}
],
"contract_artifact_id": "13a396f2-9b7b-4e53-97f9-217a9942a115",
"contract_sha256": "9518b6e307f95990a535dd3557da8f79312156ae535a6333b8df7236c2c18cfd"
},
"realModelRequests": 0,
"officialServiceTouched": false,
"companionWritePermissionsAdded": false
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

@@ -0,0 +1,10 @@
{
"success": false,
"passed": [],
"screenshots": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-b16d50fd-3185-4257-b6e2-d404bcd016b2\\failure.png"
],
"errors": [],
"error": "locator.waitFor: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - waiting for getByRole('dialog', { name: '记录用户要求', exact: true }) to be hidden\u001b[22m\n\u001b[2m 63 × locator resolved to visible <div role=\"dialog\" aria-modal=\"true\" aria-label=\"记录用户要求\" class=\"modal modal-wide\">…</div>\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-requirements-ui.mjs:42:89",
"realModelRequests": 0
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

@@ -0,0 +1,18 @@
{
"success": false,
"passed": [
"manual source selection creates pending requirement, never automatic acceptance",
"actual original read proof verified through UI",
"saved requirement and proof survive page refresh",
"requirement revision invalidates its proof and preserves original history",
"source mutation and stale original read are visible failures with preserved history"
],
"screenshots": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-be243cdc-aace-4a11-9528-559b5aa6a275\\desktop-verified.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-be243cdc-aace-4a11-9528-559b5aa6a275\\desktop-stale.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-be243cdc-aace-4a11-9528-559b5aa6a275\\failure.png"
],
"errors": [],
"error": "locator.scrollIntoViewIfNeeded: Timeout 29993.504999999997ms exceeded.\nCall log:\n\u001b[2m - attempting scroll into view action\u001b[22m\n\u001b[2m 2 × waiting for element to be stable\u001b[22m\n\u001b[2m - element is not visible\u001b[22m\n\u001b[2m - retrying scroll into view action\u001b[22m\n\u001b[2m - waiting 20ms\u001b[22m\n\u001b[2m 2 × waiting for element to be stable\u001b[22m\n\u001b[2m - element is not visible\u001b[22m\n\u001b[2m - retrying scroll into view action\u001b[22m\n\u001b[2m - waiting 100ms\u001b[22m\n\u001b[2m 58 × waiting for element to be stable\u001b[22m\n\u001b[2m - element is not visible\u001b[22m\n\u001b[2m - retrying scroll into view action\u001b[22m\n\u001b[2m - waiting 500ms\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-requirements-ui.mjs:61:74",
"realModelRequests": 0
}
@@ -0,0 +1,8 @@
PASS manual source selection creates pending requirement, never automatic acceptance
PASS actual original read proof verified through UI
PASS saved requirement and proof survive page refresh
PASS requirement revision invalidates its proof and preserves original history
PASS source mutation and stale original read are visible failures with preserved history
PASS 390px viewport keeps requirement controls usable without page overflow
PASS late response for original Task cannot replace the newly selected task
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5","success":true,"passed":["manual source selection creates pending requirement, never automatic acceptance","actual original read proof verified through UI","saved requirement and proof survive page refresh","requirement revision invalidates its proof and preserves original history","source mutation and stale original read are visible failures with preserved history","390px viewport keeps requirement controls usable without page overflow","late response for original Task cannot replace the newly selected task"],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5\\desktop-verified.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5\\desktop-stale.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-4ef3fe47-6893-4edf-8115-192e5e6f37d5\\narrow-stale.png"],"errors":[],"realModelRequests":0,"officialServiceTouched":false,"companionWritePermissionsAdded":false}
@@ -0,0 +1 @@
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-b16d50fd-3185-4257-b6e2-d404bcd016b2","success":false,"passed":[],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-b16d50fd-3185-4257-b6e2-d404bcd016b2\\failure.png"],"errors":[],"error":"locator.waitFor: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - waiting for getByRole('dialog', { name: '记录用户要求', exact: true }) to be hidden\u001b[22m\n\u001b[2m 63 × locator resolved to visible <div role=\"dialog\" aria-modal=\"true\" aria-label=\"记录用户要求\" class=\"modal modal-wide\">…</div>\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-requirements-ui.mjs:42:89","realModelRequests":0}
@@ -0,0 +1,6 @@
PASS manual source selection creates pending requirement, never automatic acceptance
PASS actual original read proof verified through UI
PASS saved requirement and proof survive page refresh
PASS requirement revision invalidates its proof and preserves original history
PASS source mutation and stale original read are visible failures with preserved history
{"directory":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-be243cdc-aace-4a11-9528-559b5aa6a275","success":false,"passed":["manual source selection creates pending requirement, never automatic acceptance","actual original read proof verified through UI","saved requirement and proof survive page refresh","requirement revision invalidates its proof and preserves original history","source mutation and stale original read are visible failures with preserved history"],"screenshots":["D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-be243cdc-aace-4a11-9528-559b5aa6a275\\desktop-verified.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-be243cdc-aace-4a11-9528-559b5aa6a275\\desktop-stale.png","D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\requirements-progress\\ui-be243cdc-aace-4a11-9528-559b5aa6a275\\failure.png"],"errors":[],"error":"locator.scrollIntoViewIfNeeded: Timeout 29993.504999999997ms exceeded.\nCall log:\n\u001b[2m - attempting scroll into view action\u001b[22m\n\u001b[2m 2 × waiting for element to be stable\u001b[22m\n\u001b[2m - element is not visible\u001b[22m\n\u001b[2m - retrying scroll into view action\u001b[22m\n\u001b[2m - waiting 20ms\u001b[22m\n\u001b[2m 2 × waiting for element to be stable\u001b[22m\n\u001b[2m - element is not visible\u001b[22m\n\u001b[2m - retrying scroll into view action\u001b[22m\n\u001b[2m - waiting 100ms\u001b[22m\n\u001b[2m 58 × waiting for element to be stable\u001b[22m\n\u001b[2m - element is not visible\u001b[22m\n\u001b[2m - retrying scroll into view action\u001b[22m\n\u001b[2m - waiting 500ms\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-requirements-ui.mjs:61:74","realModelRequests":0}
@@ -0,0 +1,17 @@
PASS manual source selection creates pending requirement, never automatic acceptance
PASS actual original read proof verified through UI
PASS saved requirement and proof survive page refresh
PASS requirement revision invalidates its proof and preserves original history
PASS source mutation and stale original read are visible failures with preserved history
PASS 390px viewport keeps requirement controls usable without page overflow
node:internal/process/promises:394
triggerUncaughtException(err, true /* fromPromise */);
^
route.continue: Route is already handled!
at D:\Ai-project\REA逆向\Agent-Workbench\scripts\verify-requirements-ui.mjs:67:170 {
log: [],
name: 'Error'
}
Node.js v24.22.1
+2
View File
@@ -2,6 +2,8 @@
## 本轮实现边界
实现复核时额外发现两个完成入口:无测试文件应用的同步settleAppliedTask与手动completeFileResults。前者配置要求时保留paused,后者走当前要求复核;避免模型完成/Git已受门控而手动路径绕过。逐文件成果复核核对原凭据/原来源链和要求指定文件当前SHA;不把无关新增来源抹掉,也不把旧全Task成果凭据自动当新要求通过,原文件交付硬门保持。
研究证据的14产品输入原本按工作区核对,后续实现必然导致历史误失效;改为核对manifest固定676fc554 Git对象,不改变原报告/输入SHA/探针。采用计划A复用已有TaskPlanManager的五类原证据校验,避免另建一套执行或Git门;B仅shadow,模型文字不能充当工程增长。
## Tianshu 已核对的机制与边界
+12
View File
@@ -2,6 +2,18 @@
## 本轮恢复与研究收口
A开发切片完成:53/53最终相关、手机新路由拒绝1/1,网页7组(桌面/390px/晚响应)和实际Electron3组,TypeScript/完整构建通过。最终Electron隐藏窗口截图首超时,按现有showInactive/setContentSize实际窗口流程修正;原两次日志及原失败均保留。新增来源保留未审阅,逐文件证据不受无关文件增改影响,模型文字/手动结束/无测试应用/Git预览发布均不越过要求复核。源码/日志/最终结果与截图封存,阶段回顾见docs/REQUIREMENTS-REVIEW-A.md。仅开发切片,正式仍1.24.8,真实模型0;发行安装和真实交付/Purge未验证保持。
A首索引验收拒绝被全局*.log忽略的所属证据;仅为本阶段docs证据目录添加明确例外,不纳入.qa。原源码快照保留checkout字节,Git源核对明确只允许既有text属性的CRLF→LF表示转换,继续要求内容SHA一致。
索引原字节45份1299321字节通过后,cached diff将原CRLF日志及原源码末空行标为格式问题;原件不修剪,本阶段证据声明binary,活跃源码仍正常审查。
要求复核首10项8通过2失败,原日志.qa/requirements-progress/requirements-first.tap保留:旧Task用例误把原Task续接当新Task,改显式结束旧Task再建立;已有成果用例误传paths,改按现有files/SHA/user来源契约。产品首构建/TypeScript通过。复核模块复用现有Task与原证据,不开放模型自签业务验收;正式和Key保持,真实模型0。
首实际网页保存没有关闭表单;截图与原结果保留ui-b16d50fd。定位是新组件把现有api(path,input)误当fetch options,服务正确拒绝Task/Run字段;修正为直接传契约输入,不放松服务归属校验。
相关70项69通过,唯一失败是新增已有成果用例取错返回字段id而应result_id;改并加强首次核验断言,不放松校验。网页第二轮前五组(保存/原证据/刷新/修订/源码失效)通过,390px切换后现有任务栏需重新打开,驱动按实际导航修正,原失败保留。
用户要求继续A/B要求证据与单轮观察。核对HEAD 676fc554、分支feat/tianshu-harness-research:既有改动仅研究文档/证据/自有验证器和计划,没有产品实现。原研究8份113756字节、63固定来源/14产品输入/6纯案例离线通过。收口验证器改读固定产品Git对象,使未来产品变动不改写旧研究。正式服务/Provider未操作,真实模型0;V网络partial、原T/R/P/O、重复读取和Purge未知保持。
固定Git字节首核验拒绝PLAN-1.25的2556/LF与原2583/CRLF差异;原索引不改,验证器仅还原历史CRLF表示并继续要求原SHA,不能跳过内容差异。
+53
View File
@@ -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 }));
+54
View File
@@ -0,0 +1,54 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { _electron } from 'playwright';
import { fixture, until } from '../tests/helpers.mjs';
import { beginPlanTask, completeRead } from '../tests/fixtures/task-plan-fixture.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';
const root = path.resolve('.qa/requirements-progress', 'electron-' + randomUUID()); fs.mkdirSync(root, { recursive: true });
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t);
beginPlanTask(f, '解释当前工程依据,保留用户原文和原读取。'); completeRead(f); f.session.title = 'Electron要求证据原任务'; f.store.save(f.session); f.store.close();
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);
const controller = new HostController({ appRoot: process.cwd(), dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 });
const passed = [], errors = [], screenshots = []; let application, result;
const mark = name => { passed.push(name); console.log('PASS ' + name); };
try {
await controller.start(); assert.equal((await controller.api('/bootstrap')).config.hasKey, false);
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 });
const page = await application.firstWindow(); page.on('pageerror', error => errors.push(error.message));
const window = await application.browserWindow(page); await window.evaluate(win => win.setSize(1440, 1080));
await page.locator('.connection.connected').waitFor(); assert.equal(await page.evaluate(() => typeof window.process), 'undefined');
await page.getByLabel('当前项目').selectOption(f.project.id); await page.locator('.session-list button').filter({ hasText: f.session.title }).click();
await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
const panel = page.getByLabel('要求与证据', { exact: true }); await until(() => panel.getByRole('button', { name: '记录要求', exact: true }).isEnabled());
await panel.getByRole('button', { name: '记录要求', exact: true }).click();
const editor = page.getByRole('dialog', { name: '记录用户要求', exact: true });
await editor.getByLabel('要求名称', { exact: true }).fill('原生窗口核对工程说明'); await editor.getByLabel('要求验收条件', { exact: true }).fill('实际读取当前文件,保留原来源');
await editor.getByRole('button', { name: '保存要求', exact: true }).click(); await editor.waitFor({ state: 'hidden' }); mark('sandboxed actual Electron saves a sourced requirement');
const row = panel.locator('.requirement-list > li').first(); await row.getByRole('combobox').selectOption({ index: 1 });
await row.getByRole('button', { name: '复核所选证据', exact: true }).click(); await until(async () => (await row.locator('.requirement-state').textContent()) === '所选证据已核对');
mark('actual Electron verifies the original tool result');
await page.reload(); await page.locator('.connection.connected').waitFor();
if (!await panel.isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await until(async () => (await row.locator('.requirement-state').textContent()) === '所选证据已核对');
await window.evaluate(win => { win.showInactive(); win.setContentSize(1440, 1080); });
await until(() => page.evaluate(() => innerWidth === 1440));
await panel.scrollIntoViewIfNeeded(); const screenshot = path.join(root, 'verified.png'); await page.screenshot({ path: screenshot }); screenshots.push(screenshot);
mark('renderer reload restores the same Task and requirement proof'); assert.deepEqual(errors, []);
result = { success: true, passed, errors, screenshots, actualElectron: true, installationValidated: false, realModelRequests: 0, officialServiceTouched: false };
} catch (error) { result = { success: false, passed, errors, screenshots, error: error.stack, realModelRequests: 0 }; }
finally {
if (application) await application.close(); if (await controller.health()) await controller.stop();
for (const dispose of disposers.reverse()) await dispose();
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ root, ...result })); if (!result.success) process.exitCode = 1;
+84
View File
@@ -0,0 +1,84 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { chromium } from 'playwright';
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
import { beginPlanTask, completeRead } from '../tests/fixtures/task-plan-fixture.mjs';
const directory = path.resolve('.qa/requirements-progress', 'ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t);
beginPlanTask(f, '研究现有README.md,说明原工程依据,不修改参考文件。'); const read = completeRead(f);
f.session.title = '要求复核原工程'; f.store.save(f.session);
const other = f.store.createSession(f.project.id), originalSession = f.session; f.session = other; beginPlanTask(f, '另一个独立研究目标');
other.title = '另一任务的独立目标'; f.store.save(other); f.session = originalSession; f.store.close();
const host = await launchWorkbench(t, f.data); assert.notEqual(new URL(host.url).port, '4318'); assert.equal(host.bootstrap.config.hasKey, false);
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1080 } });
const passed = [], screenshots = [], errors = [];
page.on('pageerror', error => errors.push(error.message));
const panel = () => page.getByLabel('要求与证据', { exact: true }), row = () => panel().locator('.requirement-list > li').first();
const mark = name => { passed.push(name); console.log('PASS ' + name); };
const shot = async name => { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' }); screenshots.push(file); };
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();
if (!await panel().isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await panel().getByRole('button', { name: '记录要求', exact: true }).waitFor();
await until(async () => await panel().getByRole('button', { name: '记录要求', exact: true }).isEnabled());
}
async function verify() {
await row().getByRole('combobox').selectOption(read.id);
await row().getByRole('button', { name: '复核所选证据', exact: true }).click();
await until(async () => (await row().locator('.requirement-state').textContent()) === '所选证据已核对');
}
let result;
try {
await page.goto(host.url); await select(f.session);
await panel().getByRole('button', { name: '记录要求', exact: true }).click();
const editor = page.getByRole('dialog', { name: '记录用户要求', exact: true });
await editor.getByLabel('要求名称', { exact: true }).fill('解释当前工程的实际依据');
await editor.getByLabel('要求验收条件', { exact: true }).fill('保留README原读取和可核对结论,参考文件保持原字节');
await editor.getByRole('button', { name: '保存要求', exact: true }).click(); await editor.waitFor({ state: 'hidden' });
assert.equal(await row().locator('.requirement-state').textContent(), '待复核'); mark('manual source selection creates pending requirement, never automatic acceptance');
await verify(); mark('actual original read proof verified through UI');
await panel().scrollIntoViewIfNeeded(); await shot('desktop-verified');
await page.reload(); await select(f.session); await until(async () => (await row().locator('.requirement-state').textContent()) === '所选证据已核对');
mark('saved requirement and proof survive page refresh');
await row().getByRole('button', { name: '修订此要求', exact: true }).click();
await editor.getByLabel('要求验收条件', { exact: true }).fill('追加核对当前说明,旧复核记录保留');
await editor.getByRole('button', { name: '保存要求', exact: true }).click(); await editor.waitFor({ state: 'hidden' });
await until(async () => (await row().locator('.requirement-state').textContent()) === '待复核');
assert.match(await panel().textContent(), /原复核历史.*1 条/s); mark('requirement revision invalidates its proof and preserves original history');
await verify();
const file = path.join(f.projectRoot, 'README.md'), original = fs.readFileSync(file); fs.appendFileSync(file, '\nChanged externally in owned fixture\n');
await panel().getByRole('button', { name: '刷新复核', exact: true }).click();
await until(async () => (await row().locator('.requirement-state').textContent()) === '依据已失效');
await row().getByRole('button', { name: '复核所选证据', exact: true }).click();
await until(async () => (await panel().textContent()).includes('原读取对应旧文件SHA'));
await panel().scrollIntoViewIfNeeded(); await shot('desktop-stale'); mark('source mutation and stale original read are visible failures with preserved history');
fs.writeFileSync(file, original);
await page.setViewportSize({ width: 390, height: 844 });
if (!await panel().isVisible()) await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await panel().scrollIntoViewIfNeeded(); await shot('narrow-stale');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), true); mark('390px viewport keeps requirement controls usable without page overflow');
await page.setViewportSize({ width: 1440, height: 1080 });
let release = null, held = false;
await page.route('**/requirements?taskId=' + f.session.taskId, async route => {
held = true; await new Promise(resolve => { release = resolve; });
try { await route.continue(); } catch (error) { if (!/Route is already handled|Invalid InterceptionId/.test(error.message)) errors.push(error.message); }
});
await panel().getByRole('button', { name: '刷新复核', exact: true }).click(); await until(() => held);
await select(other); release(); await page.unroute('**/requirements?taskId=' + f.session.taskId);
await until(async () => (await panel().textContent()).includes('尚未逐项记录要求'));
assert.ok(!(await panel().textContent()).includes('解释当前工程的实际依据')); mark('late response for original Task cannot replace the newly selected task');
assert.deepEqual(errors, []);
const requirements = await host.api('/sessions/' + f.session.id + '/requirements?taskId=' + f.session.taskId);
result = { success: true, passed, screenshots, errors, requirements, realModelRequests: 0, officialServiceTouched: false, companionWritePermissionsAdded: false };
} catch (error) {
await shot('failure').catch(() => {}); result = { success: false, passed, screenshots, errors, error: error.stack, realModelRequests: 0 };
} finally {
await browser.close(); for (const dispose of disposers.reverse()) await dispose();
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result, requirements: undefined })); if (!result.success) process.exitCode = 1;
+19
View File
@@ -0,0 +1,19 @@
.requirement-list { list-style: none; padding: 0; margin: 0; }
.requirement-list > li { padding: 14px 0; border-top: 1px solid #dce7e2; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.requirement-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; }
.requirement-heading strong { font-size: 13px; }
.requirement-state { color: #674917; background: #fbf2df; padding: 2px 6px; border-radius: 3px; flex-shrink: 0; font-size: 11px; }
.requirement-evidence_verified, .requirement-user_confirmed { color: #154b4a; background: #edf3f1; }
.requirement-list summary, .requirement-history summary { cursor: pointer; color: #526a70; }
.requirement-list blockquote, .requirement-quote { margin: 9px 0; border-left: 2px solid #bbcfc7; padding: 6px 12px; white-space: pre-wrap; font-size: 12px; max-height: 150px; overflow: auto; }
.requirement-list code { font-size: 10px; overflow-wrap: anywhere; }
.requirement-actions { display: flex; flex-wrap: wrap; gap: 12px; margin: 7px 0; }
.requirement-confirm label { display: grid; gap: 6px; }
.requirement-confirm textarea { width: 100%; box-sizing: border-box; font: inherit; padding: 8px; border: 1px solid #cbded3; border-radius: 5px; margin-bottom: 8px; }
.requirement-history { font-size: 11px; margin-top: 12px; }
.requirement-history p { display: grid; gap: 4px; }
.requirement-editor { max-height: 72vh; overflow: auto; }
.requirement-offsets { display: flex; gap: 12px; margin: 12px 0; }
.requirement-offsets label { min-width: 0; font-size: 12px; }
.requirement-panel button:focus-visible, .requirement-panel textarea:focus-visible, .requirement-editor :is(input, select, textarea):focus-visible { outline: 2px solid #4664d9; outline-offset: 2px; }
@media (max-width: 600px) { .requirement-heading { flex-direction: column; gap: 4px; } .requirement-panel .button { min-height: 36px; } }
+102
View File
@@ -0,0 +1,102 @@
import { useEffect, useRef, useState } from 'react';
import { Check, FileText, Plus, RefreshCw } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { RequirementItem, RequirementView, Session, TaskPlanStep } from './types';
import './RequirementPanel.css';
const states: Record<string, string> = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对',
evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行' };
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
const clean = (row: RequirementItem) => ({ key: row.key, title: row.title, criterion: row.criterion, kind: row.kind, method: row.method,
source: { kind: row.source.kind, id: row.source.id, start: row.source.start, end: row.source.end },
...(row.kind === 'analysis' ? { tools: row.tools } : ['changes', 'results'].includes(row.kind) ? { paths: row.paths }
: row.kind === 'checks' ? { checks: row.checks } : { viewport_width: row.viewport_width, actions: row.actions }) });
const scope = (kind: TaskPlanStep['kind']) => kind === 'analysis' ? { tools: ['read_file'] } : ['changes', 'results'].includes(kind)
? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] };
export function RequirementPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task, run = session.execution?.run;
const identity = `${session.projectId}/${session.id}/${task?.id}/${run?.id}`;
const selected = useRef(identity); selected.current = identity;
const generation = useRef(0), mutation = useRef(false);
const [view, setView] = useState<RequirementView | null>(null), [loading, setLoading] = useState(false), [saving, setSaving] = useState(false);
const [draft, setDraft] = useState<RequirementItem | null>(null), [picked, setPicked] = useState<Record<string, string>>({}), [notes, setNotes] = useState<Record<string, string>>({});
const [notice, setNotice] = useState('');
const disabled = busy || saving || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => { generation.current++; setView(null); setDraft(null); setPicked({}); setNotes({}); setNotice(''); setSaving(false); mutation.current = false;
return () => { generation.current++; }; }, [identity]);
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, session.revision, session.status]);
async function load() {
if (!task || mutation.current) return;
const scopeId = identity, request = ++generation.current; setLoading(true);
try { const result = await api<RequirementView>(`/sessions/${session.id}/requirements?taskId=${task.id}`);
if (selected.current === scopeId && generation.current === request) setView(result);
} catch (error) { if (selected.current === scopeId && generation.current === request) onError(error); }
finally { if (selected.current === scopeId && generation.current === request) setLoading(false); }
}
async function mutate(action: string, input: object) {
if (!task || !run || !view || mutation.current) return;
mutation.current = true; generation.current++; setSaving(true); setNotice(''); const scopeId = identity;
try {
const reply = await api<{ session: Session; requirements: RequirementView; verification?: { status: string; message?: string } }>(`/sessions/${session.id}/${action}`,
{ taskId: task.id, runId: run.id, expected_revision: view.revision, ...input });
if (selected.current !== scopeId) return;
setView(reply.requirements); onSession(reply.session);
setNotice(reply.verification?.status === 'error' ? reply.verification.message ?? '复核未通过,原失败已保留。' : action === 'requirements' ? '要求与原文来源已保存。' : '本次复核已记录。');
if (action === 'requirements') setDraft(null);
} catch (error) { if (selected.current === scopeId) onError(error); }
finally { if (selected.current === scopeId) { mutation.current = false; setSaving(false); setLoading(false); } }
}
function edit(row?: RequirementItem) {
const source = view?.sources[0]; if (!source) return;
setDraft(row ? { ...clean(row), depends_on: [] } : { key: 'req_' + crypto.randomUUID().slice(0, 8), title: '', criterion: '', kind: 'analysis', method: 'evidence',
source: { kind: source.kind, id: source.id, start: 0, end: source.text.length }, depends_on: [], ...scope('analysis') });
}
const source = view?.sources.find(row => row.id === draft?.source.id && row.kind === draft?.source.kind);
return <section className="task-record-section requirement-panel" aria-label="要求与证据">
<div className="record-heading"><h3>要求与证据</h3><span>{view?.items.length ?? 0} 项</span></div>
<p className="record-footnote">逐项保留用户原文与实际依据,工程证据和用户体验分别记录。</p>
<div className="plan-toolbar"><button className="text-button" disabled={loading || disabled} onClick={() => void load()}><RefreshCw size={13} />刷新复核</button>
<button className="button secondary" disabled={disabled || !view || view.status === 'unverified' || (view.items.length >= 24)} onClick={() => edit()}><Plus size={13} />记录要求</button></div>
{notice && <p className="plan-notice" role="status">{notice}</p>}
{view?.error && <p className="plan-problem" role="alert">{view.error}</p>}
{!!view?.unreviewed_sources?.length && <p className="plan-problem">有 {view.unreviewed_sources.length} 份用户来源尚未审阅。核对原目标和追加要求后保存要求;旧复核记录保留。</p>}
{view && !view.items.length && <p className="record-empty">尚未逐项记录要求。模型的完成答复保留在原会话中。</p>}
<ol className="requirement-list">{view?.items.map(row => <li key={row.key}>
<div className="requirement-heading"><strong>{row.title}</strong><span className={'requirement-state requirement-' + row.status}>{states[row.status ?? 'pending'] ?? row.status}</span></div>
<p>{row.criterion}</p>
<details><summary>用户原文 · {row.source.kind === 'goal' ? '原目标' : '追加要求'} · 要求修订 {row.revision}</summary>
<blockquote>{row.source.quote}</blockquote><code>{row.source.id} [{row.source.start}, {row.source.end})</code></details>
{row.error && <p className="plan-problem">{row.error}</p>}{row.last_rejection && <p className="plan-problem">原复核失败:{row.last_rejection.message}</p>}
{row.user_note && <p>用户确认:{row.user_note}</p>}
<div className="requirement-actions"><button className="text-button" disabled={disabled} onClick={() => edit(row)}>修订此要求</button>
{row.proof_artifact_id && <button className="text-button" onClick={() => openArtifact(row.proof_artifact_id!)}><FileText size={13} />原复核记录</button>}</div>
{row.method === 'evidence' && <div className="plan-evidence"><label>选择实际依据 · {kinds[row.kind]}<select aria-label={`要求依据 ${row.title}`} disabled={disabled} value={picked[row.key] ?? ''} onChange={event => setPicked(values => ({ ...values, [row.key]: event.target.value }))}>
<option value="">选择此任务的原结果</option>{row.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}</select></label>
<button className="button secondary" disabled={disabled || !picked[row.key]} onClick={() => void mutate('requirement-proofs', { key: row.key, evidence_id: picked[row.key] })}><Check size={13} />复核所选证据</button></div>}
{row.method === 'user' && <div className="requirement-confirm"><label>实际体验与结论<textarea aria-label={`用户确认 ${row.title}`} rows={2} maxLength={1000} disabled={disabled} value={notes[row.key] ?? ''} onChange={event => setNotes(values => ({ ...values, [row.key]: event.target.value }))} /></label>
<button className="button secondary" disabled={disabled || !notes[row.key]?.trim()} onClick={() => void mutate('requirement-proofs', { key: row.key, note: notes[row.key] })}>记录用户确认</button></div>}
{row.method === 'not_requested' && <p className="record-footnote">检查未执行,不计为测试通过。</p>}
</li>)}</ol>
{!!view?.history?.length && <details className="requirement-history"><summary>原复核历史 · {view.history.length} 条</summary>{view.history.map(row => <p key={row.id}><button className="text-button" onClick={() => openArtifact(row.artifact_id)}>{row.key} · 修订 {row.revision} · {row.status === 'rejected' ? '未通过' : '已记录'}</button>{row.error && <span>{row.error}</span>}</p>)}</details>}
{draft && view && <Modal title="记录用户要求" description="选定用户原文、验收范围和复核方式;修订保留旧要求与原失败。" wide onClose={() => { if (!saving) setDraft(null); }}>
<form className="plan-editor requirement-editor" onSubmit={event => { event.preventDefault(); const rows = view.items.some(row => row.key === draft.key) ? view.items.map(row => row.key === draft.key ? clean(draft) : clean(row)) : [...view.items.map(clean), clean(draft)]; void mutate('requirements', { requirements: rows }); }}>
<fieldset disabled={saving} className="plan-editor-step">
<label>要求名称<input aria-label="要求名称" maxLength={100} required value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} /></label>
<label>验收条件<textarea aria-label="要求验收条件" rows={2} required maxLength={300} value={draft.criterion} onChange={event => setDraft({ ...draft, criterion: event.target.value })} /></label>
<label>用户原文来源<select aria-label="要求原文来源" value={draft.source.id} onChange={event => { const row = view.sources.find(value => value.id === event.target.value)!; setDraft({ ...draft, source: { kind: row.kind, id: row.id, start: 0, end: row.text.length } }); }}>{view.sources.map((row, i) => <option key={row.id} value={row.id}>{row.kind === 'goal' ? '原目标' : `追加要求 ${i}`} · {row.text.slice(0, 65)}</option>)}</select></label>
<blockquote className="requirement-quote">{source?.text.slice(draft.source.start, draft.source.end)}</blockquote>
<div className="requirement-offsets"><label>原文起点<input aria-label="原文起点" type="number" min={0} max={Math.max(0, (source?.text.length ?? 1) - 1)} value={draft.source.start} onChange={event => setDraft({ ...draft, source: { ...draft.source, start: Number(event.target.value) } })} /></label><label>原文终点<input aria-label="原文终点" type="number" min={draft.source.start + 1} max={source?.text.length} value={draft.source.end} onChange={event => setDraft({ ...draft, source: { ...draft.source, end: Number(event.target.value) } })} /></label></div>
<label>复核方式<select aria-label="要求复核方式" value={draft.method} onChange={event => setDraft({ ...draft, method: event.target.value as RequirementItem['method'], ...(event.target.value === 'not_requested' ? { kind: 'checks', checks: ['test', 'build'] } : {}) })}><option value="evidence">核对实际证据</option><option value="user">用户体验确认</option><option value="not_requested">按用户约定不执行检查</option></select></label>
{draft.method === 'evidence' && <><label>证据类别<select aria-label="要求证据类别" value={draft.kind} onChange={event => { const kind = event.target.value as TaskPlanStep['kind']; setDraft({ ...draft, kind, ...scope(kind) }); }}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
{['results', 'changes'].includes(draft.kind) && <label>文件范围(每行一项)<textarea aria-label="要求文件范围" required value={draft.paths?.join('\n') ?? ''} onChange={event => setDraft({ ...draft, paths: event.target.value.split('\n').filter(Boolean) })} /></label>}
{draft.kind === 'analysis' && <label>读取工具(逗号分隔)<input aria-label="要求读取工具" required value={draft.tools?.join(',') ?? ''} onChange={event => setDraft({ ...draft, tools: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{draft.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label="要求检查名称" required value={draft.checks?.join(',') ?? ''} onChange={event => setDraft({ ...draft, checks: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{draft.kind === 'browser' && <label>验收视口<select aria-label="要求验收视口" value={draft.viewport_width} onChange={event => setDraft({ ...draft, viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option></select></label>}</>}
</fieldset><div className="modal-actions"><button type="button" className="button secondary" disabled={saving} onClick={() => setDraft(null)}>取消</button><button className="button primary" disabled={saving}>保存要求</button></div>
</form></Modal>}
</section>;
}
+3
View File
@@ -9,6 +9,7 @@ import { RequestContextPanel } from './RequestContextPanel';
import { WorkspacePanel } from './WorkspacePanel';
import { BrowserPanel } from './BrowserPanel';
import { TaskPlanPanel } from './TaskPlanPanel';
import { RequirementPanel } from './RequirementPanel';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
@@ -26,6 +27,7 @@ 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;
@@ -99,6 +101,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
</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} />}
+11
View File
@@ -228,6 +228,17 @@ export interface TaskPlanView {
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 }
+15 -2
View File
@@ -9,12 +9,13 @@ 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 { 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: '当前成果已核对,无新增修改', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
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', ' ');
@@ -103,6 +104,7 @@ export class DeliveryReporter {
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; }
@@ -125,6 +127,7 @@ export class DeliveryReporter {
const status = requiresVerification.length || unresolved.length ? 'needs_verification'
: ['running', 'awaiting_approval', 'stopping'].includes(session.status) ? 'in_progress'
: deliveryReview || changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review'
: 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'
@@ -136,7 +139,8 @@ export class DeliveryReporter {
project: { id: project.id, name: project.name, root: project.root }, workspace: projectWorkspaceIdentity(project),
task: { id: task.id, goal: task.goal, status: task.status, instructions: task.instructions, acceptance: task.acceptance ?? [],
contract, delivery: task.delivery ?? null,
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: 'not_recorded', note: '源码和检查证据不代替业务需求验收。' },
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: requirements.status, note: '源码和检查证据不代替业务需求验收。' },
requirements,
fileResults, fileDelivery,
checkPolicy: contract.checks === 'skip' ? 'not_requested' : contract.checks,
gitOutcome: { status: !fileDelivery.newChanges && hasFileScope ? 'no_new_changes' : commits.length ? 'committed' : 'uncommitted',
@@ -199,6 +203,15 @@ export function renderDeliveryMarkdown(report) {
}
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.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
+5
View File
@@ -14,6 +14,7 @@ import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { currentBrowserVerification } from './browser/browser-manager.mjs';
import { assertBrowserResolved } from '../shared/contracts/browser.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
import { RequirementReview } from './tasks/requirement-review.mjs';
import { assertMcpResolved } from './tools/mcp-contract.mjs';
import { assertWorkersResolved, workerForProject } from '../shared/contracts/workers.mjs';
@@ -227,6 +228,7 @@ export class GitDelivery {
const browser = await currentBrowserVerification(this.store, session, inspection);
if (browser.required && browser.status !== 'passed') throw conflict('本任务已配置页面验收,请先取得当前源码与构建的实际浏览器断言通过记录。');
const taskPlan = await new TaskPlanManager(this.store).assertReady(session, { inspection });
const requirements = await new RequirementReview(this.store).assertReady(session, { inspection });
const files = await this.selectedFiles(session, project, snapshot);
const name = options.authorName ?? snapshot.config['user.name'] ?? 'Agent Workbench';
const email = options.authorEmail ?? snapshot.config['user.email'] ?? 'local@agent-workbench.invalid';
@@ -236,12 +238,14 @@ export class GitDelivery {
if (snapshot.digest !== second.digest || identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('准备提交期间工程或任务已变化,请重新预览。');
this.assertIdle(session, idleOptions); this.assertTask(session);
await new TaskPlanManager(this.store).assertReady(session, { expectedBinding: taskPlan.binding_sha256 });
await new RequirementReview(this.store).assertReady(session, { expectedBinding: requirements.binding_sha256 });
const diffArtifact = this.store.artifactStore.write(session, run, files.map(file => file.diff).join('\n'), { kind: 'delivery-diff', mediaType: 'text/plain' });
this.store.core.artifact.set(diffArtifact.id, diffArtifact);
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id, status: 'planned', createdAt: at(),
message, author, files, paths: files.map(file => file.path), snapshot, preparedBy: source, fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint,
checkJobId: check.id, checkSummary: check.results.map(value => ({ name: value.name, command: value.command, exitCode: value.exitCode, tests: value.tests, logArtifactId: value.logArtifactId })),
...(taskPlan.configured ? { taskPlanId: taskPlan.plan_id, taskPlanRevision: taskPlan.revision, taskPlanBindingSha256: taskPlan.binding_sha256 } : {}),
...(requirements.configured ? { requirementBindingSha256: requirements.binding_sha256 } : {}),
...(browser.required ? { browserJobId: browser.jobId, browserPlanId: browser.planId, browserBuildSha256: browser.buildSha256 } : {}),
protectedIndexSha256: protectedIndex(snapshot.stage, snapshot.flags, files.map(file => file.path)), diffArtifactId: diffArtifact.id,
policy: { name: 'local-reviewed-snapshot', hooks: 'disabled', signing: 'unsigned', remote: 'none',
@@ -294,6 +298,7 @@ export class GitDelivery {
}
async verifyBrowserDelivery(session, plan, inspection) {
await new RequirementReview(this.store).assertReady(session, { inspection, expectedBinding: plan.requirementBindingSha256 ?? null });
await new TaskPlanManager(this.store).assertReady(session, { inspection, expectedBinding: plan.taskPlanBindingSha256 ?? null });
assertBrowserResolved(this.store, session.projectId);
const browser = await currentBrowserVerification(this.store, session, inspection);
+190
View File
@@ -0,0 +1,190 @@
import { randomUUID } from 'node:crypto';
import { TaskPlanManager } from './task-plan-manager.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { taskContract } from '../../shared/contracts/task-control.mjs';
import { taskPlanInput, planHash, planError } from '../../shared/contracts/task-plans.mjs';
import { readText } from '../../server/files.mjs';
import { FileResults } from './file-results.mjs';
const same = (a, b) => planHash(a) === planHash(b);
const now = () => new Date().toISOString();
const checkKeys = (value, keys) => {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !keys.includes(key)))
throw planError('要求复核包含未声明字段。', 'input', 400);
};
const requiredText = (value, max) => {
if (typeof value !== 'string' || !value.trim() || value.length > max || value.includes('\0')) throw planError('请填写有效的要求或复核说明。', 'input', 400);
return value.trim();
};
export function requirementSources(task) {
return [{ kind: 'goal', id: task.id, text: task.goal, at: task.createdAt ?? null },
...(task.instructions ?? []).filter(row => row.source !== 'review-action').map(row => ({ kind: 'instruction', id: row.id, text: row.content, at: row.createdAt ?? row.at ?? null }))]
.map(row => ({ ...row, sha256: planHash({ kind: row.kind, id: row.id, text: row.text }) }));
}
function itemInput(value, sources) {
checkKeys(value, ['key', 'title', 'criterion', 'source', 'kind', 'tools', 'paths', 'checks', 'viewport_width', 'actions', 'method']);
checkKeys(value.source, ['kind', 'id', 'start', 'end']);
const original = sources.find(row => row.kind === value.source.kind && row.id === value.source.id);
const { start, end } = value.source;
if (!original || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end <= start || end > original.text.length)
throw planError('要求来源必须是当前Task用户原文的有效范围。', 'input', 400);
const method = value.method ?? 'evidence';
if (!['evidence', 'user', 'not_requested'].includes(method)) throw planError('复核方式无效。', 'input', 400);
const { source, method: ignored, ...fields } = value;
// Reuse the existing bounded evidence scopes; a statement alone never passes.
const step = taskPlanInput({ expected_revision: 0, steps: [{ ...fields, depends_on: [] }] }).steps[0];
if (method === 'not_requested' && step.kind !== 'checks') throw planError('仅检查约定可记录为未执行。', 'input', 400);
return { ...step, method, source: { ...source, quote: original.text.slice(start, end), sourceSha256: original.sha256, at: original.at } };
}
const ledgerContract = row => ({ schemaVersion: 1, kind: 'task-requirements', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
taskId: row.taskId, runId: row.runId, revision: row.revision, parentId: row.parentId, items: row.items, sources: row.sources, createdAt: row.createdAt });
const proofContract = row => ({ schemaVersion: 1, kind: 'requirement-proof', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
taskId: row.taskId, runId: row.runId, key: row.key, requirementSha256: row.requirementSha256, requirementRevision: row.requirementRevision,
evidenceId: row.evidenceId, outcome: row.outcome, sourceFingerprint: row.sourceFingerprint, status: row.status, error: row.error,
note: row.note, createdAt: row.createdAt });
// This ledger lives on the existing Task. It delegates all engineering proof
// checks to TaskPlanManager and grants no tool, command or file permissions.
export class RequirementReview {
constructor(store, { planner = new TaskPlanManager(store), redact = String } = {}) { this.store = store; this.planner = planner; this.redact = redact; }
current(session) { return this.store.owned('task', session.taskId, session.id).requirementRevisions?.at(-1) ?? null; }
verifyRecord(session, row, kind, contract) {
if (row.sessionId !== session.id || row.projectId !== session.projectId || row.taskId !== session.taskId) throw planError('要求记录不属于当前项目和Task。');
const original = this.planner.artifact(session, row.contractArtifactId, kind, row.taskId, row.runId);
if (original.artifact.sha256 !== row.contractSha256 || original.text !== JSON.stringify(contract(row))) throw planError('要求或复核记录与原工件不一致。');
}
write(session, run, row, kind, contract) {
const artifact = this.store.artifactStore.write(session, run, contract(row), { kind });
this.store.core.artifact.set(artifact.id, artifact);
return { ...row, contractArtifactId: artifact.id, contractSha256: artifact.sha256 };
}
async evidence(session, item, id, inspection) {
if (item.kind === 'results') {
const result = new FileResults(this.store).verify(session, id, { current: false });
if (result.taskId !== session.taskId || !item.paths.every(file => result.files.some(row => row.path === file)))
throw planError('成果凭据不属于当前Task或未覆盖要求文件。');
const files = result.files.filter(file => item.paths.includes(file.path));
for (const file of files) if (readText(this.store.project(session.projectId), file.path).sha256 !== file.sha256)
throw planError('当前要求的成果文件SHA已变化。', 'stale');
const artifact = this.store.owned('artifact', result.contractArtifactId, session.id);
return { kind: 'file_result', id: result.id, runId: result.runId, scope: 'current_requirement_files',
files: files.map(({ path, sha256, origin }) => ({ path, sha256, origin })),
artifacts: [{ id: artifact.id, kind: artifact.kind, runId: artifact.runId, sha256: artifact.sha256, bytes: artifact.bytes }] };
}
const outcome = await this.planner.evidence(session, item, id, { inspection });
if (item.kind === 'analysis') {
const record = this.store.owned('tool', id, session.id);
const result = JSON.parse(this.planner.artifact(session, record.resultArtifactId, 'tool-result', record.taskId, record.runId).text);
if (record.tool === 'read_file' && (!result.sha256 || readText(this.store.project(session.projectId), result.path).sha256 !== result.sha256))
throw planError('原读取对应旧文件SHA,请使用当前文件的实际读取。', 'stale');
if (record.tool === 'inspect_project' && result.sourceFingerprint !== inspection.sourceFingerprint)
throw planError('原工程观察对应旧源码输入。', 'stale');
}
return outcome;
}
save(session, input) { return this.planner.mutate(session, 'user', async () => {
checkKeys(input, ['expected_revision', 'requirements']);
const { task, run } = this.planner.task(session), previous = this.current(session), revision = previous?.revision ?? 0;
if (previous) this.verifyRecord(session, previous, 'task-requirements', ledgerContract);
if (input.expected_revision !== revision) throw planError('要求修订已变化,请刷新后保存。', 'stale');
if (revision >= 24 || !Array.isArray(input.requirements) || !input.requirements.length || input.requirements.length > 24)
throw planError('每个Task最多24项要求与24次修订。', 'input', 400);
const sources = requirementSources(task), items = input.requirements.map(value => itemInput(value, sources));
if (new Set(items.map(row => row.key)).size !== items.length || previous?.items.some(row => !items.some(item => item.key === row.key)))
throw planError('要求ID需唯一;原要求不能删除,可修订并保留原记录。', 'input', 400);
if (JSON.stringify(items).length > 24000) throw planError('要求范围过大,请缩小Task。', 'input', 400);
for (const item of items) {
if (item.method === 'not_requested' && taskContract(task).checks !== 'skip') throw planError('当前用户约定没有跳过检查,不能标为按约定未执行。');
const old = previous?.items.find(row => row.key === item.key);
const { revision: oldRevision, ...oldContent } = old ?? {};
item.revision = old && same(oldContent, item) ? oldRevision : (oldRevision ?? 0) + 1;
}
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
if (session.taskId !== task.id || session.runId !== run.id || this.current(session)?.id !== previous?.id || !same(sources, requirementSources(task)))
throw planError('保存期间原任务、来源或要求已变化。', 'stale');
const row = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
revision: revision + 1, parentId: previous?.id ?? null, items, sources, createdAt: now() }, 'task-requirements', ledgerContract);
(task.requirementRevisions ??= []).push(row);
this.store.save(session, { type: 'task.requirements_saved', detail: { id: row.id, revision: row.revision } });
return row;
}); }
async inspect(session, { candidates = false, inspection = null } = {}) {
const { task, run } = this.planner.task(session), ledger = this.current(session), sources = requirementSources(task);
const base = { configured: !!ledger, task_id: task.id, revision: ledger?.revision ?? 0, sources, items: [], all_resolved: false, binding_sha256: null,
note: '证据核对只证明所选范围;模型完成答复不等于业务验收。' };
if (!ledger) return { ...base, status: 'not_recorded', unreviewed_sources: sources.map(row => row.id) };
try { this.verifyRecord(session, ledger, 'task-requirements', ledgerContract); }
catch (error) { return { ...base, status: 'unverified', error: this.redact(error.message) }; }
const unreviewed = sources.filter(row => !ledger.sources.some(old => old.id === row.id && old.sha256 === row.sha256)).map(row => row.id);
const items = [], proofs = task.requirementProofs ?? [];
for (const item of ledger.items) {
const source = sources.find(row => row.id === item.source.id && row.kind === item.source.kind);
const proof = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item) && row.status === 'verified');
const attempt = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item));
let status = 'pending', error = null, outcome = null;
try {
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('原用户来源已变化。', 'stale');
if (item.method === 'not_requested') {
if (taskContract(task).checks !== 'skip') throw planError('当前检查约定已变化。', 'stale');
status = 'not_requested';
} else if (proof) {
this.verifyRecord(session, proof, 'requirement-proof', proofContract);
const sourceRead = item.kind === 'analysis' && this.store.core.tool.get(proof.evidenceId)?.tool === 'read_file';
if (item.kind === 'analysis' || item.method === 'user') {
inspection ??= await inspectProject(this.store.project(session.projectId));
if (!inspection.scope.complete || !sourceRead && proof.sourceFingerprint !== inspection.sourceFingerprint) throw planError('复核后源码输入已变化。', 'stale');
}
if (item.method !== 'user') {
outcome = await this.evidence(session, item, proof.evidenceId, inspection);
if (!same(outcome, proof.outcome)) throw planError('实际记录与原复核结果不一致。', 'stale');
}
status = item.method === 'user' ? 'user_confirmed' : 'evidence_verified';
} else if (attempt?.status === 'rejected') status = 'failed';
} catch (cause) { status = cause.code === 'stale' ? 'stale' : 'unverified'; error = this.redact(cause.message); }
items.push({ ...item, status, error, evidence: outcome, proof_id: proof?.id ?? null, proof_artifact_id: proof?.contractArtifactId ?? null,
user_note: status === 'user_confirmed' ? proof.note : null,
last_rejection: attempt?.status === 'rejected' ? { id: attempt.id, message: attempt.error, at: attempt.createdAt } : null,
...(candidates && item.method === 'evidence' ? { candidates: this.planner.candidates(session, item) } : {}) });
}
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('核对期间Task/Run或要求已变化。', 'stale');
const resolved = !unreviewed.length && items.every(row => ['evidence_verified', 'user_confirmed', 'not_requested'].includes(row.status));
return { ...base, items, unreviewed_sources: unreviewed, status: resolved ? 'resolved' : 'incomplete', all_resolved: resolved,
history: proofs.map(row => ({ id: row.id, key: row.key, revision: row.requirementRevision, status: row.status, error: row.error, at: row.createdAt, artifact_id: row.contractArtifactId })),
contract_artifact_id: ledger.contractArtifactId, contract_sha256: ledger.contractSha256,
binding_sha256: resolved ? planHash({ ledger: ledger.contractSha256, proofs: items.map(row => [row.key, row.proof_id, row.status, row.evidence]) }) : null };
}
verify(session, input) { return this.planner.mutate(session, 'user', async () => {
checkKeys(input, ['expected_revision', 'key', 'evidence_id', 'note']);
const { task, run } = this.planner.task(session), ledger = this.current(session);
if (!ledger || ledger.revision !== input.expected_revision) throw planError('要求修订已变化,请刷新后复核。', 'stale');
this.verifyRecord(session, ledger, 'task-requirements', ledgerContract);
const item = ledger.items.find(row => row.key === input.key);
if (!item || item.method === 'not_requested') throw planError('请选择需要复核的当前要求。');
if ((task.requirementProofs?.length ?? 0) >= 128) throw planError('复核记录已到上限,请缩小任务。');
if (item.method === 'user' ? input.evidence_id !== undefined : input.note !== undefined) throw planError('用户确认和原证据核对不能混用。', 'input', 400);
const note = item.method === 'user' ? requiredText(input.note, 1000) : null;
let outcome = null, inspection = null, error = null;
try {
const source = requirementSources(task).find(row => row.kind === item.source.kind && row.id === item.source.id);
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('用户要求来源已变化。', 'stale');
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
inspection = await inspectProject(this.store.project(session.projectId));
if (!inspection.scope.complete) throw planError('源码范围不完整,不能复核。');
if (item.method !== 'user') outcome = await this.evidence(session, item, input.evidence_id, inspection);
} catch (cause) { error = this.redact(cause.message); }
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('复核期间任务或要求已变化。', 'stale');
const proof = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
key: item.key, requirementSha256: planHash(item), requirementRevision: item.revision, evidenceId: input.evidence_id ?? null,
sourceFingerprint: inspection?.sourceFingerprint ?? null, outcome, status: error ? 'rejected' : 'verified', error, note, createdAt: now() }, 'requirement-proof', proofContract);
(task.requirementProofs ??= []).push(proof);
this.store.save(session, { type: error ? 'task.requirement_rejected' : 'task.requirement_verified', detail: { id: proof.id, key: item.key } });
return { status: error ? 'error' : 'completed', proof_id: proof.id, ...(error ? { message: error } : {}) };
}); }
async assertReady(session, { inspection = null, expectedBinding = undefined } = {}) {
const view = await this.inspect(session, { inspection });
if (view.configured && !view.all_resolved) throw planError('用户要求仍有待复核、失效或未审阅来源,请先核对要求与证据。', 'stale');
if (expectedBinding !== undefined && expectedBinding !== view.binding_sha256) throw planError('Git预览后的要求或证据已变化,请重新预览。', 'stale');
return view;
}
}
+14 -1
View File
@@ -377,7 +377,7 @@ return async (request, response) => {
}
}
if (method === 'POST' && workerForProject(store, session.projectId)
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|file-results|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
&& /^(?:mcp|engines|research|workspaces|delivery|browser|browsing|preview|task-plans|task-proofs|requirements|requirement-proofs|file-results|task-checkpoints|collaborations|evaluations)(?:\/|-|$)/.test(action)) throw workerConflict('受限子任务只开放原目标的读取、范围内改动和已审批检查;此操作请返回父项目。');
if (method === 'GET' && action === 'evaluations') return json(response,runtime.evaluationManager().view(session));
if (method === 'POST' && action === 'evaluations') {
const batch=await runtime.evaluationManager().plan(session,await body(request));
@@ -518,6 +518,19 @@ return async (request, response) => {
if (session.taskId !== taskId || session.runId !== runId) throw Object.assign(new Error('核对期间任务已变化,请刷新当前计划。'), { status: 409 });
return json(response, plan);
}
if (method === 'GET' && action === 'requirements') {
if (url.searchParams.get('taskId') !== session.taskId) throw Object.assign(new Error('所选任务已变化,请刷新要求与证据。'), { status: 409 });
return json(response, await runtime.requirementReview().inspect(session, { candidates: true }));
}
if (method === 'POST' && ['requirements', 'requirement-proofs'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
if (!taskId || !runId || taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('原任务或运行已变化,未修改其他任务要求。'), { status: 409 });
const manager = runtime.requirementReview();
const result = action === 'requirements' ? await manager.save(session, input) : await manager.verify(session, input);
const requirements = await manager.inspect(session, { candidates: true });
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('保存结果属于原任务,请刷新当前任务。'), { status: 409 });
return json(response, { session: store.publicSession(session), requirements, ...(action === 'requirement-proofs' ? { verification: result } : {}) });
}
if (method === 'GET' && action === 'file-results') return json(response, runtime.fileResults().inspect(session, { path: url.searchParams.get('path') }));
if (method === 'POST' && ['file-results', 'file-results/complete'].includes(action)) {
const { taskId, runId, ...input } = await body(request);
+16
View File
@@ -40,6 +40,7 @@ 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 { FileResults } from '../core/tasks/file-results.mjs';
import { fileResultInput, fileResultToolDefinitions } from '../shared/contracts/file-results.mjs';
import { verifiedCheck } from '../core/delivery-report.mjs';
@@ -164,6 +165,7 @@ export class Runtime {
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 };
@@ -171,6 +173,7 @@ export class Runtime {
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,
@@ -330,6 +333,7 @@ export class Runtime {
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))
@@ -350,6 +354,11 @@ export class Runtime {
}) + (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),
@@ -512,6 +521,13 @@ export class Runtime {
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;
+1 -1
View File
@@ -77,7 +77,7 @@ export function settleAppliedTask(store, session) {
}
task.delivery = { status: 'files_applied', paths: applied.map(change => change.path), at: new Date().toISOString(),
checks: contract.checks === 'skip' ? 'not_requested' : task.verification?.status ?? 'not_configured' };
session.status = contract.checks === 'required' || task.currentTaskPlanId || ['failed', 'stale', 'unknown', 'unverified'].includes(task.verification?.status) && contract.checks !== 'skip'
session.status = contract.checks === 'required' || task.currentTaskPlanId || task.requirementRevisions?.length || ['failed', 'stale', 'unknown', 'unverified'].includes(task.verification?.status) && contract.checks !== 'skip'
? 'paused' : 'completed';
if (contract.checks === 'skip') store.message(session, 'system', '文件已审查并应用:' + task.delivery.paths.join('、') + '。按照原要求未运行测试,可在文件列表打开结果。');
}
+2 -2
View File
@@ -2,8 +2,8 @@
## 本轮:要求与证据复核、单轮进展观察
- [in_progress] 核对并封存既有未提交研究;离线原字节、固定源码和索引验证后本地提交。
- [pending] 复用 Task/计划/成果凭据,落地用户来源、要求修订及当前证据复核;相关契约、HTTP、恢复与界面验证,回顾并提交。
- [complete] 核对并封存既有未提交研究;8份114222字节、63来源/14固定Git输入/6案例与索引通过,提交ce3afb2f。
- [complete] A要求复核:最终53/53及新增手机路由拒绝1/1、网页7组/Electron3组、完整构建通过;原失败/当前来源/回顾封存后本地提交。未独立发行、安装或正式升级。
- [pending] 增加单轮外显事实 shadow 观察,区分分页增长、重复读取、失败、等待和研究;不修改停止、权限或预算。固定案例及实际宿主验证,回顾并提交。
- [pending] 构建与受影响入口验收、阶段证据和文档收尾;独立发行/实际安装/正式升级未完成前只标开发切片,不冒称产品交付。
+5
View File
@@ -159,6 +159,11 @@ test('gateway never exposes management routes, arbitrary assets or unpaired proj
const result = await f.request(route, undefined, { cookie }); assert.ok(result.status >= 400, route);
assert.ok(!JSON.stringify(result.body).includes('Workbench-Token'));
}
for (const action of ['requirements', 'requirement-proofs']) {
const route = '/mobile-api/sessions/' + f.session.id + '/' + action;
assert.equal((await f.request(route, undefined, { cookie })).status, 404);
assert.equal((await f.request(route, { expected_revision: 0, note: 'attempted remote acceptance' }, { cookie })).status, 404);
}
});
test('authorized project events paginate from original seq without leaking other project events or payloads', async t => {
+21
View File
@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { fixture, launchWorkbench } from './helpers.mjs';
import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
test('requirements HTTP binds selection, enforces optimistic revisions, restores original proofs and leaves provider history untouched', async t => {
const f = fixture(t); beginPlanTask(f, '研究当前README.md,不修改。'); const read = completeRead(f), taskId = f.session.taskId, runId = f.session.runId;
const original = structuredClone(f.session.providerMessages); f.store.close();
let host = await launchWorkbench(t, f.data); const route = '/sessions/' + f.session.id;
const input = { taskId, runId, expected_revision: 0, requirements: [{ key: 'research', title: '研究原文件', criterion: '依据真实读取', kind: 'analysis', tools: ['read_file'], method: 'evidence',
source: { kind: 'goal', id: taskId, start: 0, end: 7 } }] };
await assert.rejects(host.api(route + '/requirements?taskId=wrong'), /所选任务/);
await assert.rejects(host.api(route + '/requirements', { ...input, runId: taskId }), /原任务或运行/);
const saved = await host.api(route + '/requirements', input); assert.equal(saved.requirements.items[0].status, 'pending');
await assert.rejects(host.api(route + '/requirements', input), /修订/);
const result = await host.api(route + '/requirement-proofs', { taskId, runId, expected_revision: 1, key: 'research', evidence_id: read.id });
assert.equal(result.requirements.all_resolved, true);
const before = await host.api(route + '/export'); await host.close(); host = await launchWorkbench(t, f.data);
const restored = await host.api(route + '/requirements?taskId=' + taskId); assert.equal(restored.all_resolved, true); assert.equal(restored.history.length, 1);
const after = await host.api(route + '/export'); assert.deepEqual(after.session.providerMessages, original); assert.deepEqual(before.session.providerMessages, original);
});
+172
View File
@@ -0,0 +1,172 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { fixture, compatibleFixture, call, completion, assertToolPairs } from './helpers.mjs';
import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
import { RequirementReview } from '../src/core/tasks/requirement-review.mjs';
import { TaskPlanManager } from '../src/core/tasks/task-plan-manager.mjs';
import { FileResults } from '../src/core/tasks/file-results.mjs';
import { DeliveryReporter, renderDeliveryMarkdown } from '../src/core/delivery-report.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { readText, proposeFile, applyChange } from '../src/server/files.mjs';
import { createDeliveryProject, applyDeliveryFix, deliveryGit } from './fixtures/delivery-project.mjs';
import { CheckRunner } from '../src/core/check-runner.mjs';
import { GitDelivery } from '../src/core/git-delivery.mjs';
const item = (f, fields = {}) => ({ key: 'review', title: '解释原工程', criterion: '有原读取与结论可供核对', kind: 'analysis', tools: ['read_file'], method: 'evidence',
source: { kind: 'goal', id: f.session.taskId, start: 0, end: f.store.core.task.get(f.session.taskId).goal.length }, ...fields });
const create = async (f, rows = [item(f)]) => { const manager = new RequirementReview(f.store); await manager.save(f.session, { expected_revision: 0, requirements: rows }); return manager; };
const verify = (f, manager, id, key = 'review', revision = 1) => manager.verify(f.session, { expected_revision: revision, key, evidence_id: id });
test('research evidence binds actual original bytes; model completion is not user acceptance', async t => {
const f = fixture(t); beginPlanTask(f, '只研究README.md,不修改参考文件。'); const read = completeRead(f);
const manager = await create(f); assert.equal((await manager.inspect(f.session)).items[0].status, 'pending');
assert.equal((await verify(f, manager, read.id)).status, 'completed');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.all_resolved, true);
assert.equal(f.session.changes.length, 0); assert.equal(f.store.core.check_job.size, 0);
assert.equal(view.items[0].source.quote, '只研究README.md,不修改参考文件。');
const report = await new DeliveryReporter(f.store).create(f.session);
assert.equal(report.report.requirements.items[0].status, 'evidence_verified');
assert.match(renderDeliveryMarkdown(report.report), /原目标|goal:/); assert.match(report.report.task.note, /不代替/);
});
test('same text with distinct user source instances stays distinct; an appended requirement only invalidates its own revision', async t => {
const f = fixture(t); beginPlanTask(f, '读取当前依据'); const read = completeRead(f), task = f.store.core.task.get(f.session.taskId);
task.instructions.push({ id: randomUUID(), source: 'user', content: '读取当前依据', createdAt: new Date().toISOString() });
const first = item(f), second = item(f, { key: 'second', source: { kind: 'instruction', id: task.instructions[0].id, start: 0, end: 6 } });
const manager = await create(f, [first, second]); await verify(f, manager, read.id); await verify(f, manager, read.id, 'second');
let view = await manager.inspect(f.session); assert.notEqual(view.items[0].source.sourceSha256, view.items[1].source.sourceSha256);
task.instructions.push({ id: randomUUID(), source: 'user', content: '新增要求', createdAt: new Date().toISOString() });
view = await manager.inspect(f.session); assert.equal(view.all_resolved, false); assert.equal(view.unreviewed_sources.length, 1);
assert.equal(view.items[0].status, 'evidence_verified');
await manager.save(f.session, { expected_revision: 1, requirements: [first, { ...second, criterion: '新增明确条件' }] });
view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.items[0].revision, 1);
assert.equal(view.items[1].status, 'pending'); assert.equal(view.items[1].revision, 2); assert.equal(task.requirementProofs.length, 2);
});
test('foreign project, old Task and fabricated evidence strings are rejected with preserved failed proofs', async t => {
const f = fixture(t); beginPlanTask(f); const old = completeRead(f);
f.store.core.task.get(f.session.taskId).status = 'completed';
beginPlanTask(f, '另一个任务的原目标'); const manager = await create(f);
assert.equal((await verify(f, manager, old.id)).status, 'error');
assert.equal((await verify(f, manager, 'a nonempty fabricated evidence')).status, 'error');
const foreign = fixture(t); beginPlanTask(foreign); const foreignRead = completeRead(foreign);
assert.equal((await verify(f, manager, foreignRead.id)).status, 'error');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'failed'); assert.equal(view.history.length, 3);
assert.ok(view.history.every(row => row.status === 'rejected'));
});
test('source changes invalidate prior proofs and cannot certify a read that was already stale at binding', async t => {
const f = fixture(t); beginPlanTask(f); const read = completeRead(f), manager = await create(f);
await verify(f, manager, read.id);
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nnew user content\n');
assert.equal((await manager.inspect(f.session)).items[0].status, 'stale');
assert.equal((await verify(f, manager, read.id)).status, 'error');
const current = completeRead(f); assert.equal((await verify(f, manager, current.id)).status, 'completed');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.history.length, 3);
});
test('missing or tampered artifacts never become evidence and original failures remain after recovery', async t => {
const f = fixture(t); beginPlanTask(f); const read = completeRead(f), manager = await create(f);
await verify(f, manager, read.id); const artifact = f.store.owned('artifact', read.resultArtifactId, f.session.id), original = artifact.sha256;
artifact.sha256 = '0'.repeat(64);
assert.equal((await manager.inspect(f.session)).items[0].status, 'unverified');
assert.equal((await verify(f, manager, read.id)).status, 'error');
artifact.sha256 = original;
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.history[1].status, 'rejected');
const proof = f.store.core.task.get(f.session.taskId).requirementProofs[0]; proof.requirementRevision++;
assert.equal((await manager.inspect(f.session)).items[0].status, 'unverified');
});
test('checks omitted by explicit agreement are reported as not executed and never passed', async t => {
const f = fixture(t); beginPlanTask(f, '只研究现有文件,无需测试。');
const manager = await create(f, [item(f, { kind: 'checks', tools: undefined, checks: ['test'], method: 'not_requested' })]);
let view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'not_requested'); assert.equal(view.items[0].proof_id, null);
assert.equal(f.store.core.check_job.size, 0);
f.store.core.task.get(f.session.taskId).contract.checks = 'required';
view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'stale'); assert.equal(view.all_resolved, false);
});
test('user confirmation stays separate from engineering evidence, is bounded to current inputs and cannot be silently converted', async t => {
const f = fixture(t); beginPlanTask(f); const manager = await create(f, [item(f, { method: 'user' })]);
await assert.rejects(verify(f, manager, randomUUID()), /不能混用/);
await manager.verify(f.session, { expected_revision: 1, key: 'review', note: '实际打开页面,确认中文说明与当前要求一致。' });
let view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'user_confirmed'); assert.equal(view.items[0].evidence, null);
fs.appendFileSync(path.join(f.projectRoot, 'README.md'), 'new input');
view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'stale');
});
test('existing multi-file results keep provenance and invalidate only evidence whose files changed', async t => {
const f = fixture(t); beginPlanTask(f, '核对README.md已有成果,不修改,无需测试。');
fs.writeFileSync(path.join(f.projectRoot, 'notes.md'), 'existing notes');
const results = new FileResults(f.store);
const a = results.record(f.session, { files: [{ path: 'README.md', sha256: readText(f.project, 'README.md').sha256 }], reason: '核对现有说明' }, { source: 'user' });
const b = results.record(f.session, { files: [{ path: 'notes.md', sha256: readText(f.project, 'notes.md').sha256 }], reason: '核对现有笔记' }, { source: 'user' });
const manager = await create(f, [item(f, { kind: 'results', tools: undefined, paths: ['README.md'] }), item(f, { key: 'notes', kind: 'results', tools: undefined, paths: ['notes.md'] })]);
assert.equal((await verify(f, manager, a.result_id)).status, 'completed'); assert.equal((await verify(f, manager, b.result_id, 'notes')).status, 'completed');
fs.appendFileSync(path.join(f.projectRoot, 'notes.md'), ' changed');
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.items[1].status, 'stale');
assert.equal(f.session.changes.length, 0);
});
test('unrelated additions preserve the checked file facts but remain visible as unreviewed user sources', async t => {
const f = fixture(t); beginPlanTask(f, '解释README.md'); const read = completeRead(f);
const manager = await create(f); await verify(f, manager, read.id);
fs.writeFileSync(path.join(f.projectRoot, 'unrelated.txt'), 'new unrelated input');
f.store.core.task.get(f.session.taskId).instructions.push({ id: randomUUID(), source: 'user', content: '还要研究另一文件。', createdAt: new Date().toISOString() });
const view = await manager.inspect(f.session); assert.equal(view.items[0].status, 'evidence_verified'); assert.equal(view.all_resolved, false);
assert.equal(view.unreviewed_sources.length, 1);
});
test('actual Git preview and publication recheck changed requirement bindings without touching HEAD or the owner index', async t => {
const f = fixture(t); createDeliveryProject(f); applyDeliveryFix(f); f.session.status = 'paused';
const runner = new CheckRunner(f.store), delivery = new GitDelivery(f.store); f.onCleanup(() => runner.stopAll()); f.onCleanup(() => delivery.stopAll());
const checkPlan = await runner.plan(f.session), check = await (await runner.start(f.session, checkPlan.id)).promise; assert.equal(check.status, 'passed');
const requirement = item(f, { kind: 'checks', tools: undefined, checks: ['test', 'build'] }), manager = await create(f, [requirement]);
await assert.rejects(delivery.plan(f.session), /用户要求/);
await verify(f, manager, check.id); const preview = await delivery.plan(f.session); assert.match(preview.requirementBindingSha256, /^[a-f0-9]{64}$/);
const head = deliveryGit(f, ['rev-parse', 'HEAD']), indexFile = path.join(deliveryGit(f, ['rev-parse', '--absolute-git-dir']).trim(), 'index'), index = fs.readFileSync(indexFile);
await manager.save(f.session, { expected_revision: 1, requirements: [{ ...requirement, criterion: '新条件必须重新核对当前检查' }] });
const result = await (await delivery.start(f.session, preview.id)).promise;
assert.equal(result.status, 'stale'); assert.equal(deliveryGit(f, ['rev-parse', 'HEAD']), head); assert.deepEqual(fs.readFileSync(indexFile), index);
});
test('no-test file application and manual completion keep pending user requirements for explicit review', async t => {
const f = fixture(t); beginPlanTask(f, '修改README.md,无需测试。'); const read = completeRead(f), manager = await create(f);
const change = proposeFile(f.store, f.session, { path: 'README.md', content: '# new reviewed file\n', reason: '明确修改' });
applyChange(f.store, f.session, change.change_id); assert.equal(f.session.status, 'paused');
const runtime = new Runtime(f.store, new Provider());
await assert.rejects(runtime.completeFileResults(f.session), /用户要求/);
const currentRead = completeRead(f); assert.equal((await verify(f, manager, currentRead.id)).status, 'completed');
await runtime.completeFileResults(f.session); assert.equal(f.session.status, 'completed'); assert.equal(f.store.core.check_job.size, 0);
assert.notEqual(read.id, currentRead.id);
});
test('revision races, forged source ranges, evidence fields and deletion cannot overwrite sealed requirements', async t => {
const f = fixture(t); beginPlanTask(f); const manager = await create(f);
await assert.rejects(manager.save(f.session, { expected_revision: 1, requirements: [item(f, { source: { kind: 'goal', id: randomUUID(), start: 0, end: 1 } })] }), /来源/);
await assert.rejects(manager.save(f.session, { expected_revision: 1, requirements: [item(f, { status: 'verified' })] }), /未声明/);
await assert.rejects(manager.save(f.session, { expected_revision: 1, requirements: [item(f, { key: 'different' })] }), /不能删除/);
const race = await Promise.allSettled(['first', 'second'].map(criterion => manager.save(f.session, { expected_revision: 1, requirements: [item(f, { criterion })] })));
assert.equal(race.filter(row => row.status === 'fulfilled').length, 1);
assert.equal(f.store.core.task.get(f.session.taskId).requirementRevisions.length, 2);
});
test('requirement binding prevents completion and Git acceptance after a review changes; legacy tasks stay explicit', async t => {
const f = fixture(t); beginPlanTask(f); const read = completeRead(f), manager = new RequirementReview(f.store);
assert.equal((await manager.assertReady(f.session)).configured, false);
await manager.save(f.session, { expected_revision: 0, requirements: [item(f)] });
await assert.rejects(manager.assertReady(f.session), /待复核/);
await verify(f, manager, read.id); const accepted = await manager.assertReady(f.session);
await manager.save(f.session, { expected_revision: 1, requirements: [item(f, { criterion: '新的业务要求' })] });
await assert.rejects(manager.assertReady(f.session, { expectedBinding: accepted.binding_sha256 }), /待复核|变化/);
const model = await compatibleFixture(t, () => ({ body: completion([], '所有要求均已完成。') }));
f.store.saveConfig({ mode: 'compatible', model: 'owned-claim', baseUrl: model.baseUrl });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, '', true); await runtime.active.get(f.session.id).promise;
assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'requirements_incomplete'); assert.equal(f.session.status, 'paused');
assertToolPairs(f.session.providerMessages);
});