diff --git a/docs/LIVE-RETEST-E-PLAN.md b/docs/LIVE-RETEST-E-PLAN.md new file mode 100644 index 00000000..62aa4e71 --- /dev/null +++ b/docs/LIVE-RETEST-E-PLAN.md @@ -0,0 +1,30 @@ +# 修复后真实交付与原版 Purge:E 批次 + +这是下一独立批次的执行约定,尚未运行。前置为 A–D 相关检查通过、来源冻结,并将同一载荷在保留原 Provider 的正式宿主或经核验的同源宿主启用。原六例、20 次请求、419,597 报告 tokens 和一次未知用量保持原结论,不续跑旧 Task,不把后续成功回填旧分母。 + +## 样本和上限 + +| 样本 | 目标 | 单样本上限 | +| --- | --- | --- | +| 新 React | 模型自行读取、修复四文件、原测试/类型检查/构建、实际桌面与窄屏操作、审查和本地 Git | 24 次实际请求、140,000 报告 tokens、10 分钟 | +| 新 Python | 模型自行完成规范化/统计/渲染,保留原测试、编译、审查和本地 Git | 同上 | +| Node AB | 同一三模块收支需求和基线,先关闭再启用原版受限模式 | 每组 24 次实际请求、105,000 报告 tokens、10 分钟 | +| Node BA | 相同基线、工具、原测试与监督规则,先开启再关闭 | 同上 | + +整个批次最多六个新样本、100 次实际请求和 700,000 报告 tokens。宿主同时核对未知消费的保守预留;未知不能当零,不能为追求通过重置累计预算。单个在途响应可能超过上限,必须保留实际超额后停止,不能通过抹掉最终消费维持名义边界。所有模型请求串行,异常请求不自动切池或重放。 + +React/Python 与四个原版对照分别报告,不计算混合通过率。模型只收一次性任务和允许路径,自己读取、分析和提出实现;监督程序仅核对并批准原检查、审查模型原提案、确认其封存批次和 Git 交付。人工续接、审批、应用和任何实现提示各自计数。不得修改测试或替模型代写源码。 + +## 同源对照 + +原版开启使用 `purge-original-restricted-v1`、Purge 1.1.78 与固定 Harness 0.2.1-rc.2。关闭组使用同一个 Harness 与工具/模型桥,完全不加载原版入口,也不追加独立提示实验段。四组使用同一模型连接/修订/协议、32K 上下文、输出余量、路径、任务、检查、驱动和预算;严格核对每次实际请求及来源身份。 + +32K 是本次明确的实验条件。D 原版 16K 在零请求时因固定指令/工具/余量不足拒绝,旧样本保持失败;不能以静默扩大旧 Task 的上下文或删减原版提示制造成功。若必须调整已配置连接的容量,先保存公开配置身份,借助正式 API 操作并记录修订,结束恢复原选择与原参数;不读取、导出或复制 Key。 + +受限原版关闭自动更新、宿主修改、原版操作工具、自动重试和继续,仍保留原版提示与内部钩子的实际装配。这个对照只回答该配置在这组工程任务上的表现,不代表上游完整默认模式或通用“破甲”收益。加载、输入、原生模块及所有进程退出证据逐组保留;独立提示实验仍使用另一个标签。 + +## 结果和退出 + +每个样本记录功能、原测试/构建、页面操作、父工程审查/Git、原暂存/未暂存保护、实际模型身份、全部请求、报告/未知消费、耗时和监督次数。先记录失败,再做独立修复;同一失败样本不通过追加隐含提示变成新成功。 + +出现来源漂移、未知操作、超过预算或原进程不能确认关闭时,停止本样本并保存结果;后续组是否仍可独立执行按剩余预算和来源一致性判断。结束核对原用户项目、所有原会话/工件及模型池选择,新增记录必须归属于本批次。没有已核对的收费明细就不编造费用或节省比例;两个顺序的四个对照样本只提供描述性结果。 diff --git a/docs/QA-ORIGINAL-PURGE-D.md b/docs/QA-ORIGINAL-PURGE-D.md new file mode 100644 index 00000000..78ed1e54 --- /dev/null +++ b/docs/QA-ORIGINAL-PURGE-D.md @@ -0,0 +1,29 @@ +# 原版 Purge 受限策略:D 生产适配验收 + +原版入口已接入实际 `ControlledDeepSeekSession` 与工作台 Task/Run/预算/审批账本;源码实现仍在验收阶段,正式宿主保持 1.24.0/PID36552 与原 Provider,本轮未使用真实 Key 或发送真实模型请求。原版效果仍未测,下一批见 [E 真实复验方案](LIVE-RETEST-E-PLAN.md)。 + +## 当前能力 + +原版 1.1.78 的 60 份原文件与 Harness 的 393 份加载/解析/原生输入分别锁定,两个原生模块及实际系统库加载保留 SHA 收据。每次运行使用独立来源副本、home 与配置;原版入口/apply 和最终提示唯一性参与核验。原始许可证、NOTICE 与署名保持。 + +独立工程提示与原版受限策略分开、均默认关闭。原版自动更新、宿主修改、原版操作工具、自动重试和继续关闭;工具、检查、写入范围、停止和累计预算由工作台最终门控。Node 权限用于固定可信输入,原生模块仍须 `allow-addons`,这不是运行任意插件的操作系统沙箱;内部 fullAccess 等钩子存在的事实不因外部门控而改写。 + +## 已完成的实际流程 + +- 生产适配原生三场景:正常完成并退出 0、模型失败不重试、宿主拒绝工具;实际原版入口、两原生模块、落盘同步与所属进程树退出均核对。 +- 宿主四场景:55,017 报告 tokens 超过 35,000 运行预算后仅一次 HTTP 并保留 503;范围外提案拒绝;在途停止留下未知消费;审批期间原版输入变化时不运行检查。 +- 停止后显式续接:新 Run 绑定同一 Task,第一次停止与未知用量原字节保持,仅新增一次 HTTP 和 168 夹具报告 tokens,没有重放旧操作。 +- 实际 Harness + 自有 HTTP 的 Chat/Responses 各五组工程链路:原九项失败与分页日志、三模块修复/完整批次、父工程九项测试/构建、审查与本地 Git、原暂存/未暂存保护。 +- 编译 React 界面 1440/390px 四组操作:区分策略、完整来源漂移拒绝、刷新保留封存计划、实际原版运行及字节一致的报告下载。四张原截图均待最终封存;已目视核对来源桌面和窄屏报告,无页面横向溢出。 + +这些是实际原生进程、编译界面和真实本地检查,但模型响应来自自有夹具。不能据此宣称真实模型自主交付或 Purge 收益通过。 + +## 缺陷、修复和原失败 + +首次原版 16K 工程在发送前拒绝:固定指令约 12,476、工具约 2,704,投影所需 15,507 大于当轮 12,352 输入预算,实际 HTTP 为零。保留原失败,原版工程另用明确 32K 配置,既有无原版 16K 验收不改标。Responses 首个所谓 32K 驱动仍给连接写死 16K,同样零请求拒绝;修正验证器后独立 32K 五组通过。 + +host 验证器原先对零请求读取不存在的 consumption,已增加必须实际派发的断言。窄屏原验证器在异步切换子会话前探测关闭按钮,后来到达的检视区挡住工具栏;现等待实际检视区,再正常关闭,不使用强制点击。第一次构建子进程误用 PATH 内 Node16,显式前置已有 Node24 后通过;没有修改系统全局 Node。 + +界面接续两次四项操作完成但 SSE 被断开,均保持为失败。实际来源/策略快照较大,反复推送整份会话触发原 2MiB 队列保护。修复为超过 64KiB 的快照只发保留游标、项目、会话和修订的变更通知,React 通过原拉取流程读取完整状态;小会话仍按原协议发送。新增多字节大来源/100 次通知积压与小会话原游标回归;修复后的四组操作通过,意外网络断开和页面错误均为零。 + +完整回归、来源封存、最终原字节核验与本地提交尚在收尾;在这些必要项完成前不将 D 标为最终完成,也不操作正式安装或开启 E 真实批次。 diff --git a/findings.md b/findings.md index 753934f3..4e86b976 100644 --- a/findings.md +++ b/findings.md @@ -1,5 +1,15 @@ # 汇总发现 +## D 生产接线(接续 1408e7a) + +生产加载进一步发现研究清单只观察 JS/JSON,未覆盖 require-builtin 与 Koffi 两个必需 .node。已用 REA inspect_pe_imports 检查:require-builtin SHA ead441d1… 静态 KERNEL32 / 延迟 node.exe;Koffi SHA eb0587c8… 静态 KERNEL32+ADVAPI32 / 延迟 NODE.EXE。固定两个原生文件,禁用原生缓存,仅允许清单内 dlopen;Koffi.load 只允许已固定 System32 库绝对路径,实际加载收据另记。静态导入表不代表操作系统全部运行依赖或原生 OS 沙箱。 + +Windows 权限问题已最小复现:同次提供父/子目录读授权,Node 24.22.1 会拒绝父目录 realpath.native;单父授权通过。收敛重复包含的授权后,原版实际完成和正常退出通过。早期 modulePath URL 构造错误、该权限错误、漏原生依赖导致关闭失败、Koffi namespace 默认导出错误均有独立原结果;没有扩大为盘根读取。三生产适配场景共四桥输入、一次正常退出0,两个失败场景被所属宿主关闭,真实供应商请求0。新增六项专项和构建通过;旧提示/桥/worker 开发回归34/34通过,之后新增代码的最终范围仍须验证。 + +EngineRunner 已把策略保存到父计划、worker 和每个 engine Run;模型桥已有 C 的实际 Provider 消费和发送前预算门控,可复用,不能另造计费链。ControlledDeepSeekSession 当前只装配独立提示段;原版需单独的完整来源契约和实际加载收据。研究适配全部在 verify-original-purge-load.mjs 的 clientFactory,尚非产品能力。原版 autoRetry/continue/自动宿主修改关闭、三项原工具由外部 facade 拒绝;其内部钩子仍存在,外部桥继续验证完整工具目录。 + +生产适配将只支持已固定且可核对的原版输入。allow-addons 不是任意原生插件的 OS 沙箱;实际原生加载还须固定来源并保留限制。A/B/C 和旧真实六例原件不修改。本轮恢复无源码变动,工作区初始干净。 + ## 真实执行修复A:原生历史来源 真实Harness验证发现第二层续接问题:应用三模块完整批次后的新Run,外层历史原样再JSON转义为单用户消息,第一次必需输入13696/12352而拒绝。已独立封存种子消息/格式与外层请求SHA,为外层计划显式预留2048原生封装容量,并使用单层文字+角色元数据;实际native请求仍独立度量,超出仍拒绝。下一轮已能在新Run检查,最后反馈12437/12352,仅差85;发现latest_results与recorded_operations重复及成功日志节选浪费,现去重并仅为失败/未知保留额外日志节选。两次真实Harness开发失败都保留,没有提高16K或替换原九测试。 @@ -875,6 +885,8 @@ B独立管线已运行,受门控的推广等待独立源码/便携/同载荷 冻结期间复核了历史UI与随包专项的收据归属:all-ui将原结果复制到版本化docs指针,并保留各自日志/独立UUID目录;随后随包环境、原生参数、等待、协议、视觉、缓存、伴随及评测验证器写各自原目录,不覆盖这些主回归docs收据。最终封存仍逐一核对原结果/日志中的显式目录和截图SHA;没有仅凭最新全局指针推断历史结果。此项为静态归属审查,不增加模型或重跑已通过的验证。 # 当前现场:两条基本操作缺口 +当前D接续首轮三项失败已读原件:host验证在零请求预算拒绝后访问不存在的consumption,不能算用量验收;原版32K配置单独验收,16K原拒绝保持。原工程固定指令12476/工具2704/投影视图15507,大于16K下12352输入预算,0HTTP;不裁剪原版提示、不扩大旧原轮。UI异步切子会话尚未完成即探测关闭按钮,后到的审查栏遮挡工具栏;验证器改为等待真实子检视区可见再关闭并核对隐藏,不强制点击或改产品布局。新增显式--context-32k,既有16K行为不变。 + 1.24接续说明:下段为1.22历史现场。当前0dc0325干净起点,正式1.23已交付;runtime完成及task-plan changes只接受本Task已应用改动。新增成果凭据必须绑定当前文件、原读取工具/工件、任务要求与来源Task/Run,不能用模型文字绕过明确修改/检查要求。沿用中文React工作台,成果核对嵌入任务和文件流程。 正式服务实际 1.22.0,URL 的旧 release 参数不代表实际版本。网页的选择文件夹按钮被 desktop 条件隐藏;选中 pelican-bicycle.html 后只有源码且无预览入口。文件包含内联 SVG/JS 动画;现有任务浏览能力要求 Vite/桌面,不适用于直接打开普通 HTML。本次用已认证的本机一层目录浏览补网页选择;HTML 以独立 loopback 源、受限静态资源和 sandbox 渲染,不把项目脚本放进工作台 API 同源。 diff --git a/progress.md b/progress.md index b9408135..7bb2b43f 100644 --- a/progress.md +++ b/progress.md @@ -1395,6 +1395,10 @@ A独立源码12批合计716/716、0失败/取消/跳过/待办;实际Electron 提交预检首次指出原TAP中的空格行,原始日志不修剪;只为本版证据TAP设binary属性后重验diff检查。532个所属暂存文件及521份证据/manifest原字节批量Git对象核对通过;四份普通Markdown仅正常CRLF→LF,封存原件不发生换行转换。 # 真实执行 B 接续:网络请求归属与重放边界 +### D生产策略当前接续 + +实际原版适配正常/失败不重试/外部门控三项原来源保持。开发宿主37f02249四项(超额/越界/在途停止/审批漂移)及原生32K工程029462c1五组通过,0真实模型。16K原版首轮0HTTP/15507所需大于12352输入预算保持为不适配,不裁剪原版固定提示。首host验证器的undefined consumption和UI异步导航等待已修正;后续UI两轮均四功能完成、但SSE断开判失败,定位大体积会话重复推送/2MiB积压保护。publisher现对超过64KiB原快照只发游标/项目/会话/修订失效通知,React按已有流程拉取完整状态;增加多字节来源/100次背压及小会话原游标回归,准备最终冻结复验。原源码/正式Provider和Key未操作,真实请求0。 + 继续沿用planning-with-files和原修复方案;未启动子代理,未操作正式宿主或Key,未发起真实模型请求。A原实现与证据保持。B相关94/94、构建、原engine-worker14/14和最终编译宿主2/2通过;原诊断9/12、编译冷却误等待14/16及0/2均保留。实现e73bca9;18份/228436字节证据SHA df97b53c80204f7f0e6b352f707ff2b345d7360ecdd0e08ac4e00c86f2462c7b离线核对通过,A原封存保持。C身份纯函数4/4后已接入实际验收器,最终停止/刷新后以Task消费为准;预算校准仍待实施。工具恢复时一次多文件读取输出截断,随后限定短段,截断内容不作完整审查结论。 C最终接续:预算专项7/7、最终编译通过;新UI独立目录model-budget-ui-7c0de90d-1afd-4165-911e-e949b60b7d30两视口通过并已目视回看原图。原label失败保留,不改产品。Chat16K独立目录controlled-context-fe746aa6-377a-40be-945d-1a849ad675e2五组通过;Responses和最终15文件相关回归运行中。B/原六例离线核验已通过,A离线核验运行中。未使用真实Key、未改正式宿主、未加载原版Purge。 diff --git a/scripts/build-original-purge-lock.mjs b/scripts/build-original-purge-lock.mjs new file mode 100644 index 00000000..f027d3ea --- /dev/null +++ b/scripts/build-original-purge-lock.mjs @@ -0,0 +1,46 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {createHash} from 'node:crypto'; + +// Development-only provenance recipe. Runtime code imports the resulting JSON; +// it neither trusts the QA directory nor learns new executable inputs on launch. +const evidence='docs/original-purge-load-evidence',raw=fs.readFileSync(path.join(evidence,'manifest.json')); +const sha=bytes=>createHash('sha256').update(bytes).digest('hex'); +assert.equal(sha(raw),'acabdce397139dcd59cbe7f66229a1353d4f95a5ceb7a555977e544b17ea1066'); +const manifest=JSON.parse(raw),root=process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT; +assert.ok(root&&path.isAbsolute(root)); +const prefix=path.resolve(root)+path.sep,files=new Map(); +const identify=file=>{const raw=fs.readFileSync(file);return {relative:path.relative(root,file).replaceAll('\\','/'),bytes:raw.length,sha256:sha(raw)};}; +for(const input of manifest.loadedModuleInputs.filter(input=>input.path.startsWith(prefix))){ + assert.equal(sha(fs.readFileSync(path.join(evidence,input.snapshot))),input.sha256); + const identity=identify(input.path);assert.equal(identity.sha256,input.sha256);files.set(identity.relative,identity); + // Node package resolution reads these metadata before source loading. + for(let parent=path.dirname(input.path);parent.startsWith(prefix)||parent===root;parent=path.dirname(parent)){ + const file=path.join(parent,'package.json');if(fs.existsSync(file)){const item=identify(file);files.set(item.relative,item);} + if(parent===root)break; + } +} +for(const relative of ['packages/bundle/sdk-minimal/cordis.patch.yml','pnpm-lock.yaml']){ + const input=identify(path.join(root,relative));files.set(relative,input); +} +const nativePackage='node_modules/.pnpm/node-addon-require-builtin-win32-x64-msvc@0.1.9/node_modules/node-addon-require-builtin-win32-x64-msvc'; +const native=identify(path.join(root,nativePackage,'prebuilt/win32-x64-msvc-napi-v9.node')); +assert.equal(native.sha256,'ead441d11202126827a789a7eb88e79abe8f7f374b16e7273c4244225c8d6c2b'); +for(const relative of ['prebuilds.json','prebuilt/win32-x64-msvc-napi-v9.node']){ + const input=identify(path.join(root,nativePackage,relative));files.set(input.relative,input); +} +const koffi=identify(path.join(root,'node_modules/.pnpm/@koromix+koffi-win32-x64@3.1.1/node_modules/@koromix/koffi-win32-x64/win32_x64/koffi.node')); +assert.equal(koffi.sha256,'eb0587c804bb76262968bf83028528da4dc2d4322f558845cce205c709e2ba20');files.set(koffi.relative,koffi); +const upstream=manifest.upstreamInputs.map(({relative,bytes,sha256,snapshot})=>{ + assert.equal(sha(fs.readFileSync(path.join(evidence,snapshot))),sha256);return {relative,bytes,sha256}; +}).sort((a,b)=>a.relative.localeCompare(b.relative,'en')); +const lock={schemaVersion:1,purgeVersion:'1.1.78',harnessVersion:'0.2.1-rc.2', + provenance:{manifestSha256:sha(raw),sourceCommit:manifest.sourceCommit,scope:'Observed JS/JSON plus resolution metadata and explicit native require-builtin input.', + nativePeEvidenceIds:['ev_4a114ba373a5039c34e7fcdad6b9202b42d00f16cd4ae6d80304feb4d93cc19c','ev_b9670d77723678e6c17415368494a06583872fe1e41bd739d795c0c6a20ddca2']}, + original:upstream,harness:[...files.values()].sort((a,b)=>a.relative.localeCompare(b.relative,'en')), + nativeAddons:[{...native,staticImports:['KERNEL32.dll'],staticDelayImports:['node.exe']}, + {...koffi,staticImports:['KERNEL32.dll','ADVAPI32.dll'],staticDelayImports:['NODE.EXE']}]}; +const output=process.argv[2]??'src/core/engines/original-purge-lock.json';assert.equal(fs.existsSync(output),false); +fs.writeFileSync(output,JSON.stringify(lock,null,2)+'\n',{flag:'wx'}); +console.log(JSON.stringify({output,original:lock.original.length,harness:lock.harness.length,sha256:sha(fs.readFileSync(output))})); diff --git a/scripts/upgrade-running.mjs b/scripts/upgrade-running.mjs index 2deb1113..e9198c91 100644 --- a/scripts/upgrade-running.mjs +++ b/scripts/upgrade-running.mjs @@ -99,7 +99,9 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo if (!candidates.length) throw new Error('The existing server module is missing from inspector metadata.'); for (const script of candidates) { const { scriptSource } = await protocol.send('Debugger.getScriptSource', { scriptId: script.scriptId }); - const locations = scriptSource.split('\n').flatMap((line, index) => line.includes('const url = new URL(request.url') ? [index] : []); + // Bundled transport libraries can parse request.url too. Select the + // actual loopback handler with its local base and observed port binding. + const locations = scriptSource.split('\n').flatMap((line, index) => /const url = new URL\(request\.url,\s*["']http:\/\/127\.0\.0\.1:["']\s*\+\s*actualPort\d*\)/.test(line) ? [index] : []); if (locations.length !== 1) throw new Error('The existing request handler could not be identified uniquely.'); breakpoints.push((await protocol.send('Debugger.setBreakpoint', { location: { scriptId: script.scriptId, lineNumber: locations[0] } })).breakpointId); } diff --git a/scripts/verify-controlled-projects.mjs b/scripts/verify-controlled-projects.mjs index b81f1d9d..c96e02d8 100644 --- a/scripts/verify-controlled-projects.mjs +++ b/scripts/verify-controlled-projects.mjs @@ -9,7 +9,7 @@ import { Runtime } from '../src/server/runtime.mjs'; import { EngineRunner } from '../src/core/engines/engine-runner.mjs'; import { resolveControlledInstallation } from '../src/core/engines/controlled-installation.mjs'; import { originalEngineRun, verifyEngineModelInput } from '../src/shared/contracts/engine-execution.mjs'; -import { resolvePurgeSource, assertPurgeModelInput, nativeSystemTexts, PURGE_DEFAULT_PROMPT } from '../src/core/engines/purge-strategy.mjs'; +import { resolvePurgeSource, resolveOriginalPurgeSource, ORIGINAL_PURGE_KIND, assertPurgeModelInput, nativeSystemTexts, PURGE_DEFAULT_PROMPT } from '../src/core/engines/purge-strategy.mjs'; import { deliveryGit as git, writeDeliveryFile as write } from '../tests/fixtures/delivery-project.mjs'; import { ownerBytes } from '../tests/fixtures/workers-project.mjs'; import { desktopProjectQa } from './desktop-project-qa.mjs'; @@ -18,12 +18,15 @@ import { responsesEngineeringHttp } from '../tests/fixtures/responses-engineerin import { nativeContextSpecification } from '../tests/fixtures/native-context-project.mjs'; const args = process.argv.slice(2); -assert.ok(args.every(value => ['--help', '--purge-comparison', '--desktop', '--responses', '--context-16k'].includes(value)), 'Unknown option; use --help.'); +assert.ok(args.every(value => ['--help', '--purge-comparison', '--desktop', '--responses', '--context-16k','--context-32k','--original-purge'].includes(value)), 'Unknown option; use --help.'); if (args.includes('--help')) { - console.log('node scripts/verify-controlled-projects.mjs [--purge-comparison | --desktop | --context-16k] [--responses] — actual pinned Harness and owned HTTP model fixture; default verifies Node/React/Python with approvals, Edge and Git. --context-16k uses a new copy of the sealed three-module/nine-test pilot, original failure/log paging and a complete reviewed batch at 16K. --responses uses actual Responses SSE and ModelHub routing. Set AGENT_WORKBENCH_DEEPSEEK_ROOT and AGENT_WORKBENCH_TEST_PYTHON; context mode needs no Python. No configured-model requests.'); process.exit(0); + console.log('node scripts/verify-controlled-projects.mjs [--purge-comparison | --desktop | --context-16k | --context-32k] [--responses] [--original-purge] — actual pinned Harness and owned HTTP model fixture; default verifies Node/React/Python with approvals, Edge and Git. Context modes use a new copy of the sealed three-module/nine-test pilot, original failure/log paging and a complete reviewed batch at the explicit limit. Original Purge is separate from the independent prompt and its fixed instructions need the 32K profile. --responses uses actual Responses SSE and ModelHub routing. Set AGENT_WORKBENCH_DEEPSEEK_ROOT and AGENT_WORKBENCH_TEST_PYTHON; context mode needs no Python. No configured-model requests.'); process.exit(0); } const comparisonMode = args.includes('--purge-comparison'), desktopMode = args.includes('--desktop'); -const contextMode = args.includes('--context-16k');assert.ok(!contextMode || !comparisonMode && !desktopMode, '16K bridge acceptance is a separate run.'); +assert.ok(!(args.includes('--context-16k')&&args.includes('--context-32k')),'Choose one explicit native context limit.'); +const contextMode = args.includes('--context-16k')||args.includes('--context-32k');assert.ok(!contextMode || !comparisonMode && !desktopMode, 'Native context acceptance is a separate run.'); +const contextLimit=args.includes('--context-32k')?32000:16000; +const originalPurgeMode=args.includes('--original-purge');assert.ok(!originalPurgeMode||contextMode,'Original Purge engineering acceptance uses a separate owned context case.'); const responsesMode = args.includes('--responses'); assert.ok(!responsesMode || !comparisonMode, 'Protocol acceptance and Purge comparison remain separate.'); assert.ok(!comparisonMode || !desktopMode, 'Desktop engineering and prompt comparison are separate acceptance runs.'); const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version; @@ -31,6 +34,9 @@ const directory = path.resolve('.qa', (contextMode ? 'controlled-context-' : des const hash = bytes => createHash('sha256').update(bytes).digest('hex'); const installation = resolveControlledInstallation(process.cwd(), process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT); assert.equal(installation.controlledStatus, 'available', installation.message); +const originalSource=originalPurgeMode?resolveOriginalPurgeSource(process.cwd(),process.env.AGENT_WORKBENCH_PURGE_178_ROOT,installation):null; +if(originalSource)assert.equal(originalSource.status,'available',originalSource.message); +const originalStrategy=originalSource?{kind:ORIGINAL_PURGE_KIND,root:originalSource.root,sourceSha256:originalSource.sourceSha256,runtimeSha256:originalSource.runtimeSha256,prompt:PURGE_DEFAULT_PROMPT}:null; const python = process.env.AGENT_WORKBENCH_TEST_PYTHON; if (!comparisonMode && !contextMode) assert.ok(python && path.isAbsolute(python) && fs.existsSync(python), 'Provide the existing isolated Python 3.10+ interpreter.'); const sources = comparisonMode ? ['1.1.78', '1.1.81'].map((expected, index) => { @@ -111,12 +117,12 @@ async function runSample(kind, { sampleName = kind, strategy = null, comparison return { choices: [{ message: { role: 'assistant', content: calls.length ? '' : 'Owned native run complete; host proof is still required.', ...(calls.length ? { tool_calls: calls } : {}) }, finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 123, completion_tokens: 45, total_tokens: 168 } }; }); - f.store.saveConfig({ mode: 'compatible', model: 'owned-controlled-engineering', baseUrl: model.baseUrl, contextLimit: contextMode ? 16000 : 64000, + f.store.saveConfig({ mode: 'compatible', model: 'owned-controlled-engineering', baseUrl: model.baseUrl, contextLimit: contextMode ? contextLimit : 64000, ...(contextMode ? {maxOutputTokens:2048} : {}) }); const provider = new Provider(); provider.setKey('self-owned-controlled-model-fixture'); if (responsesMode) { const hub = provider.modelHub(f.store), connection = hub.upsert({ name: 'Owned Responses engineering', protocol: 'responses', model: 'owned-controlled-engineering', baseUrl: model.baseUrl, - requiresKey: false, contextLimit: contextMode ? 16000 : 64000, ...(contextMode ? {maxOutputTokens:2048} : {}), streaming: true, capabilityDeclarations: { streaming: 'supported' } }); + requiresKey: false, contextLimit: contextMode ? contextLimit : 64000, ...(contextMode ? {maxOutputTokens:2048} : {}), streaming: true, capabilityDeclarations: { streaming: 'supported' } }); hub.select({ type: 'connection', id: connection.id }); } runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll()); @@ -166,10 +172,17 @@ async function runSample(kind, { sampleName = kind, strategy = null, comparison const engineRuns = [...f.store.core.engine_run.values()].filter(job => job.taskId === child.taskId), childSession = f.store.session(child.sessionId); for (const job of engineRuns) { originalEngineRun(f.store, childSession, job); assert.equal(job.status, 'completed', job.error); assert.equal(job.native.cleanup.treeConfirmed, true); - assert.equal(job.native.stderr, ''); assert.equal(job.native.activity.endEvents[0].data.reason.kind, 'completed'); + if(originalPurgeMode){ + const warning='(node:'+job.native.process.pid+') [PERM0001] SecurityWarning: The flag --allow-addons must be used with extreme caution. It could invalidate the permission model.\n(Use `node --trace-warnings ...` to show where the warning was created)\n'; + const expected=warning+['package.json','lib/index.js'].map(file=>'AWB_MODULE_REFUSED '+path.join(installation.root,'packages/context/agent-instructions',file)+'\n').join(''); + assert.equal(job.native.stderr,expected);assert.equal(job.native.originalPurge.readiness.originalApplyCalled,true); + assert.equal(job.native.originalPurge.nativeLoads.length,2);assert.ok(job.native.originalPurge.durabilityReceipts.length>0); + }else assert.equal(job.native.stderr, ''); assert.equal(job.native.activity.endEvents[0].data.reason.kind, 'completed'); for (const request of job.requests) { const saved = verifyEngineModelInput(f.store, childSession, job, request); - if (strategy) { assertPurgeModelInput(saved.native, job.installation.strategy); assert.equal(job.native.readiness.promptExperimentSha256, job.installation.strategy.sha256); } + if (strategy) { assertPurgeModelInput(saved.native, job.installation.strategy); + if(originalPurgeMode)assert.equal(job.native.originalPurge.strategySha256,job.installation.strategy.sha256); + else assert.equal(job.native.readiness.promptExperimentSha256, job.installation.strategy.sha256); } else assert.ok(nativeSystemTexts(saved.native).every(text => !text.includes('[Agent Workbench engineering prompt experiment]'))); } } @@ -190,7 +203,7 @@ async function runSample(kind, { sampleName = kind, strategy = null, comparison const failed=childChecks.find(job=>job.status==='failed'),log=f.store.core.artifact.get(failed.results[0].logArtifactId); assert.ok(f.store.artifactStore.read(log).includes('fail 9'));assert.ok(engineRuns.some(job=>job.calls.some(call=>call.name==='read_artifact'))); assert.ok(engineRuns.some(job=>job.calls.some(call=>call.name==='prepare_change_set')));assert.ok(engineRuns.every(job=>!job.inputRejections?.length)); - mark('16K: original nine failures and paged log survive verified native compaction; all three proposals form one reviewed batch without replay'); + mark(contextLimit/1000+'K: original nine failures and paged log survive verified native compaction; all three proposals form one reviewed batch without replay'); } await (await manager.collect(f.session, group.id, group.fingerprint)).promise; assert.equal(group.status, 'collected', group.summary); const collection = await manager.readCollection(f.session, group); assert.deepEqual(collection.conflicts, []); assert.deepEqual(collection.paths, writable); @@ -272,9 +285,9 @@ try { mark(source.version + ' repetition ' + repetition + ': identical original task/baseline/tests/response algorithm and budgets; actual prompt overhead and host approvals recorded'); } assert.equal(results.length, 8); assert.equal(comparisons.length, 4); - } else for (const kind of contextMode ? ['native-context'] : ['node', 'react', 'python']) results.push(await runSample(kind)); + } else for (const kind of contextMode ? ['native-context'] : ['node', 'react', 'python']) results.push(await runSample(kind,{strategy:originalStrategy})); assert.deepEqual(inputs(), frozen); - report = { success: true, targetVersion: version, testedVersion: version, protocol: responsesMode ? 'responses-stream' : 'chat-completions', directory, installation, cases, results, comparisons, sources, inputs: frozen, realModelRequests: 0, + report = { success: true, targetVersion: version, testedVersion: version, protocol: responsesMode ? 'responses-stream' : 'chat-completions', contextLimit:contextMode?contextLimit:64000, originalPurge:originalPurgeMode, directory, installation, cases, results, comparisons, sources, inputs: frozen, realModelRequests: 0, scope: 'Pinned actual Harness and workbench execution with an owned HTTP model fixture. Checks, approvals, failures, parent merges, Edge and Git are real. Model reasoning and Purge benefit remain separate.' }; } catch (error) { report = { success: false, targetVersion: version, testedVersion: version, directory, installation, cases, results, inputs: frozen, error: error.stack, realModelRequests: 0 }; process.exitCode = 1; } finally { fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(report, null, 2)); fs.writeFileSync('.qa/' + (contextMode ? (responsesMode ? 'responses-context' : 'controlled-context') : responsesMode ? 'responses-engineering' : desktopMode ? 'desktop-projects' : comparisonMode ? 'controlled-purge' : 'controlled-projects') + '-location.json', JSON.stringify({ directory, result: path.join(directory, 'result.json') })); console.log('EVIDENCE ' + directory); console.log(JSON.stringify({ success: report.success, cases: cases.length, directory, realModelRequests: 0, error: report.error ?? null })); } diff --git a/scripts/verify-original-purge-host.mjs b/scripts/verify-original-purge-host.mjs new file mode 100644 index 00000000..8981622d --- /dev/null +++ b/scripts/verify-original-purge-host.mjs @@ -0,0 +1,101 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {fixture,compatibleFixture,call,until} from '../tests/helpers.mjs'; +import {createDeliveryProject} from '../tests/fixtures/delivery-project.mjs'; +import {ownerBytes} from '../tests/fixtures/workers-project.mjs'; +import {Provider} from '../src/server/provider.mjs'; +import {Runtime} from '../src/server/runtime.mjs'; +import {EngineRunner} from '../src/core/engines/engine-runner.mjs'; +import {resolveControlledInstallation} from '../src/core/engines/controlled-installation.mjs'; +import {resolveOriginalPurgeSource,ORIGINAL_PURGE_KIND,assertPurgeModelInput,PURGE_DEFAULT_PROMPT} from '../src/core/engines/purge-strategy.mjs'; +import {originalEngineRun,verifyEngineModelInput} from '../src/shared/contracts/engine-execution.mjs'; + +const directory=path.resolve('.qa','original-purge-host-'+randomUUID());fs.mkdirSync(directory,{recursive:true}); +const installation=resolveControlledInstallation(process.cwd(),process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT); +assert.equal(installation.controlledStatus,'available',installation.message); +const source=resolveOriginalPurgeSource(process.cwd(),process.env.AGENT_WORKBENCH_PURGE_178_ROOT,installation);assert.equal(source.status,'available',source.message); +const results=[]; +const usage={prompt_tokens:123,completion_tokens:45,total_tokens:168}; +async function sample(scenario){ + const disposers=[],t={after:fn=>disposers.push(fn)},f=fixture(t),sample=path.join(directory,scenario);fs.mkdirSync(sample); + let runtime,group,release,started,reported;let first=true; + try{ + createDeliveryProject(f);const original=ownerBytes(f),copy=path.join(f.root,'declared-original-source'); + fs.mkdirSync(copy);for(const input of source.inputs){const file=path.join(copy,input.relative);fs.mkdirSync(path.dirname(file),{recursive:true});fs.copyFileSync(input.path,file);} + const selected=resolveOriginalPurgeSource(process.cwd(),copy,installation);assert.equal(selected.status,'available',selected.message); + const gate=new Promise(resolve=>{release=resolve;}); + const model=await compatibleFixture(t,async(_route,_input,requests)=>{ + if(scenario==='stop-in-flight')await gate; + if(scenario==='reported-budget-overrun')return {status:503,body:{error:{message:'Owned upstream 503 with reported usage'},usage:{prompt_tokens:55000,completion_tokens:17,total_tokens:55017}}}; + const tools=[]; + if(scenario==='source-changed-at-approval'){ + const worker=group.children[0],plan=[...f.store.core.check_plan.values()].find(item=>item.taskId===worker.taskId); + tools.push(plan?call('owned-check','run_checks',{plan_id:plan.id}):call('owned-plan','plan_checks',{names:['test','build']})); + }else if(scenario==='denied-scope'&&requests.length===1)tools.push(call('owned-outside','propose_file',{path:'../outside.mjs',content:'denied',reason:'Declared negative scope test'})); + return {choices:[{message:{role:'assistant',content:tools.length?'':'Owned host fixture terminal.',...(tools.length?{tool_calls:tools}:{})},finish_reason:tools.length?'tool_calls':'stop'}],usage}; + }); + f.store.saveConfig({mode:'compatible',model:'owned-original-host',baseUrl:model.baseUrl,contextLimit:32000,maxOutputTokens:1024}); + const provider=new Provider();provider.setKey('owned-original-host-http-fixture');runtime=new Runtime(f.store,provider); + runtime.controlledEngines=new EngineRunner(f.store,provider,{directoryRoot:path.join(f.root,'owned-engines')}); + const manager=runtime.workerManager();group=await manager.plan(f.session,{goal:'Verify original Purge '+scenario, + engine:{id:'deepseek-harness',root:installation.root,controlledSha256:installation.controlledSha256, + strategy:{kind:ORIGINAL_PURGE_KIND,root:copy,sourceSha256:selected.sourceSha256,runtimeSha256:selected.runtimeSha256,prompt:PURGE_DEFAULT_PROMPT}}, + budget:{maxTokens:scenario==='reported-budget-overrun'?35000:150000,maxSteps:12,maxToolCalls:20,maxDurationMs:120000}, + children:[{label:'original-1',goal:'Keep the original project and host controls',paths:['src/add.mjs']}]}); + await (await manager.prepare(f.session,group.id,group.fingerprint)).promise;assert.equal(group.status,'ready',group.summary); + const worker=group.children[0],session=f.store.session(worker.sessionId),task=f.store.core.task.get(worker.taskId); + started=manager.start(f.session,group.id,group.fingerprint); + if(scenario==='stop-in-flight'){ + await until(()=>model.requests.length===1,45000);await runtime.stop(session.id);release(); + } + if(scenario==='source-changed-at-approval'){ + await until(()=>session.approvals.some(item=>item.status==='pending'),45000); + fs.appendFileSync(path.join(copy,'lib/host.js'),'\n// Declared source drift during approval\n'); + const approval=session.approvals.find(item=>item.status==='pending');runtime.decide(session.id,approval.id,true); + } + await started.promise;release(); + const jobs=[...f.store.core.engine_run.values()].filter(job=>job.taskId===worker.taskId),job=jobs.at(-1),run=f.store.core.run.get(job.runId); + assert.equal(job.native.cleanup.rootExited,true);assert.equal(job.native.cleanup.treeConfirmed,true);assert.deepEqual(ownerBytes(f),original); + originalEngineRun(f.store,session,job); + for(const request of job.requests){const input=verifyEngineModelInput(f.store,session,job,request);assertPurgeModelInput(input.native,job.installation.strategy);} + assert.ok(model.requests.length>0,'The owned native request must reach the declared HTTP fixture.'); + assert.equal(task.usage.requests,model.requests.length);assert.equal((run.consumption??[]).length,model.requests.length); + if(scenario==='reported-budget-overrun'){ + assert.equal(model.requests.length,1);assert.equal(task.usage.totalTokens,55017);assert.equal(run.usage.unknownRequests,0);assert.equal(run.stopReason,'token_limit');assert.equal(job.calls.length,0); + } + if(scenario==='denied-scope'){ + assert.equal(model.requests.length,2);assert.equal(job.calls.length,1);assert.equal(session.changes.length,0);assert.equal(task.usage.totalTokens,336); + assert.equal(fs.existsSync(path.join(f.store.project(worker.projectId).root,'..','outside.mjs')),false); + } + if(scenario==='stop-in-flight'){ + assert.equal(model.requests.length,1);assert.equal(job.calls.length,0);assert.equal(job.status,'cancelled');assert.equal(run.usage.unknownRequests,1);assert.equal(task.usage.unknownRequests,1); + const oldJob=JSON.stringify(job),oldUsage=structuredClone(task.usage),oldRun=JSON.stringify(run); + await (await manager.start(f.session,group.id,group.fingerprint)).promise; + const resumed=[...f.store.core.engine_run.values()].filter(value=>value.taskId===worker.taskId).at(-1),resumedRun=f.store.core.run.get(resumed.runId); + assert.notEqual(resumed.id,job.id);assert.notEqual(resumed.runId,job.runId);assert.equal(resumed.taskId,job.taskId);assert.equal(resumed.status,'completed',resumed.error); + assert.equal(model.requests.length,2);assert.equal(task.usage.requests,2);assert.equal(task.usage.unknownRequests,1);assert.equal(task.usage.totalTokens,oldUsage.totalTokens+168); + assert.equal(task.usage.estimatedUnknownTokens,oldUsage.estimatedUnknownTokens);assert.equal(JSON.stringify(job),oldJob);assert.equal(JSON.stringify(run),oldRun); + assert.equal(resumedRun.consumption.length,1);assert.equal(resumed.native.cleanup.treeConfirmed,true);assert.equal(resumed.calls.length,0); + originalEngineRun(f.store,session,resumed);reported={resumedJob:resumed,resumedRun,originalStopUsage:oldUsage}; + } + if(scenario==='source-changed-at-approval'){ + assert.equal(model.requests.length,2);assert.equal(f.store.core.check_job.size,0);assert.match(job.error,/已变化/);assert.equal(task.usage.totalTokens,336); + } + reported={...reported,scenario,passed:true,group,task,run,job,modelRequests:model.requests,realModelRequests:0}; + console.log('PASS '+scenario+'; HTTP '+model.requests.length+'; task reported '+task.usage.totalTokens+'; unknown '+task.usage.unknownRequests); + }catch(error){reported={scenario,passed:false,error:error.stack,group,realModelRequests:0};throw error;} + finally{ + release?.();if(started)await started.promise.catch(()=>{});if(runtime)await runtime.stopAll(); + f.store.storage.database.exec('PRAGMA wal_checkpoint(TRUNCATE)');fs.writeFileSync(path.join(sample,'result.json'),JSON.stringify(reported,null,2)); + fs.cpSync(f.root,path.join(sample,'original-fixture'),{recursive:true,filter:file=>!file.split(path.sep).includes('node_modules')}); + for(const dispose of disposers.reverse())await dispose(); + } + return {scenario,passed:true}; +} +let report; +try{for(const scenario of ['reported-budget-overrun','denied-scope','stop-in-flight','source-changed-at-approval'])results.push(await sample(scenario)); + report={passed:true,directory,results,realModelRequests:0,scope:'Actual pinned Harness and production host routing with owned HTTP fixtures. No real model reasoning or Purge benefit.'}; +}catch(error){process.exitCode=1;report={passed:false,directory,results,error:error.stack,realModelRequests:0};} +fs.writeFileSync(path.join(directory,'validation.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report)); diff --git a/scripts/verify-original-purge-production-evidence.mjs b/scripts/verify-original-purge-production-evidence.mjs new file mode 100644 index 00000000..b44e1d74 --- /dev/null +++ b/scripts/verify-original-purge-production-evidence.mjs @@ -0,0 +1,75 @@ +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'; +import {originalEngineRun,verifyEngineModelInput} from '../src/shared/contracts/engine-execution.mjs'; +import {assertPurgeModelInput} from '../src/core/engines/purge-strategy.mjs'; + +// Offline only: inspect original bytes and pure contracts, never instantiate +// a Provider/Runtime, load an upstream plugin or send a model request. +const root=path.resolve('docs/original-purge-production-evidence'),sha=raw=>createHash('sha256').update(raw).digest('hex'); +const inside=relative=>{const file=path.resolve(root,relative);assert.ok(file.startsWith(root+path.sep));return file;}; +const read=relative=>JSON.parse(fs.readFileSync(inside(relative))),raw=fs.readFileSync(inside('manifest.json')),manifest=JSON.parse(raw); +assert.equal(manifest.schemaVersion,1);assert.equal(manifest.realModelRequests,0);assert.equal(manifest.formalServiceChanged,false); +let bytes=0;const paths=new Set(); +for(const entry of manifest.entries){assert.ok(!paths.has(entry.path));paths.add(entry.path);const data=fs.readFileSync(inside(entry.path)); + assert.equal(data.length,entry.bytes,entry.path);assert.equal(sha(data),entry.sha256,entry.path);bytes+=data.length;} +assert.equal(paths.size,manifest.count);assert.equal(bytes,manifest.bytes); +for(const input of manifest.sourceInputs){ + const git=execFileSync('git',['show',manifest.sourceCommit+':'+input.path],{windowsHide:true,maxBuffer:16*1024*1024}); + assert.equal(sha(git),input.gitBlobSha256,input.path); + if(input.snapshot){const bytes=fs.readFileSync(inside(input.snapshot));assert.equal(sha(bytes),input.sha256);assert.equal(bytes.length,input.bytes); + assert.equal(bytes.toString('utf8').replaceAll('\r\n','\n'),git.toString('utf8').replaceAll('\r\n','\n'));} + else assert.equal(sha(git),input.sha256,input.path); +} +const receipt=name=>fs.readFileSync(inside(manifest.receipts.find(value=>value.name===name).file),'utf8'); +assert.match(receipt('full'),new RegExp('tests '+manifest.fullSummary.tests+'\\b')); +assert.match(receipt('full'),new RegExp('pass '+manifest.fullSummary.passed+'\\b')); +assert.match(receipt('full'),/fail 4\b/);assert.equal(manifest.fullSummary.failed,4); +assert.equal(manifest.fullSummary.tests,manifest.fullSummary.passed+manifest.fullSummary.failed); +// Preserve the original failed whole run. Subsequent evidence is the same +// Python cases with the declared environment and the two repaired migrations. +assert.deepEqual(manifest.fullSummary.failedNames.slice().sort(),[ + 'real pytest pass, failure, skip, collection errors and teardown errors use collected case outcomes', + 'a missing interpreter and repeated pytest item objects cannot create a false verification pass', + 'a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider', + 'the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection' +].sort()); +for(const [name,count] of [['python-final',15],['upgrade-final',2]]){ + assert.match(receipt(name),new RegExp('tests '+count+'\\b'));assert.match(receipt(name),new RegExp('pass '+count+'\\b'));assert.match(receipt(name),/fail 0\b/); +} +assert.match(receipt('build'),/Server bundle built\./); +const runtime=read(manifest.runtime);assert.equal(runtime.passed,true);assert.equal(runtime.productionAdapter,true); +assert.deepEqual(runtime.cases.map(value=>value.scenario),['completed','failed-no-retry','host-denied-tool']); +assert.equal(runtime.cases[0].exit.code,0);assert.deepEqual(runtime.cases.map(value=>value.bridgeCalls),[1,1,2]); +const host=read(manifest.host.result);assert.equal(host.passed,true);assert.equal(host.results.length,4); +for(const sample of manifest.host.samples){const value=read(sample.result);assert.equal(value.passed,true);assert.equal(value.job.native.cleanup.treeConfirmed,true); + if(value.scenario==='reported-budget-overrun'){assert.equal(value.task.usage.totalTokens,55017);assert.equal(value.run.stopReason,'token_limit');assert.equal(value.modelRequests.length,1);} + if(value.scenario==='stop-in-flight'){assert.equal(value.run.usage.unknownRequests,1);assert.equal(value.task.usage.unknownRequests,1); + assert.equal(value.modelRequests.length,2);assert.equal(value.resumedJob.taskId,value.job.taskId);assert.notEqual(value.resumedJob.runId,value.job.runId); + assert.equal(value.resumedJob.native.cleanup.treeConfirmed,true);assert.equal(value.task.usage.totalTokens,168);} + if(value.scenario==='source-changed-at-approval')assert.match(value.job.error,/已变化/); +} +const ui=read(manifest.ui.result);assert.equal(ui.passed,true);assert.equal(ui.cases.length,4);assert.deepEqual(ui.pageErrors,[]);assert.deepEqual(ui.unexpectedFailures,[]); +assert.equal(manifest.ui.screenshots.length,4); +let requests=0,artifacts=0; +for(const sample of manifest.engineering){ + const result=read(sample.result),core={},owners=new Map(read(sample.sessions).map(value=>[value.id,value])); + for(const row of read(sample.records)){const value=JSON.parse(row.payload);(core[row.kind]??=new Map()).set(value.id,value);} + const inputs=new Map(sample.artifacts.map(value=>[value.id,value]));artifacts+=inputs.size; + const store={core,owned(kind,id,sessionId){const value=core[kind]?.get(id);assert.equal(value?.sessionId,sessionId);return value;}, + artifactStore:{read(artifact){const data=fs.readFileSync(inside(inputs.get(artifact.id).file));assert.equal(sha(data),artifact.sha256);assert.equal(data.length,artifact.bytes);return data.toString('utf8');}}, + savedToolResult(sessionId,callId){const tool=[...core.tool.values()].find(value=>value.sessionId===sessionId&&value.callId===callId);return JSON.parse(this.artifactStore.read(core.artifact.get(tool.resultArtifactId)));}}; + assert.equal(result.success,true);assert.equal(result.metrics.contextLimit,32000);assert.equal(result.parentCheck.results[0].tests.passed,9); + assert.ok(result.checks.some(job=>job.status==='failed'&&job.results[0].tests.failed===9)); + for(const job of core.engine_run.values()){ + const session=owners.get(job.sessionId);originalEngineRun(store,session,job);assert.equal(job.status,'completed');assert.equal(job.native.cleanup.treeConfirmed,true); + const original=job.native.originalPurge;assert.equal(original.readiness.originalApplyCalled,true);assert.equal(original.nativeLoads.length,2);assert.ok(original.durabilityReceipts.length); + assert.equal(job.installation.strategy.kind,'purge-original-restricted-v1'); + for(const request of job.requests){const input=verifyEngineModelInput(store,session,job,request);assertPurgeModelInput(input.native,job.installation.strategy);requests++;} + } +} +assert.deepEqual(manifest.engineering.map(value=>value.name),['chat','responses']); +console.log(JSON.stringify({passed:true,sourceCommit:manifest.sourceCommit,files:paths.size,bytes,fullSummary:manifest.fullSummary,artifacts,requests, + manifestSha256:sha(raw),realModelRequests:0,scope:'Offline original source/receipt/request/usage/cleanup checks. Actual reasoning and Purge benefit remain unmeasured.'})); diff --git a/scripts/verify-original-purge-runtime.mjs b/scripts/verify-original-purge-runtime.mjs new file mode 100644 index 00000000..81d6400a --- /dev/null +++ b/scripts/verify-original-purge-runtime.mjs @@ -0,0 +1,52 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {ControlledDeepSeekSession} from '../src/core/engines/controlled-session.mjs'; +import {resolveControlledInstallation} from '../src/core/engines/controlled-installation.mjs'; +import {resolveOriginalPurgeSource,selectPurgeStrategy,assertPurgeModelInput,ORIGINAL_PURGE_KIND} from '../src/core/engines/purge-strategy.mjs'; + +// Real pinned Harness, production adapter, synthetic model responses. No Key, +// configured provider, user project, clientFactory patch or upstream mutation. +const directory=path.resolve('.qa','original-purge-runtime-'+randomUUID());fs.mkdirSync(directory,{recursive:true}); +const installation=resolveControlledInstallation(process.cwd(),process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT); +assert.equal(installation.controlledStatus,'available',installation.message); +const source=resolveOriginalPurgeSource(process.cwd(),process.env.AGENT_WORKBENCH_PURGE_178_ROOT,installation); +assert.equal(source.status,'available',source.message); +const strategy=selectPurgeStrategy({kind:ORIGINAL_PURGE_KIND,root:source.root,sourceSha256:source.sourceSha256,runtimeSha256:source.runtimeSha256, + prompt:'Preserve the owned engineering task, host approvals, saved evidence and cumulative budget.'},process.cwd(),installation); +const results=[];let active; +try{ + for(const scenario of ['completed','failed-no-retry','host-denied-tool']){ + const cwd=path.join(directory,scenario);fs.mkdirSync(cwd);const driver=new ControlledDeepSeekSession(installation,{timeoutMs:30000});active=driver; + const controller=new AbortController(),modelInputs=[];let tools=0,text=null,error=null; + try{ + await driver.open({directory:path.join(cwd,'native'),cwd,owner:Object.fromEntries(['sessionId','projectId','taskId','runId','jobId'].map(key=>[key,randomUUID()])), + sdkSessionId:randomUUID(),strategy,signal:controller.signal,config:{model:'owned-original-purge-runtime',contextLimit:16000,maxOutputTokens:512,maxRunDurationMs:30000}, + tools:[{name:'owned_probe',description:'A host-gated synthetic test tool.',parameters:{type:'object',properties:{},additionalProperties:false}}], + onModel:async input=>{ + modelInputs.push(input);assertPurgeModelInput(input,strategy); + if(scenario==='failed-no-retry')throw new Error('Declared upstream fixture failure; no automatic retry.'); + if(modelInputs.length>1)throw new Error('Host stops the next model round after the rejected tool result.'); + return {message:{role:'assistant',content:scenario==='completed'?'Owned original entry completed.':'',...(scenario==='host-denied-tool'?{ + tool_calls:[{id:'declared-owned-tool',type:'function',function:{name:'owned_probe',arguments:'{}'}}]}:{})},usage:{prompt_tokens:300,completion_tokens:50,total_tokens:350}}; + },onTool:async()=>{tools++;throw new Error('External host denied the declared operation.');}}); + await driver.prompt('Complete only this owned loading/protocol acceptance.');text=await driver.wait(); + }catch(failure){error=failure.stack;} + const report=await driver.close({force:!!error});active=null; + const result={scenario,text,error,modelInputs,tools,report};results.push(result);fs.writeFileSync(path.join(cwd,'result.json'),JSON.stringify(result,null,2)); + assert.equal(report.cleanup?.rootExited,true,JSON.stringify(report));assert.equal(report.cleanup?.treeConfirmed,true); + assert.equal(report.originalPurge.readiness?.originalApplyCalled,true);assert.ok(report.originalPurge.loadedModules.length>330); + if(scenario==='completed'){assert.equal(error,null);assert.equal(text,'Owned original entry completed.');assert.equal(report.status,'closed');assert.equal(report.cleanup.exit.code,0);assert.equal(modelInputs.length,1);assert.equal(tools,0);} + assert.ok(report.originalPurge.durabilityReceipts.length>0); + if(scenario==='failed-no-retry'){assert.notEqual(error,null);assert.equal(modelInputs.length,1);assert.equal(tools,0);} + if(scenario==='host-denied-tool'){assert.notEqual(error,null);assert.equal(modelInputs.length,2);assert.equal(tools,1);} + console.log('PASS '+scenario+'; model bridge '+modelInputs.length+'; host tools '+tools+'; process tree closed'); + } + const summary={passed:true,directory,productionAdapter:true,realModelRequests:0,sourceSha256:source.sourceSha256,runtimeSha256:source.runtimeSha256, + cases:results.map(({scenario,modelInputs,tools,report})=>({scenario,bridgeCalls:modelInputs.length,hostTools:tools,status:report.status,exit:report.cleanup.exit, + loadedModules:report.originalPurge.loadedModules.length,fsyncs:report.originalPurge.durabilityReceipts.length})), + scope:'Pinned original entry through production ControlledDeepSeekSession. Synthetic model responses; no real autonomy or Purge benefit measured.'}; + fs.writeFileSync(path.join(directory,'validation.json'),JSON.stringify(summary,null,2));console.log(JSON.stringify(summary)); +}catch(error){console.error(JSON.stringify({passed:false,directory,error:error.stack,realModelRequests:0}));process.exitCode=1;} +finally{if(active)await active.close({force:true});} diff --git a/scripts/verify-original-purge-ui.mjs b/scripts/verify-original-purge-ui.mjs new file mode 100644 index 00000000..2410a380 --- /dev/null +++ b/scripts/verify-original-purge-ui.mjs @@ -0,0 +1,84 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {createHash,randomUUID} from 'node:crypto'; +import {chromium,expect} from 'playwright/test'; +import {fixture} from '../tests/helpers.mjs'; +import {workerHttp} from '../tests/fixtures/workers-http.mjs'; +import {ownerBytes} from '../tests/fixtures/workers-project.mjs'; +import {EngineRunner} from '../src/core/engines/engine-runner.mjs'; +import {resolveControlledInstallation} from '../src/core/engines/controlled-installation.mjs'; +import {resolveOriginalPurgeSource} from '../src/core/engines/purge-strategy.mjs'; +import {originalEngineRun} from '../src/shared/contracts/engine-execution.mjs'; + +const directory=path.resolve('.qa','original-purge-ui-'+randomUUID());fs.mkdirSync(directory,{recursive:true}); +const installation=resolveControlledInstallation(process.cwd(),process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT); +assert.equal(installation.controlledStatus,'available',installation.message); +const originalSource=resolveOriginalPurgeSource(process.cwd(),process.env.AGENT_WORKBENCH_PURGE_178_ROOT,installation);assert.equal(originalSource.status,'available',originalSource.message); +const copy=path.join(directory,'declared-source');fs.mkdirSync(copy); +for(const input of originalSource.inputs){const target=path.join(copy,input.relative);fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(input.path,target);} +const disposers=[],t={after:fn=>disposers.push(fn)},f=fixture(t),host=await workerHttp(f),owner=ownerBytes(f); +f.store.saveConfig({contextLimit:64000});host.runtime.controlledEngines=new EngineRunner(f.store,host.provider,{directoryRoot:path.join(f.root,'owned-native-runs')}); +const hash=raw=>createHash('sha256').update(raw).digest('hex'),cases=[],screenshots=[],pageErrors=[],unexpectedFailures=[],closedNavigationStreams=[]; +const browser=await chromium.launch({channel:'msedge',headless:true}),page=await browser.newPage({viewport:{width:1440,height:1000},acceptDownloads:true}); +const eventStreams=new Set(),navigationStreams=new WeakSet(); +page.on('request',request=>{if(new URL(request.url()).pathname==='/api/events')eventStreams.add(request);}); +page.on('pageerror',error=>pageErrors.push(error.message));page.on('requestfailed',request=>{ + const error=request.failure()?.errorText,record={path:new URL(request.url()).pathname,error}; + if(navigationStreams.has(request)&&/ERR_ABORTED|ERR_INCOMPLETE_CHUNKED_ENCODING/.test(error??''))closedNavigationStreams.push(record); + else unexpectedFailures.push(record); +}); +const panel=()=>page.getByLabel('隔离协作控制台',{exact:true}),control=()=>panel().getByLabel('Purge 原版受限模式',{exact:true}); +const seal=()=>panel().getByRole('button',{name:'封存分工计划',exact:true}); +const mark=value=>{cases.push(value);console.log('PASS '+value);}; +async function screenshot(name){const file=path.join(directory,name+'.png');await page.screenshot({path:file,scale:'css'});screenshots.push({file,sha256:hash(fs.readFileSync(file))});} +async function workers(){const close=page.getByRole('button',{name:'关闭检视区',exact:true});if(page.viewportSize().width<=940&&await close.isVisible())await close.click(); + await page.getByRole('button',{name:'隔离协作',exact:true}).click();await expect(panel()).toBeVisible();} +async function detect(){await control().getByRole('button',{name:'检测 Purge 来源',exact:true}).click();await expect(control()).toContainText('已核对 Purge 1.1.78');} +let report; +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,{waitUntil:'networkidle'});await workers();await panel().getByLabel('执行方式',{exact:true}).selectOption('deepseek'); + await panel().getByLabel('Harness 安装目录',{exact:true}).fill(installation.root);await panel().getByRole('button',{name:'检测受控安装',exact:true}).click();await expect(panel()).toContainText('受控安装可用'); + await panel().getByLabel('父目标',{exact:true}).fill('核对原版 Purge 的真实加载与任务归属');await panel().getByLabel('任务名称',{exact:true}).fill('original-1'); + await panel().getByLabel('独立子目标',{exact:true}).fill('只在允许目录中提出修改,保留原审批与完整报告');await panel().getByLabel('允许修改的文件或目录',{exact:true}).fill('src/a.mjs'); + const promptControl=panel().getByLabel('Purge 提示实验',{exact:true});await expect(promptControl.getByRole('checkbox')).not.toBeChecked(); + await promptControl.getByRole('checkbox').check();await promptControl.getByLabel('Purge 执行模式',{exact:true}).selectOption('purge-original-restricted-v1'); + await expect(seal()).toBeDisabled();await expect(control()).toContainText('原版效果需另行实测'); + await control().getByLabel('Purge 源码目录',{exact:true}).fill(copy);await detect();await expect(seal()).toBeEnabled(); + await control().getByText('实验来源与执行范围',{exact:true}).click();await expect(control()).toContainText('Node 权限不等同于操作系统沙箱'); + await screenshot('original-purge-desktop-source');mark('desktop distinguishes the original restricted profile from the default-off independent prompt and detects complete fixed inputs'); + const before=f.store.core.task.size;fs.appendFileSync(path.join(copy,'lib/host.js'),'\n// owned post-detection drift\n'); + await seal().click();await expect(panel()).toContainText('原版来源或运行依赖与刚才的检测不一致');assert.equal(f.store.core.task.size,before);assert.equal(host.requests.length,0); + fs.copyFileSync(path.join(originalSource.root,'lib/host.js'),path.join(copy,'lib/host.js'));await detect(); + await expect(panel()).not.toContainText('原版来源或运行依赖与刚才的检测不一致');mark('a changed original module outside the old nine-file lock refuses sealing and restoring/detecting clears obsolete feedback'); + await page.setViewportSize({width:390,height:844});await control().getByLabel('Purge 执行模式',{exact:true}).scrollIntoViewIfNeeded(); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);const box=await control().getByLabel('Purge 执行模式',{exact:true}).boundingBox();assert.ok(box.height>=42); + await screenshot('original-purge-mobile-source');await seal().click();await expect(panel()).toContainText('本计划的 Purge 原版受限模式'); + const group=[...f.store.core.collaboration.values()].at(-1),strategy=group.children[0].engine.strategy;assert.equal(strategy.kind,'purge-original-restricted-v1'); + assert.equal(strategy.source.inputs.length,60);assert.equal(strategy.runtime.nativeAddons.length,2);assert.equal(strategy.originalConfig.autoRetry,false); + for(const request of eventStreams)navigationStreams.add(request); + const reconnected=page.waitForResponse(response=>new URL(response.url()).pathname==='/api/events'&&response.status()===200); + await page.reload({waitUntil:'networkidle'});await reconnected;await workers();await expect(panel()).toContainText(strategy.sha256.slice(0,16));mark('390px selection is usable and the persisted parent plan retains the original source, runtime and fixed configuration after refresh'); + await panel().getByRole('button',{name:'创建引擎工作区',exact:true}).click();await page.getByRole('dialog',{name:'确认创建隔离工作区',exact:true}).getByRole('button',{name:'确认创建',exact:true}).click(); + await expect(panel().getByRole('button',{name:'开始引擎任务',exact:true})).toBeEnabled({timeout:30000}); + await panel().getByRole('button',{name:'开始引擎任务',exact:true}).click();await page.getByRole('dialog',{name:'确认受限子执行',exact:true}).getByRole('button',{name:'确认开始',exact:true}).click(); + await expect.poll(()=>group.status,{timeout:60000}).toBe('awaiting_review'); + const job=[...f.store.core.engine_run.values()].at(-1),session=f.store.session(job.sessionId);assert.equal(job.status,'completed',job.error);assert.equal(job.native.cleanup.treeConfirmed,true); + assert.equal(job.native.originalPurge.readiness.originalApplyCalled,true);assert.equal(job.native.originalPurge.nativeLoads.length,2);assert.deepEqual(ownerBytes(f),owner); + await panel().getByRole('button',{name:'审查子任务改动',exact:true}).click(); + // Navigation loads the child asynchronously; wait for its inspector before + // closing it, so a late navigation result cannot reopen it over the toolbar. + await expect(panel()).toBeHidden(); + const close=page.getByRole('button',{name:'关闭检视区',exact:true});await expect(close).toBeVisible();await close.click();await expect(page.locator('aside.inspector')).toBeHidden(); + await page.getByRole('button',{name:'本地代理引擎',exact:true}).click();const runs=page.getByLabel('受控引擎工程运行',{exact:true}); + await expect(runs).toContainText('Purge 原版受限模式 · 1.1.78');await runs.getByText('查看本次实验策略',{exact:true}).click();await expect(runs).toContainText(strategy.runtime.sha256); + const pending=page.waitForEvent('download');await runs.getByRole('button',{name:'下载完整报告',exact:true}).click();const download=await pending,file=path.join(directory,'original-engine-report.json');await download.saveAs(file); + assert.equal(fs.readFileSync(file,'utf8'),originalEngineRun(f.store,session,job));assert.equal(hash(fs.readFileSync(file)),job.reportSha256); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await screenshot('original-purge-mobile-run');mark('actual original Harness execution remains an owned Run and the UI downloads its byte-identical native loading, request and cleanup report'); + await page.setViewportSize({width:1440,height:1000});await screenshot('original-purge-desktop-run');assert.equal(pageErrors.length,0);assert.equal(unexpectedFailures.length,0); + report={passed:true,directory,cases,screenshots,pageErrors,unexpectedFailures,closedNavigationStreams,group,job,realModelRequests:0,scope:'Compiled React UI, source HTTP host, actual Harness/original entry and declared Provider fixture. No real model benefit.'}; +}catch(error){process.exitCode=1;report={passed:false,directory,cases,screenshots,pageErrors,unexpectedFailures,closedNavigationStreams,error:error.stack,realModelRequests:0};} +finally{await host.runtime.stopAll();await browser.close();f.store.storage.database.exec('PRAGMA wal_checkpoint(TRUNCATE)'); + fs.cpSync(f.root,path.join(directory,'original-fixture'),{recursive:true,filter:file=>!file.split(path.sep).includes('node_modules')}); + fs.writeFileSync(path.join(directory,'validation.json'),JSON.stringify(report,null,2));for(const dispose of disposers.reverse())await dispose();console.log(JSON.stringify({passed:report.passed,directory,cases:cases.length,error:report.error??null}));} diff --git a/src/client/EngineRunPanel.tsx b/src/client/EngineRunPanel.tsx index fedafb4b..2c0821e8 100644 --- a/src/client/EngineRunPanel.tsx +++ b/src/client/EngineRunPanel.tsx @@ -51,7 +51,7 @@ export function EngineRunPanel({ session, onSession, onError, onNavigate }: { {job.error &&

