feat: add evidence-bound task recovery checkpoints
This commit is contained in:
@@ -16,7 +16,7 @@ Agent Workbench 1.11.0 将 Claude Code 与 Cursor 的机制研究整合为独立
|
||||
|
||||
## 后续产品与能力建设
|
||||
|
||||
1.12开发源码已增加模型中心/池路由和[项目记忆](docs/PROJECT-MEMORY.md)。记忆只在来源复核、脱敏且请求预算允许时使用,可查看本次实际发送快照;正式服务与新源码的发行状态分别记录。
|
||||
1.12开发源码已增加模型中心/池路由、[项目记忆](docs/PROJECT-MEMORY.md)和[任务恢复检查点](docs/TASK-CHECKPOINTS.md)。记忆只在来源复核、脱敏且请求预算允许时使用;恢复检查点绑定完整要求和原结果,核对后显式续接同一任务。正式服务与新源码的发行状态分别记录。
|
||||
|
||||
当前Git项目可以先预览已提交版本,再创建独立目录和分支;来源已有暂存、未提交及未跟踪文件保留在原项目。子工作区有自己的项目、会话和实际执行目录,创建中断后显式核对。模型准备Git交付预览后停止请求,确认这份预览后由内核完成提交和报告。具体范围见[独立工作区](docs/WORKSPACES.md)及[1.6验收](docs/QA-1.6.md)。
|
||||
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
|
||||
## 2. 能力矩阵
|
||||
|
||||
### 1.12 开发源码(未升级正式服务)
|
||||
|
||||
- C05:项目所属记忆、来源核对/过期/归档、有界脱敏模型上下文和原发送快照已通过17项专项、桌面/390px和322项全量,见[项目记忆](PROJECT-MEMORY.md)。
|
||||
- C04/C07/C11:新增可核验Task恢复包,保存完整要求、原工具/计划/证明及未知/待审查项;显式续接保留同Task和已完成结果。12项专项和桌面/390px三组通过,最终回归另行封存,见[任务检查点](TASK-CHECKPOINTS.md)。
|
||||
- 新协议、多worker、动态Skills/MCP、桌面/手机配对和真实模型池任务继续按独立切片开发与验收,不从本地配置或夹具结果推断完成。
|
||||
|
||||
### 1.11.0 任务依赖与证据收尾(本地发行与正式升级完成)
|
||||
|
||||
- C01/C02/C07/C12:Task/Run所属的1–12步依赖计划与不可变修订,目标、条件和实际证据绑定。读取、已应用变更集、当前检查与页面结果由内核核验,模型不能直接标记完成;未核验收尾暂停原Task,续接保留原操作。
|
||||
|
||||
@@ -28,6 +28,8 @@
|
||||
|
||||
当前源码每轮在已有目标、完整协议组及当前代码选择后,以剩余预算纳入已复核项目记忆。最多8条/12000字节,内容先脱敏,明确为无额外权限的项目数据;不完整扫描、来源变化/损坏、到期和归档不参与。实际发送快照保存context-project-memory工件及消费Task/Run,context_plan记录条数/ID/SHA256,历史验证不随当前记忆变化改写。详细保存、失效和容量边界见[项目记忆契约](PROJECT-MEMORY.md);真实模型收益和新发行单独验收。
|
||||
|
||||
在完整历史/结果工件基础上,新增[任务恢复检查点](TASK-CHECKPOINTS.md)保存全部用户要求与原结果引用。恢复时重核对当前Task/Run、源码/工作区和待审查/未知项,再由原Runtime显式续接;不从摘要重新合成工具调用,也不把历史成功自动当作当前工程验证。
|
||||
|
||||
## 1.6.1:当前任务工作依据与文件分页
|
||||
|
||||
1.6.0的真实样本存在一个更细的缺口:六份小代码/测试/构建读取与其他结果属于同一较大工具组,整个组被封存,原模型从未收到这些直接读取。历史定位notice又占用8482–10700字符。1.6.1保留完整消息组契约,压紧notice中的定位元数据,并为被省略组的当前Task观察构造独立工作依据视图。
|
||||
|
||||
+3
-1
@@ -20,6 +20,8 @@ A–D分别提交和验收。A先建立注册与归属,B依赖A,C使用A的
|
||||
|
||||
项目记忆管理提交f7292a9,完成项目隔离、来源SHA256/工程指纹、显式到期/归档和扫描不完整时的unverified状态;管理专项7/7、桌面/390px和固定环境全量312/312通过。后续源码已接入模型请求:每轮复核、凭据脱敏、最多8条/12000字节、目标/代码优先和原发送快照封存;新增10项专项与桌面/390px本地HTTP流程通过,完整回归322/322通过、199份冻结输入和原TAP已封存。记忆不进入通用执行快照;源码核对不能证明用户记忆内容的业务结论正确,详见[项目记忆契约](PROJECT-MEMORY.md)。
|
||||
|
||||
后续[任务恢复检查点](TASK-CHECKPOINTS.md)源码已实现保存完整要求/原工具工件/计划与证明、复核当前源码和Git/工作区、显式同Task续接。12项专项含真实进程提交前后退出及桌面/390px三组通过,最终源码/构建334/334回归及204份输入已独立封存;新包与真实模型长任务收益尚未验收。
|
||||
|
||||
## 专业界面与操作结构
|
||||
|
||||
用户需要持续交付工程的工作空间。桌面采用坚实的工程控制台:蓝黑文字、钢灰底、清楚的实体面板和高辨识操作状态;减少小字号、低对比细线和大块无用途留白。数字只显示实际量测结果。
|
||||
@@ -128,6 +130,6 @@ REA研究、Purge策略对照与外部引擎采用同一追溯要求:具体工
|
||||
|
||||
## 下一次开发的明确起点
|
||||
|
||||
连接注册/池路由首个切片和项目记忆管理已本地提交;当前收尾已核验记忆的上下文接入。下一独立切片完善长任务检查点与恢复:从原Task目标/全部要求、不可变计划、已完成工具工件、未知副作用及待审核操作生成可核验恢复包,显式续接仍由同一Task接管,不自动重放。之后按依赖推进隔离worker、动态Skills/MCP和桌面/移动宿主。旧Provider内存连接、全部历史证据和正式4318在新候选验收前继续按现有方式运行。
|
||||
连接注册/池路由、项目记忆管理/上下文和长任务恢复检查点已通过本地验收。下一独立切片先建立版本可追踪、可启停的Skills/MCP注册与调用契约,之后推进隔离worker和桌面/移动宿主;两个worker必须绑定各自worktree和预算,父任务只归集实际结果与可审查改动。旧Provider内存连接、全部历史证据和正式4318在新候选验收前继续按现有方式运行。
|
||||
|
||||
每个切片提交均包含最终行为说明、适当检查和真实限制。A–D最终发行还须独立源码/便携、数据迁移/升级及界面验证;真实模型工程样本的失败如实保留,不以通过数量替代工程交付能力。
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# 任务恢复检查点
|
||||
|
||||
2026-10-30源码切片。正式4318继续运行已验收的1.11发行;新恢复入口尚未发布为新的不可变安装包。
|
||||
|
||||
## 用户可执行的流程
|
||||
|
||||
任务暂停或失败后,在任务记录中保存恢复检查点。检查点包含全部用户目标/追加要求/约束/验收条件、工作区和源码版本、原工具调用/参数/结果工件引用、原依赖计划/证明、待审查改动、未知结果以及最后已封存模型请求。内容保存为SHA256工件,并由SQLite记录绑定消费会话、Task和Run。
|
||||
|
||||
核对恢复条件时,工作台重新校验原恢复包、引用工件的真实字节、当前源码、Git HEAD/分支、工作区身份、任务要求和原工具/计划/提案状态。满足条件后,用户可以显式继续同一Task,创建resumeOf指向原Run的新运行。原文件、会话历史和工具状态不会被恢复包覆盖;已执行工具没有自动重放。
|
||||
|
||||
这是同一任务的受控续接和状态封存。它没有把项目复制成完整备份,也不支持把一个已完成或已经推进的任务回退到任意旧执行位置;原项目目录和原结果工件仍须存在。
|
||||
|
||||
## 拒绝和恢复边界
|
||||
|
||||
- 源码变化、扫描不完整、目标或追加要求变化、Git/工作区身份变化:保留原包,显示变化原因,不从旧位置继续。
|
||||
- 后续已经产生新Run或新Task:旧检查点保持为历史,不再次续接原位置。
|
||||
- 结果未知的工具调用:要求先核对实际副作用,不能转成已完成。
|
||||
- 待审查文件提案、Git预览、未解决变更集或工作区创建/恢复:先完成现有审查或核对。
|
||||
- 原恢复包、工具参数、结果工件或计划证明损坏/篡改:拒绝使用,不补造缺少的原记录。
|
||||
- 缺少模型凭据:检查点仍可保存、读取和核对;实际续接能否调用服务由连接层独立判断。检查点不保存或重新填入任何模型Key。
|
||||
|
||||
恢复前端的确认带原包SHA256,服务端会再次执行核对;界面显示可恢复不代替续接时的检查。控制台更新只接受当前会话/Task/Run的响应,旧项目迟到响应不会更改当前检查点界面。
|
||||
|
||||
## 完整性、预算与生命周期
|
||||
|
||||
核验是项目活动的一部分,复用TaskPlanManager的活动门控;运行、检查、Git、变更集、工作区等活动期间不能保存或核对竞争状态。宿主关闭/升级会等待已有核验完成。热升级成功会重建记忆/检查点管理器;安装失败恢复原管理器与原Provider对象。
|
||||
|
||||
原结果使用稳定ID、实际参数SHA256及结果工件SHA256;检查点仅保存引用,避免重复复制整段长日志。每Task最多30个检查点、2000项工具引用,原工具结果累计最多64MB;来源扫描沿用有界工程清单,包体仍受8MB单工件上限约束。超出边界明确拒绝,原任务和证据不删除。
|
||||
|
||||
用户要求通过Provider已知凭据脱敏后存入恢复工件,原要求SHA256用于确认任务未变化。保存不发送模型请求。进程在记录提交前退出,仅可能留下未登记的内容地址工件,不能呈现为已保存检查点;提交后退出则由SQLite重新加载原记录,不自动执行模型或工具。
|
||||
|
||||
## API和验证
|
||||
|
||||
- GET /api/sessions/:sessionId/task-checkpoints:列出当前Task的原检查点。
|
||||
- POST /api/sessions/:sessionId/task-checkpoints:要求匹配当前taskId/runId,保存稳定检查点。
|
||||
- GET /api/sessions/:sessionId/task-checkpoints/:id:复核原证据和当前条件;只读核对不请求模型。
|
||||
- POST /api/sessions/:sessionId/task-checkpoints/:id/resume:要求匹配sha256,重新核对后显式续接原Task。
|
||||
|
||||
12项专项通过,覆盖同Task续接/无重放、全部要求、来源变化、未知效果、待审查提案、工件/证明损坏、Git身份、归属/并发、SQLite重开、预算以及真实子进程在提交前/后退出。桌面/390px三组界面通过,证据.qa/task-checkpoint-ui-19c55755-cdf3-4f97-9802-421fd2460096;模型请求均为自有本地HTTP夹具。
|
||||
|
||||
最终完整源码/构建回归334/334通过,0失败/取消/跳过;204份输入前后散列一致,固定Node24.22.1/Python3.10.11/pytest8.4.2。原TAP、输入与核验器保存在.qa/task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56,TAP SHA256为e4a07d969c5f256cf1035730b9bc0763da98e93728972de16dac6649f4669ed9,摘要见[完整回归](task-checkpoint-regression.json)及[界面验证](task-checkpoint-ui-validation.json)。没有覆盖旧1.11发行证据,真实模型请求0,正式4318未重启或升级。
|
||||
|
||||
真实模型长任务成功率和新的源码/便携发行另行验收。检查点核验表示原状态完整、当前条件相容,不能代替业务完成判断。
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"success": true,
|
||||
"startedAt": "2026-10-30T10:05:05.939Z",
|
||||
"finishedAt": "2026-10-30T10:15:29.024Z",
|
||||
"node": "v24.22.1",
|
||||
"testPython": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\python-3.10\\Scripts\\python.exe",
|
||||
"exitCode": 0,
|
||||
"stats": {
|
||||
"tests": 322,
|
||||
"pass": 322,
|
||||
"fail": 0,
|
||||
"cancelled": 0,
|
||||
"skipped": 0,
|
||||
"todo": 0
|
||||
},
|
||||
"inputFiles": 199,
|
||||
"directory": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\memory-context-regression-d698ba4f-d646-4c0c-ad10-6213b24083e9",
|
||||
"inputs": {
|
||||
"path": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\memory-context-regression-d698ba4f-d646-4c0c-ad10-6213b24083e9\\inputs.json",
|
||||
"sha256": "b188d65b466d5394ae44ac458734a1b773340b5a2bd348fc1aa9ba0e2d25a831"
|
||||
},
|
||||
"log": {
|
||||
"path": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\memory-context-regression-d698ba4f-d646-4c0c-ad10-6213b24083e9\\tests.tap",
|
||||
"bytes": 86534,
|
||||
"sha256": "81a60cecb4eabb222b869ce99a2e8fbe0125a4926a1e2f37458941f108e88fbe"
|
||||
},
|
||||
"stderr": {
|
||||
"path": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\memory-context-regression-d698ba4f-d646-4c0c-ad10-6213b24083e9\\stderr.log",
|
||||
"bytes": 0,
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
},
|
||||
"realModelRequests": 0
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"success": true,
|
||||
"url": "http://127.0.0.1:58760",
|
||||
"viewportWidths": [
|
||||
1440,
|
||||
390
|
||||
],
|
||||
"assertions": [
|
||||
"source hashes remain visible and a changed file is explicitly expired with retained provenance",
|
||||
"incomplete inventory marks existing facts unverified and blocks new saves",
|
||||
"390px memory review stays within the viewport with the incomplete-scan warning visible",
|
||||
"desktop and 390px request records expose the exact memory snapshot used by one owned local HTTP request"
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"localFixtureModelRequests": 1,
|
||||
"realModelRequests": 0,
|
||||
"screenshots": [
|
||||
"desktop-expired-memory.png",
|
||||
"mobile-incomplete-memory.png",
|
||||
"desktop-sent-memory.png",
|
||||
"mobile-sent-memory.png"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"success": true,
|
||||
"startedAt": "2026-10-30T10:29:37.233Z",
|
||||
"finishedAt": "2026-10-30T10:40:46.181Z",
|
||||
"node": "v24.22.1",
|
||||
"testPython": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\dev-task-plans\\.qa\\python-3.10\\Scripts\\python.exe",
|
||||
"exitCode": 0,
|
||||
"stats": {
|
||||
"tests": 334,
|
||||
"pass": 334,
|
||||
"fail": 0,
|
||||
"cancelled": 0,
|
||||
"skipped": 0,
|
||||
"todo": 0
|
||||
},
|
||||
"inputFiles": 204,
|
||||
"directory": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56",
|
||||
"inputs": {
|
||||
"path": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56\\inputs.json",
|
||||
"sha256": "6d281585562cd7579883a02670c657d8d1eea574c5e965d5abe3e4ebd00d8484"
|
||||
},
|
||||
"log": {
|
||||
"path": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56\\tests.tap",
|
||||
"bytes": 90031,
|
||||
"sha256": "e4a07d969c5f256cf1035730b9bc0763da98e93728972de16dac6649f4669ed9"
|
||||
},
|
||||
"verifier": {
|
||||
"path": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56\\verifier.mjs",
|
||||
"sha256": "2852bb472e0b431abd5a003a770a61cd280f947a4f2f5ac311796e26ec03c0e1"
|
||||
},
|
||||
"stderr": {
|
||||
"path": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56\\stderr.log",
|
||||
"bytes": 0,
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
},
|
||||
"realModelRequests": 0
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"success": true,
|
||||
"passed": [
|
||||
"desktop saves and inspects the full original Task and tool provenance without another model request",
|
||||
"an outside source change is visible and removes the checkpoint continuation action",
|
||||
"390px explicit continuation keeps the same Task and one original read; a second resume of the old checkpoint is blocked"
|
||||
],
|
||||
"viewportWidths": [
|
||||
1440,
|
||||
390
|
||||
],
|
||||
"pageErrors": [],
|
||||
"requestFailures": [],
|
||||
"screenshots": [
|
||||
"desktop-original-checkpoint.png",
|
||||
"mobile-checkpoint-ready.png"
|
||||
],
|
||||
"localFixtureModelRequests": 3,
|
||||
"realModelRequests": 0
|
||||
}
|
||||
@@ -352,3 +352,12 @@ Claude Code 报告已验证工具输入校验、权限决定、队列并发屏
|
||||
- 修正后4组记忆界面流程通过,桌面/390px原快照已目视核对,JSON长字段可换行且对话框在视口内;最终证据.qa/project-memory-ui-22e0dcaa-b1e9-415e-b064-9f4d658cfe15。1次自有HTTP夹具请求,0真实模型请求。
|
||||
- 最终记忆专项扩为17/17:补充无效package.json时省略记忆但保留修复请求,以及memory.expired持久化失败时0发送并恢复原状态。最终源码/构建正在.qa/memory-context-regression-d698ba4f-d646-4c0c-ad10-6213b24083e9独立冻结回归,期间不改源码输入。
|
||||
- 现有长Task已有完整消息组压缩、原结果工件和Run.checkpoint;下一切片应补用户可核验的Task恢复包,而非重复制造模型摘要。包保留全部要求、原计划、工具结果SHA与未知调用,源码/要求变化必须明确显示,恢复使用显式同Task续接且不重放操作。
|
||||
|
||||
## 2026-10-30 任务恢复检查点
|
||||
|
||||
- af0a42b封存记忆上下文。新增TaskCheckpointManager复用TaskPlanManager的项目活动门控,保存原目标/全部要求、工具参数和结果工件SHA、原计划/证明、待审查/未知操作及最后已封存请求;原状态不覆盖、不自动重放。
|
||||
- 检查点确认前核对当前Task/Run、要求、源码/扫描、Git和workspace、计划/工具/提案状态。未知副作用、待审查变更集/工作区或新运行均阻止从旧检查点续接。原恢复包和依赖工件损坏会直接拒绝,不补造证据。
|
||||
- 首批10项测试通过,含真实子进程在检查点提交前/后退出;重启只保留已提交记录,原工具不重放。独立桌面/390px三组通过,证据.qa/task-checkpoint-ui-19c55755-cdf3-4f97-9802-421fd2460096,3次本地HTTP夹具请求/0真实模型请求,手机界面已目视核对。
|
||||
- 长任务恢复核验限制每Task30个检查点、2000条工具引用和64MB原结果字节;先预检体积,再核对原工件,避免长历史重复展开查找。一次不存在的task-plan-crash.test.mjs只读查询已改用rg确认task-plans.test.mjs及现有worker路径。
|
||||
- 最终12项专项和334/334完整回归通过,204份源码/构建输入一致,TAP SHA256 e4a07d969c5f256cf1035730b9bc0763da98e93728972de16dac6649f4669ed9;原始文件在.qa/task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56。冻结期间只更新文档,正式4318和真实凭据未触碰。
|
||||
- 接续恢复读取有过量输出截断,后续限定段落;一次计划补丁锚点不匹配未写入任何文件,已改用实际锚点。未将读取或补丁失败当作验证通过。
|
||||
|
||||
+2
-1
@@ -22,7 +22,8 @@
|
||||
"verify:browser-ui": "node scripts/verify-browser-ui.mjs",
|
||||
"verify:task-plans": "node scripts/verify-task-plans-ui.mjs",
|
||||
"verify:model-center": "node scripts/verify-model-center-ui.mjs",
|
||||
"verify:project-memory": "node scripts/verify-project-memory-ui.mjs"
|
||||
"verify:project-memory": "node scripts/verify-project-memory-ui.mjs",
|
||||
"verify:task-checkpoints": "node scripts/verify-task-checkpoints-ui.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/parser": "7.29.11",
|
||||
|
||||
@@ -393,3 +393,10 @@
|
||||
- 管理7项+新HTTP/恢复10项=17/17;构建通过。桌面/390px四组界面通过并目视核对:.qa/project-memory-ui-22e0dcaa-b1e9-415e-b064-9f4d658cfe15。首轮窄屏脚本未重新打开任务栏的失败保留,未用强制点击掩盖。
|
||||
- 最终全量322/322、0失败/取消/跳过;固定Node24.22.1/Python3.10.11/pytest8.4.2;199份源码与构建输入散列前后一致。原TAP与结果为.qa/memory-context-regression-d698ba4f-d646-4c0c-ad10-6213b24083e9;TAP SHA256 81a60cecb4eabb222b869ce99a2e8fbe0125a4926a1e2f37458941f108e88fbe。
|
||||
- 该全量验证使用新独立目录,没有覆盖1.11发行历史验收报告。真实模型请求0,正式4318没有重启或升级。继续下一独立Task恢复检查点切片。
|
||||
|
||||
## 任务恢复检查点切片完成
|
||||
|
||||
- 保存全部用户要求、源码/Git/workspace身份、原工具参数/结果及计划证明;恢复核对变更、未知副作用和待审查状态,确认原包SHA256后同Task新Run续接,不重放工具。
|
||||
- 12项专项覆盖真实进程提交前/后退出、原证据损坏、身份/并发/预算和恢复。桌面/390px三组通过,原图已目视核对,证据.qa/task-checkpoint-ui-19c55755-cdf3-4f97-9802-421fd2460096。
|
||||
- 最终334/334、0失败/取消/跳过,204份源码/构建输入一致;固定Node24.22.1/Python3.10.11/pytest8.4.2。原TAP与核验器在.qa/task-checkpoint-regression-40d8ec07-c24d-4439-a169-cf03bfd63a56;TAP SHA256 e4a07d969c5f256cf1035730b9bc0763da98e93728972de16dac6649f4669ed9。
|
||||
- 新报告另存docs/task-checkpoint-regression.json,旧1.11发行证据保持。真实模型0请求,正式4318不重启、不升级。接续版本化Skills/MCP切片。
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { chromium, expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench, compatibleFixture, completion, call, until } from '../tests/helpers.mjs';
|
||||
|
||||
const directory = path.resolve('.qa', 'task-checkpoint-ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
|
||||
const disposers = [], t = { after: dispose => disposers.push(dispose) }, f = fixture(t); f.store.close();
|
||||
let failing = true;
|
||||
const model = await compatibleFixture(t, (_url, _body, requests) => requests.length === 1 ? completion([call('checkpoint-ui-read', 'read_file', { path: 'README.md' })])
|
||||
: failing ? { status: 401, body: { error: { message: '独立本地HTTP故障样本。' } } } : completion([], '同一任务已从原结果继续,未重新读取文件。'));
|
||||
const host = await launchWorkbench(t, f.data); assert.notEqual(new URL(host.url).port, '4318');
|
||||
await host.api('/config', { mode: 'compatible', baseUrl: model.baseUrl, model: 'owned-checkpoint-ui', apiKey: 'owned-checkpoint-ui-key', contextLimit: 24000 });
|
||||
await host.api('/sessions/' + f.session.id + '/messages', { content: '读取README一次,保留原任务,出现本地HTTP故障后等待显式继续。' });
|
||||
await until(async () => (await host.api('/sessions/' + f.session.id)).status === 'failed');
|
||||
const before = await host.api('/sessions/' + f.session.id);
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }), pageErrors = [], requestFailures = [], passed = [];
|
||||
page.on('pageerror', error => pageErrors.push(error.message)); page.on('requestfailed', request => requestFailures.push(request.url() + ': ' + request.failure()?.errorText));
|
||||
const mark = value => { passed.push(value); console.log('PASS ' + value); };
|
||||
try {
|
||||
await page.addInitScript(({ projectId, sessionId }) => { localStorage.setItem('awb-project', projectId); localStorage.setItem('awb-session', sessionId); }, { projectId: f.project.id, sessionId: f.session.id });
|
||||
await page.goto(host.url); await expect(page.getByRole('button', { name: '查看任务记录', exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
|
||||
const panel = page.getByLabel('任务恢复检查点', { exact: true }); await expect(panel).toBeVisible();
|
||||
await panel.getByRole('button', { name: '保存恢复检查点', exact: true }).click();
|
||||
await expect(panel.locator('.checkpoint-card')).toHaveCount(1); await expect(panel).toContainText('1 项已完成工具');
|
||||
assert.equal(model.requests.length, 2);
|
||||
await panel.getByRole('button', { name: '核对恢复条件', exact: true }).click();
|
||||
await expect(panel).toContainText('当前可以续接原任务');
|
||||
await panel.getByRole('button', { name: '查看原恢复包', exact: true }).click();
|
||||
const artifact = page.getByRole('dialog', { name: '执行结果工件', exact: true });
|
||||
await expect(artifact.locator('pre')).toContainText('task-recovery-checkpoint'); await expect(artifact.locator('pre')).toContainText('resultArtifact');
|
||||
await page.screenshot({ path: path.join(directory, 'desktop-original-checkpoint.png') }); await page.keyboard.press('Escape');
|
||||
mark('desktop saves and inspects the full original Task and tool provenance without another model request');
|
||||
const filename = path.join(f.projectRoot, 'README.md'), original = fs.readFileSync(filename); fs.appendFileSync(filename, '\nOutside UI edit.\n');
|
||||
await panel.getByRole('button', { name: '核对恢复条件', exact: true }).click();
|
||||
await expect(panel).toContainText('工程源码已变化'); await expect(panel.getByRole('button', { name: '从已核对检查点继续', exact: true })).toHaveCount(0);
|
||||
assert.equal(model.requests.length, 2); mark('an outside source change is visible and removes the checkpoint continuation action');
|
||||
fs.writeFileSync(filename, original);
|
||||
await page.setViewportSize({ width: 390, height: 844 }); await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
|
||||
await panel.getByRole('button', { name: '核对恢复条件', exact: true }).click();
|
||||
await expect(panel).toContainText('当前可以续接原任务'); await panel.scrollIntoViewIfNeeded();
|
||||
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390));
|
||||
await page.screenshot({ path: path.join(directory, 'mobile-checkpoint-ready.png') });
|
||||
failing = false; await panel.getByRole('button', { name: '从已核对检查点继续', exact: true }).click();
|
||||
await until(async () => (await host.api('/sessions/' + f.session.id)).status === 'completed');
|
||||
const after = await host.api('/sessions/' + f.session.id);
|
||||
assert.equal(after.taskId, before.taskId); assert.equal(after.execution.run.resumeOf, before.runId);
|
||||
assert.equal(after.execution.progress.totalTools, 1); assert.equal(model.requests.length, 3);
|
||||
await expect(panel.locator('.checkpoint-card')).toHaveCount(1);
|
||||
await panel.getByRole('button', { name: '核对恢复条件', exact: true }).click(); await expect(panel).toContainText('已有新运行');
|
||||
mark('390px explicit continuation keeps the same Task and one original read; a second resume of the old checkpoint is blocked');
|
||||
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
|
||||
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify({ success: true, passed, viewportWidths: [1440, 390], pageErrors, requestFailures,
|
||||
screenshots: ['desktop-original-checkpoint.png', 'mobile-checkpoint-ready.png'], localFixtureModelRequests: model.requests.length, realModelRequests: 0 }, null, 2));
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: path.join(directory, 'failure.png') }).catch(() => {});
|
||||
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify({ success: false, error: error.message, passed, pageErrors, requestFailures }, null, 2)); throw error;
|
||||
} finally { console.log('EVIDENCE ' + directory); await browser.close(); for (const dispose of disposers.reverse()) await dispose(); }
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Archive, FileText, LoaderCircle, Play, RefreshCw, Save } from 'lucide-react';
|
||||
import { api } from './api';
|
||||
import type { Session, TaskCheckpoint, TaskCheckpointView } from './types';
|
||||
|
||||
export function TaskCheckpointPanel({ 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 scope = `${session.id}/${task?.id}/${run?.id}`;
|
||||
const selectedScope = useRef(scope); selectedScope.current = scope;
|
||||
const request = useRef(0);
|
||||
const [records, setRecords] = useState<TaskCheckpoint[]>([]), [view, setView] = useState<TaskCheckpointView | null>(null);
|
||||
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
|
||||
const disabled = busy || working || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
|
||||
useEffect(() => {
|
||||
let alive = true; const id = ++request.current; setRecords([]); setView(null); setWorking(false); setNotice('');
|
||||
if (task) api<TaskCheckpoint[]>(`/sessions/${session.id}/task-checkpoints`).then(values => {
|
||||
if (alive && selectedScope.current === scope && request.current === id) setRecords(values.filter(value => value.taskId === task.id));
|
||||
}).catch(error => { if (alive && selectedScope.current === scope) onError(error); });
|
||||
return () => { alive = false; request.current++; };
|
||||
}, [scope]);
|
||||
if (!task || !run) return null;
|
||||
async function save() {
|
||||
if (!task || !run) return;
|
||||
const id = ++request.current; setWorking(true); setNotice('');
|
||||
try {
|
||||
const value = await api<{ checkpoint: TaskCheckpoint; session: Session }>(`/sessions/${session.id}/task-checkpoints`, { taskId: task.id, runId: run.id });
|
||||
if (selectedScope.current === scope && request.current === id) {
|
||||
onSession(value.session); setRecords(values => [value.checkpoint, ...values]); setView(null); setNotice('恢复检查点已保存;继续前还会核对当前工程。');
|
||||
}
|
||||
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
|
||||
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
|
||||
}
|
||||
async function inspect(checkpoint: TaskCheckpoint) {
|
||||
const id = ++request.current; setWorking(true); setView(null); setNotice('');
|
||||
try { const value = await api<TaskCheckpointView>(`/sessions/${session.id}/task-checkpoints/${checkpoint.id}`);
|
||||
if (selectedScope.current === scope && request.current === id) setView(value);
|
||||
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
|
||||
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
|
||||
}
|
||||
async function resume() {
|
||||
if (!view?.resumable) return;
|
||||
const id = ++request.current; setWorking(true);
|
||||
try { const value = await api<Session>(`/sessions/${session.id}/task-checkpoints/${view.checkpoint.id}/resume`, { sha256: view.checkpoint.sha256 });
|
||||
if (selectedScope.current === scope && request.current === id) onSession(value);
|
||||
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
|
||||
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
|
||||
}
|
||||
return <section className="task-record-section task-checkpoints" aria-label="任务恢复检查点">
|
||||
<div className="record-heading"><Archive size={15} /><h3>恢复检查点</h3><span>{records.length} 个</span></div>
|
||||
<p className="record-footnote">保存完整目标、原工具结果和待处理项;续接前核对源码与任务身份。</p>
|
||||
<button type="button" className="button secondary" onClick={() => void save()} disabled={disabled}>{working ? <LoaderCircle size={13} className="spin" /> : <Save size={13} />}保存恢复检查点</button>
|
||||
{notice && <p className="record-footnote" role="status">{notice}</p>}
|
||||
{records.map(checkpoint => <article className="checkpoint-card" key={checkpoint.id}>
|
||||
<strong>{new Date(checkpoint.createdAt).toLocaleString('zh-CN')}</strong>
|
||||
<p>{checkpoint.counts.completed} 项已完成工具 · {checkpoint.counts.unknown} 项待核对 · {checkpoint.counts.pendingChanges} 项待审查</p>
|
||||
<code title={checkpoint.sha256}>SHA256 {checkpoint.sha256.slice(0, 16)}</code>
|
||||
<div className="context-actions"><button type="button" className="text-button" disabled={disabled} onClick={() => void inspect(checkpoint)}><RefreshCw size={13} />核对恢复条件</button>
|
||||
<button type="button" className="text-button" onClick={() => openArtifact(checkpoint.artifactId)}><FileText size={13} />查看原恢复包</button></div>
|
||||
</article>)}
|
||||
{view && <div className="checkpoint-assessment" role="status"><strong>{view.resumable ? '当前可以续接原任务' : '暂不能从此检查点续接'}</strong>
|
||||
{view.reasons.length > 0 && <ul>{view.reasons.map(reason => <li key={reason}>{reason}</li>)}</ul>}
|
||||
{view.resumable && <button type="button" className="button primary" disabled={disabled} onClick={() => void resume()}><Play size={13} />从已核对检查点继续</button>}
|
||||
</div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -82,3 +82,10 @@
|
||||
.context-unknown { padding: 1px 6px; border-radius: 4px; color: #805d22; background: #faf4e8; font-size: 10px; }
|
||||
@media (max-width: 1120px) { .inspector-tabs > button:not(.icon-button) { padding-left: 7px; padding-right: 7px; gap: 4px; } .task-record { padding-left: 13px; padding-right: 13px; } }
|
||||
@media (max-width: 620px) { .toolbar-actions { gap: 1px; } .toolbar-actions .icon-button { width: 24px; } .task-record { padding: 4px 16px 20px; } .record-fields { grid-template-columns: 83px minmax(0, 1fr); } .artifact-pagination .button { height: 32px; } }
|
||||
.checkpoint-card { margin-top: 12px; padding: 12px; background: var(--panel, #fff); border: 1px solid var(--border, #cbd5df); border-radius: 6px; min-width: 0; }
|
||||
.checkpoint-card strong { display: block; font-size: 12px; }
|
||||
.checkpoint-card p, .checkpoint-card code { display: block; margin-top: 6px; font-size: 11px; color: var(--muted); line-height: 1.7; overflow-wrap: anywhere; }
|
||||
.checkpoint-assessment { margin-top: 12px; padding: 12px; border: 1px solid #b9c9da; background: #f3f7fb; border-radius: 6px; font-size: 12px; line-height: 1.8; }
|
||||
.checkpoint-assessment ul { margin: 8px 0; padding-left: 18px; overflow-wrap: anywhere; }
|
||||
.checkpoint-assessment .button, .task-checkpoints > .button { margin-top: 8px; height: auto; min-height: 36px; white-space: normal; }
|
||||
@media (max-width: 620px) { .task-checkpoints .button, .task-checkpoints .text-button { min-height: 44px; } }
|
||||
|
||||
@@ -8,6 +8,7 @@ import { RequestContextPanel } from './RequestContextPanel';
|
||||
import { WorkspacePanel } from './WorkspacePanel';
|
||||
import { BrowserPanel } from './BrowserPanel';
|
||||
import { TaskPlanPanel } from './TaskPlanPanel';
|
||||
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
|
||||
import './TaskPanel.css';
|
||||
|
||||
const stopReasons: Record<string, string> = { no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
|
||||
@@ -85,6 +86,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
|
||||
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
|
||||
</section>
|
||||
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
{task && <TaskCheckpointPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
{execution?.progress.requiresVerification.length ? <section className="verification-note" role="status"><ShieldQuestion size={17} /><div><strong>{execution.progress.requiresVerification.length} 项结果需要核对</strong><p>这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。</p>{execution.progress.requiresVerification.map(tool => <code key={tool.id}>{tool.tool} · {tool.id.slice(0, 8)}</code>)}</div></section> : null}
|
||||
{task && <section className="task-record-section">
|
||||
<div className="record-heading"><h3>运行记录</h3><span>{execution?.runs.filter(item => item.taskId === task.id).length} 次</span></div>
|
||||
|
||||
@@ -81,6 +81,14 @@ export interface Usage { requests: number; inputTokens: number; outputTokens: nu
|
||||
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 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;
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { inspectProject } from '../project-inspector.mjs';
|
||||
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
|
||||
import { projectWorkspaceIdentity } from '../../shared/contracts/workspaces.mjs';
|
||||
import { planHash, taskRequirements, taskProofContract } from '../../shared/contracts/task-plans.mjs';
|
||||
import { verifyPlanEvidence } from '../context/request-plan.mjs';
|
||||
import { pendingDeliveryReview } from '../../shared/contracts/delivery-review.mjs';
|
||||
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacesResolved } from '../../shared/contracts/workspaces.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const failure = (message, status = 409) => Object.assign(new Error(message), { status });
|
||||
const identity = artifact => ({ id: artifact.id, sha256: artifact.sha256, bytes: artifact.bytes, kind: artifact.kind, taskId: artifact.taskId, runId: artifact.runId });
|
||||
export const TASK_CHECKPOINT_LIMITS = Object.freeze({ checkpoints: 30, tools: 2000, resultBytes: 64 * 1024 * 1024 });
|
||||
const counts = state => ({ tools: state.tools.length, completed: state.tools.filter(value => value.state === 'completed').length,
|
||||
unknown: state.unknown.length, pendingChanges: state.changes.filter(value => ['pending', 'conflict'].includes(value.status)).length });
|
||||
|
||||
export class TaskCheckpointManager {
|
||||
constructor(store, { taskPlans, redact = String }) { this.store = store; this.taskPlans = taskPlans; this.redact = redact; }
|
||||
|
||||
list(session) {
|
||||
return [...this.store.core.task_checkpoint.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId)
|
||||
.slice(-TASK_CHECKPOINT_LIMITS.checkpoints).reverse().map(value => structuredClone(value));
|
||||
}
|
||||
|
||||
artifact(session, id, taskId) {
|
||||
const artifact = this.store.owned('artifact', id, session.id);
|
||||
if (artifact.taskId !== taskId || this.store.owned('run', artifact.runId, session.id).taskId !== taskId) throw failure('恢复依据的原工件不属于当前任务。');
|
||||
this.store.artifactStore.readBytes(artifact);
|
||||
return artifact;
|
||||
}
|
||||
|
||||
ledger(session, task) {
|
||||
const tools = [...this.store.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === task.id);
|
||||
if (tools.length > TASK_CHECKPOINT_LIMITS.tools) throw failure('当前任务超过恢复包2000项工具引用的上限,请缩小任务范围。');
|
||||
let resultBytes = 0;
|
||||
for (const tool of tools) if (tool.resultArtifactId) {
|
||||
resultBytes += this.store.owned('artifact', tool.resultArtifactId, session.id).bytes;
|
||||
if (resultBytes > TASK_CHECKPOINT_LIMITS.resultBytes) throw failure('恢复检查点的原结果核验超过64MB上限,请缩小任务范围。');
|
||||
}
|
||||
const calls = new Map(session.providerMessages.flatMap(value => value.tool_calls ?? []).map(value => [value.id, value]));
|
||||
return tools.map(tool => {
|
||||
let resultArtifact = null;
|
||||
if (tool.resultArtifactId) resultArtifact = identity(this.artifact(session, tool.resultArtifactId, task.id));
|
||||
if (tool.state === 'completed' && !resultArtifact) throw failure('已完成工具缺少原结果工件,不能封存为可恢复依据。');
|
||||
const sourceRun = this.store.owned('run', tool.runId, session.id);
|
||||
if (sourceRun.taskId !== task.id) throw failure('工具原运行不属于当前任务。');
|
||||
const call = calls.get(tool.callId);
|
||||
if (!call || call.function.name !== tool.tool || planHash(call.function.arguments) !== tool.argsSha256) throw failure('原工具参数或调用身份已变化,不能使用恢复包。');
|
||||
return { id: tool.id, callId: tool.callId, runId: tool.runId, tool: tool.tool, argsSha256: tool.argsSha256,
|
||||
state: tool.state, requiresVerification: !!tool.requiresVerification, resultArtifact };
|
||||
});
|
||||
}
|
||||
|
||||
state(session, task) {
|
||||
const plan = task.currentTaskPlanId ? this.taskPlans.planFor(session, task.currentTaskPlanId) : null;
|
||||
const proofs = [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === task.id && value.planId === plan?.id)
|
||||
.map(proof => {
|
||||
const artifact = this.artifact(session, proof.contractArtifactId, task.id);
|
||||
if (artifact.sha256 !== proof.contractSha256 || this.store.artifactStore.read(artifact) !== JSON.stringify(taskProofContract(proof))) throw failure('步骤证明与原工件不一致,不能用作恢复依据。');
|
||||
return { id: proof.id, status: proof.status, artifact: identity(artifact) };
|
||||
});
|
||||
return JSON.parse(this.redact(JSON.stringify({ tools: this.ledger(session, task),
|
||||
plan: plan ? { id: plan.id, revision: plan.revision, contractArtifactId: plan.contractArtifactId, contractSha256: plan.contractSha256 } : null,
|
||||
proofs,
|
||||
changes: session.changes.filter(value => value.taskId === task.id || ['pending', 'conflict'].includes(value.status))
|
||||
.map(value => ({ id: value.id, path: value.path, status: value.status, changeSetId: value.changeSetId ?? null })),
|
||||
deliveryReviewId: pendingDeliveryReview(this.store, session)?.id ?? null,
|
||||
unknown: [...this.store.core.tool.values()].filter(value => value.taskId === task.id && value.requiresVerification).map(value => value.id),
|
||||
})));
|
||||
}
|
||||
|
||||
create(session) { return this.taskPlans.mutate(session, 'user', async () => {
|
||||
const { task, run } = this.taskPlans.task(session), taskId = task.id, runId = run.id;
|
||||
if (['running', 'awaiting_approval', 'stopping'].includes(session.status)) throw failure('先停止当前任务,再封存稳定的恢复检查点。');
|
||||
if (this.list(session).length >= TASK_CHECKPOINT_LIMITS.checkpoints) throw failure('当前任务已达到30个恢复检查点上限。');
|
||||
const requirements = taskRequirements(task), requirementsSha256 = planHash(requirements);
|
||||
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
|
||||
const inspection = await inspectProject(this.store.project(session.projectId));
|
||||
if (!inspection.scope.complete) throw failure('源码扫描不完整,不能保存完整恢复检查点。');
|
||||
const state = this.state(session, task);
|
||||
const lastContext = [...this.store.core.context_plan.values()].findLast(value => value.sessionId === session.id && value.taskId === task.id);
|
||||
if (lastContext) verifyPlanEvidence(this.store, session, lastContext);
|
||||
if (session.taskId !== taskId || session.runId !== runId || planHash(taskRequirements(task)) !== requirementsSha256) throw failure('保存期间任务或要求已变化,请重新核对。');
|
||||
const safeRequirements = JSON.parse(this.redact(JSON.stringify(requirements)));
|
||||
const bundle = { schemaVersion: 1, kind: 'task-recovery-checkpoint', sessionId: session.id,
|
||||
projectId: session.projectId, taskId, runId, savedAt: at(), requirements: safeRequirements, requirementsSha256,
|
||||
workspace: projectWorkspaceIdentity(this.store.project(session.projectId)), sourceFingerprint: inspection.sourceFingerprint,
|
||||
sourceScope: inspection.scope, git: { head: inspection.git.head, branch: inspection.git.branch }, state,
|
||||
lastRequest: lastContext ? { planId: lastContext.id, artifactId: lastContext.requestArtifactId, sha256: lastContext.requestSha256 } : null,
|
||||
note: '恢复包是原任务数据与结果引用,不授予权限,不重放工具,不将未知调用改为成功。' };
|
||||
const artifact = this.store.artifactStore.write(session, run, bundle, { kind: 'task-recovery-checkpoint' });
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
const record = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId, runId,
|
||||
status: 'stored', createdAt: bundle.savedAt, artifactId: artifact.id, sha256: artifact.sha256,
|
||||
sourceFingerprint: inspection.sourceFingerprint, requirementsSha256, stateSha256: planHash(state),
|
||||
counts: counts(state) };
|
||||
return this.store.putRecord('task_checkpoint', session, record, 'task.checkpoint_saved');
|
||||
}); }
|
||||
|
||||
original(session, id) {
|
||||
const record = this.store.owned('task_checkpoint', id, session.id), artifact = this.artifact(session, record.artifactId, record.taskId);
|
||||
const bundle = JSON.parse(this.store.artifactStore.read(artifact));
|
||||
if (artifact.kind !== 'task-recovery-checkpoint' || artifact.sha256 !== record.sha256 || artifact.runId !== record.runId
|
||||
|| bundle.kind !== 'task-recovery-checkpoint' || bundle.sessionId !== session.id || bundle.projectId !== session.projectId
|
||||
|| bundle.taskId !== record.taskId || bundle.runId !== record.runId || bundle.requirementsSha256 !== record.requirementsSha256
|
||||
|| bundle.sourceFingerprint !== record.sourceFingerprint || planHash(bundle.state) !== record.stateSha256
|
||||
|| planHash(counts(bundle.state)) !== planHash(record.counts)) throw failure('恢复检查点与原封存身份或内容不一致。');
|
||||
if (bundle.state.tools.length > TASK_CHECKPOINT_LIMITS.tools || bundle.state.tools.reduce((sum, tool) => sum + (tool.resultArtifact?.bytes ?? 0), 0) > TASK_CHECKPOINT_LIMITS.resultBytes) throw failure('恢复包的原工具结果范围超过核验上限。');
|
||||
for (const tool of bundle.state.tools) if (tool.resultArtifact) {
|
||||
const source = this.artifact(session, tool.resultArtifact.id, record.taskId);
|
||||
if (planHash(identity(source)) !== planHash(tool.resultArtifact)) throw failure('恢复包引用的原工具工件身份已变化。');
|
||||
}
|
||||
if (bundle.state.plan) {
|
||||
const source = this.artifact(session, bundle.state.plan.contractArtifactId, record.taskId);
|
||||
if (source.sha256 !== bundle.state.plan.contractSha256 || source.kind !== 'task-plan') throw failure('恢复包引用的原任务计划身份已变化。');
|
||||
}
|
||||
for (const proof of bundle.state.proofs) {
|
||||
const source = this.artifact(session, proof.artifact.id, record.taskId);
|
||||
if (planHash(identity(source)) !== planHash(proof.artifact)) throw failure('恢复包引用的原步骤证明身份已变化。');
|
||||
}
|
||||
if (bundle.lastRequest) {
|
||||
const plan = this.store.owned('context_plan', bundle.lastRequest.planId, session.id);
|
||||
if (plan.taskId !== record.taskId || plan.requestArtifactId !== bundle.lastRequest.artifactId || plan.requestSha256 !== bundle.lastRequest.sha256) throw failure('恢复包引用的原模型请求身份已变化。');
|
||||
verifyPlanEvidence(this.store, session, plan);
|
||||
}
|
||||
return { record, bundle };
|
||||
}
|
||||
|
||||
inspect(session, id) { return this.taskPlans.mutate(session, 'user', async () => {
|
||||
const { record, bundle } = this.original(session, id), reasons = [];
|
||||
const { task, run } = this.taskPlans.task(session);
|
||||
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
|
||||
const inspection = await inspectProject(this.store.project(session.projectId));
|
||||
if (task.id !== record.taskId) reasons.push('当前已是另一个任务,不能回退到历史任务。');
|
||||
if (run.id !== record.runId) reasons.push('这个检查点之后已有新运行,不能重复续接原位置。');
|
||||
if (planHash(taskRequirements(task)) !== record.requirementsSha256) reasons.push('任务目标或追加要求已变化。');
|
||||
if (!inspection.scope.complete || inspection.sourceFingerprint !== record.sourceFingerprint) reasons.push('工程源码已变化或扫描不完整。');
|
||||
if (inspection.git.head !== bundle.git.head || inspection.git.branch !== bundle.git.branch
|
||||
|| planHash(projectWorkspaceIdentity(this.store.project(session.projectId))) !== planHash(bundle.workspace)) reasons.push('Git或工作区身份已变化。');
|
||||
const state = this.state(session, task);
|
||||
if (planHash(state) !== record.stateSha256) reasons.push('任务计划、改动审查或原工具状态已变化。');
|
||||
if (state.unknown.length) reasons.push('存在结果未知的工具调用,须先核对实际副作用。');
|
||||
if (state.deliveryReviewId || state.changes.some(value => ['pending', 'conflict'].includes(value.status))) reasons.push('存在待审核改动或Git预览,请先处理审查。');
|
||||
try { assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true }); } catch (error) { reasons.push(error.message); }
|
||||
try { assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true }); } catch (error) { reasons.push(error.message); }
|
||||
if (!['paused', 'failed'].includes(session.status)) reasons.push('当前任务没有暂停或失败;新增工作请发送新任务。');
|
||||
return { checkpoint: structuredClone(record), integrity: 'verified', checkedAt: at(), resumable: !reasons.length, reasons,
|
||||
currentSourceFingerprint: inspection.sourceFingerprint };
|
||||
}); }
|
||||
|
||||
async resume(session, id, sha256, runtime) {
|
||||
const view = await this.inspect(session, id);
|
||||
if (sha256 !== view.checkpoint.sha256) throw failure('恢复确认已过期,请核对原检查点SHA256。');
|
||||
if (!view.resumable) throw failure('不能从此检查点续接:' + view.reasons.join(' '));
|
||||
// Existing Runtime continues the same Task with original results and fresh approvals.
|
||||
// No saved file, command, provider message or model credential is restored or replayed.
|
||||
return runtime.resume(session.id);
|
||||
}
|
||||
}
|
||||
@@ -249,6 +249,21 @@ return async (request, response) => {
|
||||
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 });
|
||||
|
||||
@@ -18,7 +18,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
const oldHandlers = server.listeners('request');
|
||||
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
|
||||
const oldStoreProperties = { ...store };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints };
|
||||
const oldUpdates = store.listeners('update');
|
||||
const closeStorage = () => store.close();
|
||||
if (oldUpdates.length > 1) throw new Error('Unexpected Store observers; preserve their ownership before upgrading.');
|
||||
@@ -28,7 +28,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
Object.setPrototypeOf(store, Store.prototype);
|
||||
Object.setPrototypeOf(provider, Provider.prototype);
|
||||
Object.setPrototypeOf(runtime, Runtime.prototype);
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null;
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null;
|
||||
store.ensureStorage();
|
||||
// A SQLite host can retain an artifact object from an earlier bundle.
|
||||
// Reopen the same blobs through the new API without mutating that object;
|
||||
|
||||
@@ -27,6 +27,7 @@ import { TaskPlanManager } from '../core/tasks/task-plan-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';
|
||||
|
||||
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
|
||||
|
||||
@@ -105,6 +106,8 @@ export class Runtime {
|
||||
}
|
||||
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
|
||||
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) }); }
|
||||
researchManager() {
|
||||
return this.research ??= new ResearchManager(this.store, { appDirectory: this.appDirectory,
|
||||
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) });
|
||||
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
||||
|
||||
export const EXECUTION_SCHEMA = 1;
|
||||
export const ACTIVE_STATES = new Set(['running', 'awaiting_approval', 'stopping']);
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory'];
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job', 'engine_job', 'browser_plan', 'browser_job', 'task_plan', 'task_proof', 'memory', 'task_checkpoint'];
|
||||
export const timestamp = () => new Date().toISOString();
|
||||
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
|
||||
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@
|
||||
1. [complete] 接续fb58a41后的项目记忆管理:项目隔离、来源/源码指纹、到期/归档、扫描不完整降级与桌面/390px界面;固定Node24/Python3.10环境全量312/312通过。
|
||||
2. [complete] f7292a9封存记忆管理和验证文档;正式4318保持不可变1.11,不重启、不读取凭据、不发真实模型请求。
|
||||
3. [complete] 已核对current记忆接入有界请求,10项新边界+原7项管理、桌面/390px原快照和最终322/322全量通过;199份输入与原TAP封存,真实模型0请求。
|
||||
4. [pending] 接续长任务压缩/恢复、隔离worker、动态Skills/MCP及桌面/移动切片,按依赖和原结果逐项验收,不把计划或夹具结果登记为真实模型交付。
|
||||
4. [complete] af0a42b封存记忆上下文。Task恢复检查点内核/API/界面、12项专项和桌面/390px三组通过;最终334/334全量、204份源码/构建输入一致和原TAP封存,真实模型0请求。
|
||||
5. [in_progress] 按依赖先开发版本可追溯、可启停的Skills/MCP注册与调用契约,复用Task/Run、权限、预算和取消;之后推进隔离worker和桌面/移动。计划或夹具结果不登记为真实模型交付。
|
||||
|
||||
## 当前执行:1.11本地交付完成,1.12-A/B/C/D进入实现与验收
|
||||
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import fs from 'node:fs';
|
||||
import { Store } from '../../src/server/store.mjs';
|
||||
import { TaskPlanManager } from '../../src/core/tasks/task-plan-manager.mjs';
|
||||
import { TaskCheckpointManager } from '../../src/core/tasks/task-checkpoint-manager.mjs';
|
||||
|
||||
const input = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
const store = new Store(input.data), session = store.session(input.sessionId);
|
||||
const manager = new TaskCheckpointManager(store, { taskPlans: new TaskPlanManager(store) });
|
||||
const put = store.putRecord.bind(store);
|
||||
store.putRecord = (kind, ...args) => {
|
||||
if (kind === 'task_checkpoint' && input.point === 'before') process.exit(71);
|
||||
const result = put(kind, ...args);
|
||||
if (kind === 'task_checkpoint' && input.point === 'after') process.exit(71);
|
||||
return result;
|
||||
};
|
||||
await manager.create(session);
|
||||
throw new Error('Declared checkpoint process exit was not reached.');
|
||||
@@ -0,0 +1,180 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fixture, compatibleFixture, completion, call, until, launchWorkbench, assertToolPairs } from './helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { proposeFile } from '../src/server/files.mjs';
|
||||
import { gitEnvironment, runGit } from '../src/core/git-process.mjs';
|
||||
|
||||
async function failedTask(t, { goal = 'Keep the original engineering goal, read README once, and continue after the fixture outage.' } = {}) {
|
||||
const f = fixture(t); let failing = true;
|
||||
const server = await compatibleFixture(t, (_url, _body, requests) => requests.length === 1
|
||||
? completion([call('checkpoint-owned-read', 'read_file', { path: 'README.md' })])
|
||||
: failing ? { status: 503, body: { error: { message: 'Owned local fixture outage.' } } } : completion([], 'Original task resumed from verified results.'));
|
||||
const provider = new Provider({ retryPolicy: { attempts: 1 } }); provider.setKey('checkpoint-owned-secret');
|
||||
f.store.saveConfig({ mode: 'compatible', model: 'owned-checkpoint-fixture', baseUrl: server.baseUrl, contextLimit: 48000 });
|
||||
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
||||
runtime.start(f.session.id, goal); await runtime.active.get(f.session.id).promise;
|
||||
assert.equal(f.session.status, 'failed'); assert.equal(server.requests.length, 2);
|
||||
return { ...f, server, provider, runtime, manager: runtime.checkpointManager(), recover: () => { failing = false; } };
|
||||
}
|
||||
|
||||
test('a checkpoint seals all task requirements and original results without a model request and explicit continuation keeps the same Task without replay', async t => {
|
||||
const goal = 'Keep every requirement🙂\n'.repeat(300) + 'Final exact requirement must remain.';
|
||||
const f = await failedTask(t, { goal });
|
||||
const task = f.store.core.task.get(f.session.taskId); task.instructions.push({ content: 'Keep the public API unchanged.', createdAt: new Date().toISOString() });
|
||||
task.constraints = ['No outside files.']; task.acceptance = ['Actual tests must pass.']; f.store.save(f.session);
|
||||
const checkpoint = await f.manager.create(f.session), original = f.manager.original(f.session, checkpoint.id).bundle;
|
||||
assert.equal(f.server.requests.length, 2); assert.equal(original.requirements.goal, goal);
|
||||
assert.equal(original.requirements.instructions[0].content, 'Keep the public API unchanged.');
|
||||
assert.deepEqual(original.requirements.constraints, ['No outside files.']); assert.deepEqual(original.requirements.acceptance, ['Actual tests must pass.']);
|
||||
assert.equal(original.state.tools.length, 1); assert.equal(original.state.tools[0].tool, 'read_file');
|
||||
assert.match(original.state.tools[0].resultArtifact.sha256, /^[a-f0-9]{64}$/);
|
||||
assert.equal((await f.manager.inspect(f.session, checkpoint.id)).resumable, true);
|
||||
const taskId = f.session.taskId, runId = f.session.runId;
|
||||
f.recover(); await f.manager.resume(f.session, checkpoint.id, checkpoint.sha256, f.runtime); await f.runtime.active.get(f.session.id).promise;
|
||||
assert.equal(f.session.status, 'completed'); assert.equal(f.session.taskId, taskId);
|
||||
assert.equal(f.store.core.run.get(f.session.runId).resumeOf, runId); assert.equal(f.server.requests.length, 3);
|
||||
assert.equal([...f.store.core.tool.values()].length, 1); assertToolPairs(f.session.providerMessages);
|
||||
assert.ok(f.server.requests.at(-1).input.messages.some(value => value.role === 'tool' && value.tool_call_id === 'checkpoint-owned-read'));
|
||||
const old = await f.manager.inspect(f.session, checkpoint.id); assert.equal(old.resumable, false); assert.match(old.reasons.join(' '), /新运行/);
|
||||
});
|
||||
|
||||
test('checkpoint sources, requirements, plan and original tool changes block continuation and leave original checkpoint bytes intact', async t => {
|
||||
const f = await failedTask(t), checkpoint = await f.manager.create(f.session);
|
||||
const artifact = f.store.core.artifact.get(checkpoint.artifactId), bytes = f.store.artifactStore.readBytes(artifact);
|
||||
const readme = path.join(f.projectRoot, 'README.md'), before = fs.readFileSync(readme);
|
||||
fs.appendFileSync(readme, '\nExternal edit.\n');
|
||||
let view = await f.manager.inspect(f.session, checkpoint.id); assert.equal(view.resumable, false); assert.match(view.reasons.join(' '), /源码/);
|
||||
await assert.rejects(f.manager.resume(f.session, checkpoint.id, checkpoint.sha256, f.runtime), /不能从此检查点/);
|
||||
fs.writeFileSync(readme, before);
|
||||
const task = f.store.core.task.get(f.session.taskId); task.constraints.push('New outside requirement.');
|
||||
view = await f.manager.inspect(f.session, checkpoint.id); assert.equal(view.resumable, false); assert.match(view.reasons.join(' '), /要求/);
|
||||
task.constraints.pop();
|
||||
await f.runtime.taskPlanner().plan(f.session, { expected_revision: 0, steps: [{ key: 'read', title: 'Read source', criterion: 'Use an actual read.', kind: 'analysis', tools: ['read_file'], depends_on: [] }] });
|
||||
view = await f.manager.inspect(f.session, checkpoint.id); assert.equal(view.resumable, false); assert.match(view.reasons.join(' '), /计划/);
|
||||
assert.deepEqual(f.store.artifactStore.readBytes(artifact), bytes); assert.equal(f.server.requests.length, 2);
|
||||
});
|
||||
|
||||
test('unknown tool effects and pending proposals stay blocked in recovery packages rather than being changed into completed work', async t => {
|
||||
const f = await failedTask(t);
|
||||
const invocation = [...f.store.core.tool.values()][0]; invocation.requiresVerification = true; invocation.state = 'unknown'; f.store.save(f.session);
|
||||
const unknown = await f.manager.create(f.session), view = await f.manager.inspect(f.session, unknown.id);
|
||||
assert.equal(unknown.counts.unknown, 1); assert.equal(view.resumable, false); assert.match(view.reasons.join(' '), /结果未知/);
|
||||
await assert.rejects(f.manager.resume(f.session, unknown.id, unknown.sha256, f.runtime), /未知/);
|
||||
invocation.requiresVerification = false; invocation.state = 'completed';
|
||||
proposeFile(f.store, f.session, { path: 'new-owned.mjs', content: 'export const value = 1;\n', explanation: 'Pending review.' });
|
||||
const pending = await f.manager.create(f.session), reviewed = await f.manager.inspect(f.session, pending.id);
|
||||
assert.equal(pending.counts.pendingChanges, 1); assert.equal(reviewed.resumable, false); assert.match(reviewed.reasons.join(' '), /待审核/);
|
||||
assert.equal(fs.existsSync(path.join(f.projectRoot, 'new-owned.mjs')), false); assert.equal(f.server.requests.length, 2);
|
||||
});
|
||||
|
||||
test('checkpoint and referenced result corruption are rejected before dispatch and historical blobs are never rebuilt', async t => {
|
||||
const f = await failedTask(t), checkpoint = await f.manager.create(f.session);
|
||||
const source = f.store.core.artifact.get([...f.store.core.tool.values()][0].resultArtifactId), filename = path.join(f.store.artifactStore.root, source.relative), bytes = fs.readFileSync(filename);
|
||||
fs.writeFileSync(filename, '{}'); await assert.rejects(f.manager.inspect(f.session, checkpoint.id), /工件校验失败/);
|
||||
assert.equal(fs.readFileSync(filename, 'utf8'), '{}'); assert.equal(f.server.requests.length, 2);
|
||||
fs.writeFileSync(filename, bytes);
|
||||
const blob = path.join(f.store.artifactStore.root, f.store.core.artifact.get(checkpoint.artifactId).relative);
|
||||
fs.writeFileSync(blob, 'corrupt checkpoint');
|
||||
await assert.rejects(f.manager.resume(f.session, checkpoint.id, checkpoint.sha256, f.runtime), /工件校验失败/);
|
||||
assert.equal(fs.readFileSync(blob, 'utf8'), 'corrupt checkpoint'); assert.equal(f.server.requests.length, 2);
|
||||
});
|
||||
|
||||
test('checkpoint ownership, exact confirmation and concurrent operations reject foreign or stale resumes', async t => {
|
||||
const f = await failedTask(t), checkpoint = await f.manager.create(f.session), otherSession = f.store.createSession(f.project.id);
|
||||
await assert.rejects(f.manager.inspect(otherSession, checkpoint.id), /不属于/);
|
||||
await assert.rejects(f.manager.resume(f.session, checkpoint.id, 'wrong hash', f.runtime), /SHA256/);
|
||||
const first = f.manager.inspect(f.session, checkpoint.id);
|
||||
await assert.rejects(f.manager.create(f.session), /正在执行/); await first;
|
||||
const source = [...f.store.core.tool.values()][0]; source.argsSha256 = '0'.repeat(64);
|
||||
await assert.rejects(f.manager.create(f.session), /原工具参数/); assert.equal(f.server.requests.length, 2);
|
||||
});
|
||||
|
||||
test('Git identity changes and altered plan proofs cannot be accepted as the sealed recovery state', async t => {
|
||||
const f = await failedTask(t), plans = f.runtime.taskPlanner();
|
||||
const plan = await plans.plan(f.session, { expected_revision: 0, steps: [{ key: 'read', title: 'Read source', criterion: 'Use the actual owned read.', kind: 'analysis', tools: ['read_file'], depends_on: [] }] });
|
||||
const proof = await plans.verify(f.session, { plan_id: plan.id, expected_revision: 1, step_key: 'read', evidence_id: [...f.store.core.tool.values()][0].id });
|
||||
assert.equal(proof.status, 'completed');
|
||||
const checkpoint = await f.manager.create(f.session);
|
||||
const initialized = await runGit(f.projectRoot, ['init', '-q']); assert.equal(initialized.ok, true);
|
||||
const view = await f.manager.inspect(f.session, checkpoint.id); assert.equal(view.resumable, false); assert.match(view.reasons.join(' '), /Git或工作区身份/);
|
||||
const record = f.store.core.task_proof.get(proof.proof_id); record.outcome = { fabricated: true };
|
||||
await assert.rejects(f.manager.inspect(f.session, checkpoint.id), /步骤证明与原工件不一致/);
|
||||
assert.equal(f.server.requests.length, 2);
|
||||
});
|
||||
|
||||
test('checkpoint records survive SQLite reopen and do not trigger automatic model or tool replay', async t => {
|
||||
const f = await failedTask(t), checkpoint = await f.manager.create(f.session), taskId = f.session.taskId;
|
||||
f.store.close(); const restored = new Store(f.data); f.onCleanup(() => restored.close());
|
||||
const provider = new Provider(); provider.setKey(''); const runtime = new Runtime(restored, provider); f.onCleanup(() => runtime.stopAll());
|
||||
const session = restored.session(f.session.id), manager = runtime.checkpointManager();
|
||||
assert.equal(session.taskId, taskId); assert.equal(manager.list(session)[0].id, checkpoint.id);
|
||||
const view = await manager.inspect(session, checkpoint.id); assert.equal(view.resumable, true);
|
||||
assert.equal(f.server.requests.length, 2); assert.equal(runtime.hasActivity(), false);
|
||||
assertToolPairs(session.providerMessages);
|
||||
});
|
||||
|
||||
test('incomplete scans and in-progress project activity refuse checkpoint creation while private credentials are redacted from saved requirements', async t => {
|
||||
const f = await failedTask(t);
|
||||
const task = f.store.core.task.get(f.session.taskId); task.instructions.push({ content: 'Secret value checkpoint-owned-secret must not be exported.', createdAt: new Date().toISOString() }); f.store.save(f.session);
|
||||
const checkpoint = await f.manager.create(f.session), original = f.manager.original(f.session, checkpoint.id).bundle;
|
||||
assert.equal(JSON.stringify(original).includes('checkpoint-owned-secret'), false); assert.match(original.requirements.instructions[0].content, /已隐藏/);
|
||||
const large = path.join(f.projectRoot, 'large-source.mjs'); fs.writeFileSync(large, Buffer.alloc(1024 * 1024 + 1));
|
||||
await assert.rejects(f.manager.create(f.session), /扫描不完整/); fs.rmSync(large);
|
||||
f.runtime.active.set('owned-project-busy', { project: f.project });
|
||||
await assert.rejects(f.manager.create(f.session), /正在执行/); f.runtime.active.delete('owned-project-busy');
|
||||
assert.equal(f.server.requests.length, 2);
|
||||
});
|
||||
|
||||
test('oversized recovery evidence is refused before reading or publishing the checkpoint', async t => {
|
||||
const f = await failedTask(t), artifact = f.store.core.artifact.get([...f.store.core.tool.values()][0].resultArtifactId), bytes = artifact.bytes;
|
||||
artifact.bytes = 64 * 1024 * 1024 + 1;
|
||||
await assert.rejects(f.manager.create(f.session), /64MB上限/);
|
||||
artifact.bytes = bytes;
|
||||
assert.equal(f.manager.list(f.session).length, 0); assert.equal(f.server.requests.length, 2);
|
||||
});
|
||||
|
||||
test('compiled checkpoint HTTP APIs bind current Task/Run, isolate sessions and only resume on an explicit matching confirmation', async t => {
|
||||
const f = fixture(t); f.store.close(); let failing = true;
|
||||
const model = await compatibleFixture(t, (_url, _body, requests) => requests.length === 1 ? completion([call('http-checkpoint-read', 'read_file', { path: 'README.md' })])
|
||||
: failing ? { status: 401, body: { error: { message: 'Owned HTTP fixture failure.' } } } : completion([], 'Recovered original HTTP Task.'));
|
||||
const host = await launchWorkbench(t, f.data);
|
||||
await host.api('/config', { mode: 'compatible', model: 'owned-http-checkpoint', baseUrl: model.baseUrl, apiKey: 'owned-http-key', contextLimit: 24000 });
|
||||
await host.api('/sessions/' + f.session.id + '/messages', { content: 'Read README once and keep the original Task.' });
|
||||
await until(async () => (await host.api('/sessions/' + f.session.id)).status === 'failed');
|
||||
const before = await host.api('/sessions/' + f.session.id), route = '/sessions/' + f.session.id + '/task-checkpoints';
|
||||
await assert.rejects(host.api(route, { taskId: before.taskId, runId: '00000000-0000-4000-8000-000000000000' }), /任务或运行已变化/);
|
||||
const saved = await host.api(route, { taskId: before.taskId, runId: before.runId });
|
||||
assert.equal((await host.api(route)).length, 1); assert.equal((await host.api(route + '/' + saved.checkpoint.id)).resumable, true);
|
||||
const other = await host.api('/sessions', { projectId: f.project.id });
|
||||
await assert.rejects(host.api('/sessions/' + other.id + '/task-checkpoints/' + saved.checkpoint.id), /不属于/);
|
||||
await assert.rejects(host.api(route + '/' + saved.checkpoint.id + '/resume', { sha256: 'stale' }), /SHA256/);
|
||||
assert.equal(model.requests.length, 2); failing = false;
|
||||
await host.api(route + '/' + saved.checkpoint.id + '/resume', { sha256: saved.checkpoint.sha256 });
|
||||
await until(async () => (await host.api('/sessions/' + f.session.id)).status === 'completed');
|
||||
const after = await host.api('/sessions/' + f.session.id);
|
||||
assert.equal(after.taskId, before.taskId); assert.equal(after.execution.run.resumeOf, before.runId); assert.equal(after.execution.progress.totalTools, 1);
|
||||
assert.equal(model.requests.length, 3); await host.close();
|
||||
});
|
||||
|
||||
for (const point of ['before', 'after']) test('actual process exit ' + point + ' checkpoint commit retains only durable records without replay', async t => {
|
||||
const f = await failedTask(t), taskId = f.session.taskId, input = path.join(f.root, 'checkpoint-crash.json');
|
||||
fs.writeFileSync(input, JSON.stringify({ data: f.data, sessionId: f.session.id, point })); f.store.close();
|
||||
const child = spawn(process.execPath, ['tests/fixtures/task-checkpoint-crash-worker.mjs', input], { cwd: process.cwd(), env: gitEnvironment(), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let output = ''; child.stdout.on('data', bytes => { output += bytes.toString('utf8'); }); child.stderr.on('data', bytes => { output += bytes.toString('utf8'); });
|
||||
const timer = setTimeout(() => child.kill(), 15000);
|
||||
const exit = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); }); clearTimeout(timer);
|
||||
assert.equal(exit, 71, output);
|
||||
const restored = new Store(f.data); f.onCleanup(() => restored.close());
|
||||
const runtime = new Runtime(restored, new Provider()); f.onCleanup(() => runtime.stopAll());
|
||||
const current = restored.session(f.session.id), records = runtime.checkpointManager().list(current);
|
||||
assert.equal(current.taskId, taskId); assert.equal(records.length, point === 'after' ? 1 : 0);
|
||||
if (records.length) assert.equal((await runtime.checkpointManager().inspect(current, records[0].id)).resumable, true);
|
||||
assert.equal(restored.core.tool.size, 1); assert.equal([...restored.core.tool.values()][0].state, 'completed');
|
||||
assert.equal(f.server.requests.length, 2); assert.equal(runtime.hasActivity(), false);
|
||||
});
|
||||
@@ -32,12 +32,18 @@ test('a live SQLite host with the actual 1.9 artifact object upgrades, keeps its
|
||||
const artifact = original.write(f.session, run, value); f.store.core.artifact.set(artifact.id, artifact); f.store.save(f.session);
|
||||
const bytes = fs.readFileSync(path.join(original.root, artifact.relative));
|
||||
const beforeSession = structuredClone(f.store.publicSession(f.session));
|
||||
context.runtime.projectMemories = { context: () => { throw new Error('Old memory context must not survive an upgrade.'); } };
|
||||
context.runtime.taskCheckpoints = { list: () => { throw new Error('Old checkpoint verifier must not survive an upgrade.'); } };
|
||||
assert.equal(typeof original.readBytes, 'undefined');
|
||||
const upgraded = installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false });
|
||||
assert.equal(upgraded.hasKey, true); assert.equal(context.provider, context.runtime.provider);
|
||||
assert.deepEqual(f.store.publicSession(f.session), beforeSession);
|
||||
assert.deepEqual(f.store.artifactStore.readBytes(artifact), bytes);
|
||||
assert.deepEqual(JSON.parse(f.store.artifactStore.read(artifact)), value);
|
||||
assert.equal(await context.runtime.memoryManager().context(f.session), null);
|
||||
const checkpoints = await fetch('http://127.0.0.1:' + context.server.address().port + '/api/sessions/' + f.session.id + '/task-checkpoints',
|
||||
{ headers: { 'X-Workbench-Token': context.token, Connection: 'close' } });
|
||||
assert.equal(checkpoints.status, 200); assert.deepEqual(await checkpoints.json(), []);
|
||||
const planned = await context.runtime.browserManager().plan(f.session, { steps: browserSteps });
|
||||
const active = await context.runtime.browserManager().start(f.session, planned.id); await active.promise;
|
||||
assert.equal(active.job.status, 'passed'); assert.equal(active.job.cleanup.exited, true);
|
||||
@@ -54,12 +60,14 @@ test('a live SQLite host with the actual 1.9 artifact object upgrades, keeps its
|
||||
|
||||
test('failed upgrade restores the original artifact object, provider and request handler', async t => {
|
||||
const { f, context } = await legacyContext(t), original = f.store.artifactStore, handlers = context.server.listeners('request');
|
||||
const runtimeProperties = { appDirectory: context.runtime.appDirectory, browser: context.runtime.browser };
|
||||
const runtimeProperties = { appDirectory: context.runtime.appDirectory, browser: context.runtime.browser,
|
||||
projectMemories: context.runtime.memoryManager(), taskCheckpoints: context.runtime.checkpointManager() };
|
||||
fs.mkdirSync(path.join(f.data, 'service-info.json'));
|
||||
assert.throws(() => installUpgrade(context, { appDirectory: workspace }));
|
||||
assert.equal(f.store.artifactStore, original); assert.equal(typeof f.store.artifactStore.readBytes, 'undefined');
|
||||
assert.deepEqual(context.server.listeners('request'), handlers); assert.equal(context.provider.hasKey(), true);
|
||||
assert.equal(context.runtime.appDirectory, runtimeProperties.appDirectory); assert.equal(context.runtime.browser, runtimeProperties.browser);
|
||||
assert.equal(context.runtime.projectMemories, runtimeProperties.projectMemories); assert.equal(context.runtime.taskCheckpoints, runtimeProperties.taskCheckpoints);
|
||||
const artifact = original.write(f.session, f.store.core.run.get(f.session.runId), { rollback: true });
|
||||
assert.deepEqual(JSON.parse(original.read(artifact)), { rollback: true });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user