{job.error}

} {job.status === 'completed' &&

原引擎运行与调用账本已核验。工程完成仍以提案应用、当前检查和父工程交付为准。

} {job.requiresVerification &&

请返回父目标核对原输入与现场。原未知结果保留,继续会创建新的运行。

} - {job.installation.strategy &&
Purge 提示实验 · {job.installation.strategy.source.version}

本 Run 使用已封存工程提示,原审批与预算继续生效。

查看本次实验策略
策略 SHA256
{job.installation.strategy.sha256}
来源 SHA256
{job.installation.strategy.source.sourceSha256}
文本 SHA256
{job.installation.strategy.promptSha256}
来源目录
{job.installation.strategy.source.root}
{job.installation.strategy.prompt}
} + {job.installation.strategy &&
Purge {job.installation.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {job.installation.strategy.source.version}

{job.installation.strategy.kind==='purge-original-restricted-v1'?'本 Run 加载固定原版入口,自动重试和继续关闭;工作台审批与预算继续生效。':'本 Run 使用已封存工程提示,原审批与预算继续生效。'}

查看本次实验策略
策略 SHA256
{job.installation.strategy.sha256}
来源 SHA256
{job.installation.strategy.source.sourceSha256}
文本 SHA256
{job.installation.strategy.promptSha256}
来源目录
{job.installation.strategy.source.root}
{job.installation.strategy.kind==='purge-original-restricted-v1'&&<>
固定运行依赖 SHA256
{job.installation.strategy.runtime.sha256}
加载范围
{job.installation.strategy.runtime.inputs.length} 份固定输入 / {job.installation.strategy.runtime.nativeAddons.length} 个固定原生模块
}
{job.installation.strategy.prompt}
} {job.review &&

人工核对记录:{job.review.evidenceSha256.slice(0, 16)}。原未知输出未改写为完成。

}
任务身份与来源
Task
{job.taskId}
Run
{job.runId}
SDK 会话
{job.sdkSessionId}
安装目录
{job.installation.root}
输入 SHA256
{job.inputSha256}
报告 SHA256
{job.reportSha256 ?? '尚未封存'}
原事件
{job.nativeSummary.notifications} 项
diff --git a/src/client/PurgeStrategyControl.css b/src/client/PurgeStrategyControl.css index c83e7ee3..7af2c35c 100644 --- a/src/client/PurgeStrategyControl.css +++ b/src/client/PurgeStrategyControl.css @@ -14,6 +14,8 @@ .purge-strategy-fields details { font-size:12px; color:#587087; min-width:0; } .purge-strategy-fields summary { cursor:pointer; } .purge-strategy-fields dl > div { margin-top:8px; } +.purge-strategy-fields .purge-source-inputs { max-height:260px; overflow:auto; padding-right:8px; } +.purge-strategy-fields select { width:100%; min-height:42px; min-width:0; border:1px solid #b8c7d5; border-radius:4px; background:white; color:#243d54; padding:8px; } .purge-strategy-fields dd { margin:4px 0 0; } .purge-strategy-control .purge-source-error { color:#794d21; background:#fff8ee; padding:10px; border-left:3px solid #925619; overflow-wrap:anywhere; } .engine-run-panel .engine-prompt-note { padding:12px; background:#f5f6fa; border-left:3px solid #626594; font-size:12px; line-height:1.7; } diff --git a/src/client/PurgeStrategyControl.tsx b/src/client/PurgeStrategyControl.tsx index 5fbd6724..f33a5acd 100644 --- a/src/client/PurgeStrategyControl.tsx +++ b/src/client/PurgeStrategyControl.tsx @@ -4,38 +4,49 @@ import { api } from './api'; import type { PurgeSourceAvailability } from './types'; import './PurgeStrategyControl.css'; -export type PurgeDraft = { enabled: boolean; root: string; prompt: string; source: PurgeSourceAvailability | null }; -export const emptyPurgeDraft = (): PurgeDraft => ({ enabled: false, root: '', prompt: '', source: null }); +export type PurgeDraft = { enabled: boolean; kind: 'purge-prompt-experiment' | 'purge-original-restricted-v1'; root: string; prompt: string; source: PurgeSourceAvailability | null }; +export const emptyPurgeDraft = (): PurgeDraft => ({ enabled: false, kind: 'purge-prompt-experiment', root: '', prompt: '', source: null }); +export const purgeStrategyInput = (value: PurgeDraft) => ({kind:value.kind,root:value.source?.root,sourceSha256:value.source?.sourceSha256,prompt:value.prompt, + ...(value.kind==='purge-original-restricted-v1'?{runtimeSha256:value.source?.runtimeSha256}:{})}); export function purgeDraftReady(value: PurgeDraft) { return !value.enabled || value.source?.status === 'available' && !!value.source.sourceSha256 + && (value.source.kind??'purge-prompt-experiment')===value.kind && (value.kind!=='purge-original-restricted-v1'||!!value.source.runtimeSha256) && !!value.prompt.trim() && new TextEncoder().encode(value.prompt).length <= 24000; } -export function PurgeStrategyControl({ value, onChange, busy }: { value: PurgeDraft; onChange: (value: PurgeDraft) => void; busy: boolean }) { +export function PurgeStrategyControl({ value, onChange, busy, harnessRoot }: { value: PurgeDraft; onChange: (value: PurgeDraft) => void; busy: boolean; harnessRoot?: string | null }) { const [detecting, setDetecting] = useState(false), [error, setError] = useState(''); const request = useRef(0), current = useRef(value); current.current = value; + const previousHarness = useRef(harnessRoot); + useEffect(() => { if(previousHarness.current===harnessRoot)return;previousHarness.current=harnessRoot;request.current++;setDetecting(false);setError(''); + if(current.current.kind==='purge-original-restricted-v1')onChange({...current.current,source:null}); }, [harnessRoot, onChange]); useEffect(() => () => { request.current++; }, []); function enabled(next: boolean) { request.current++; setDetecting(false); setError(''); onChange({ ...value, enabled: next }); } function editRoot(root: string) { request.current++; setDetecting(false); setError(''); onChange({ ...value, root, source: null }); } async function detect() { const generation = ++request.current; setDetecting(true); setError(''); onChange({ ...current.current, source: null }); try { - const source = await api('/engines/purge/source' + (value.root.trim() ? '?root=' + encodeURIComponent(value.root.trim()) : '')); + const query=new URLSearchParams({kind:value.kind});if(value.root.trim())query.set('root',value.root.trim());if(value.kind==='purge-original-restricted-v1'&&harnessRoot)query.set('harnessRoot',harnessRoot); + const source = await api('/engines/purge/source?'+query); if (generation !== request.current) return; onChange({ ...current.current, root: source.root ?? current.current.root, source, prompt: current.current.prompt || source.defaultPrompt }); } catch (failure) { if (generation === request.current) setError(failure instanceof Error ? failure.message : String(failure)); } finally { if (generation === request.current) setDetecting(false); } } - return
-
{value.enabled ? '仅对本计划生效' : '默认关闭'}
-

追加已封存的工程提示,继续使用原任务范围、检查审批和累计预算。实际收益需同题对照验证。

+ const original=value.kind==='purge-original-restricted-v1'; + return
+
{value.enabled ? '仅对本计划生效' : '默认关闭'}
+

{original?'运行原版 1.1.78 的固定受限配置,继续使用工作台的工具审批和累计预算。原版效果需另行实测。':'追加已封存的工程提示,继续使用原任务范围、检查审批和累计预算。实际收益需同题对照验证。'}

{value.enabled &&
+ - {value.source &&
{value.source.status === 'available' ? '已核对 Purge ' + value.source.version : '来源尚不可用'}

{value.source.message}

{value.source.sourceSha256 && {value.source.sourceSha256}}
} + {value.source &&
{value.source.status === 'available' ? '已核对 Purge ' + value.source.version : '来源尚不可用'}

{value.source.message}

{value.source.sourceSha256 && {value.source.sourceSha256}}{original&&value.source.runtimeSha256&&

固定运行依赖 {value.source.runtimeInputs} 份 · {value.source.runtimeSha256}

}
} {error &&

{error}

}