feat: integrate pinned original Purge with host execution gates
This commit is contained in:
@@ -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、原暂存/未暂存保护、实际模型身份、全部请求、报告/未知消费、耗时和监督次数。先记录失败,再做独立修复;同一失败样本不通过追加隐含提示变成新成功。
|
||||
|
||||
出现来源漂移、未知操作、超过预算或原进程不能确认关闭时,停止本样本并保存结果;后续组是否仍可独立执行按剩余预算和来源一致性判断。结束核对原用户项目、所有原会话/工件及模型池选择,新增记录必须归属于本批次。没有已核对的收费明细就不编造费用或节省比例;两个顺序的四个对照样本只提供描述性结果。
|
||||
@@ -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 真实批次。
|
||||
+12
@@ -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 同源。
|
||||
|
||||
@@ -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。
|
||||
|
||||
@@ -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))}));
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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 })); }
|
||||
|
||||
@@ -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));
|
||||
@@ -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.'}));
|
||||
@@ -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});}
|
||||
@@ -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}));}
|
||||
@@ -51,7 +51,7 @@ export function EngineRunPanel({ session, onSession, onError, onNavigate }: {
|
||||
{job.error && <p className="engine-run-error">{job.error}</p>}
|
||||
{job.status === 'completed' && <p className="engine-run-note">原引擎运行与调用账本已核验。工程完成仍以提案应用、当前检查和父工程交付为准。</p>}
|
||||
{job.requiresVerification && <p className="engine-run-note">请返回父目标核对原输入与现场。原未知结果保留,继续会创建新的运行。</p>}
|
||||
{job.installation.strategy && <div className="engine-prompt-note"><strong>Purge 提示实验 · {job.installation.strategy.source.version}</strong><p>本 Run 使用已封存工程提示,原审批与预算继续生效。</p><details><summary>查看本次实验策略</summary><dl><dt>策略 SHA256</dt><dd>{job.installation.strategy.sha256}</dd><dt>来源 SHA256</dt><dd>{job.installation.strategy.source.sourceSha256}</dd><dt>文本 SHA256</dt><dd>{job.installation.strategy.promptSha256}</dd><dt>来源目录</dt><dd>{job.installation.strategy.source.root}</dd></dl><pre>{job.installation.strategy.prompt}</pre></details></div>}
|
||||
{job.installation.strategy && <div className="engine-prompt-note"><strong>Purge {job.installation.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {job.installation.strategy.source.version}</strong><p>{job.installation.strategy.kind==='purge-original-restricted-v1'?'本 Run 加载固定原版入口,自动重试和继续关闭;工作台审批与预算继续生效。':'本 Run 使用已封存工程提示,原审批与预算继续生效。'}</p><details><summary>查看本次实验策略</summary><dl><dt>策略 SHA256</dt><dd>{job.installation.strategy.sha256}</dd><dt>来源 SHA256</dt><dd>{job.installation.strategy.source.sourceSha256}</dd><dt>文本 SHA256</dt><dd>{job.installation.strategy.promptSha256}</dd><dt>来源目录</dt><dd>{job.installation.strategy.source.root}</dd>{job.installation.strategy.kind==='purge-original-restricted-v1'&&<><dt>固定运行依赖 SHA256</dt><dd>{job.installation.strategy.runtime.sha256}</dd><dt>加载范围</dt><dd>{job.installation.strategy.runtime.inputs.length} 份固定输入 / {job.installation.strategy.runtime.nativeAddons.length} 个固定原生模块</dd></>}</dl><pre>{job.installation.strategy.prompt}</pre></details></div>}
|
||||
{job.review && <p className="engine-run-note">人工核对记录:<code>{job.review.evidenceSha256.slice(0, 16)}</code>。原未知输出未改写为完成。</p>}
|
||||
<div className="engine-run-actions"><button className="button secondary" disabled={pending} onClick={() => void read(job, 'input')}><FileText size={14} />查看原输入</button><button className="button secondary" disabled={pending || !job.reportArtifactId} onClick={() => void read(job, 'report')}><Fingerprint size={14} />查看原报告</button><button className="text-button" disabled={!job.reportArtifactId} onClick={() => void download(job)}><Download size={14} />下载完整报告</button></div>
|
||||
<details><summary>任务身份与来源</summary><dl><dt>Task</dt><dd>{job.taskId}</dd><dt>Run</dt><dd>{job.runId}</dd><dt>SDK 会话</dt><dd>{job.sdkSessionId}</dd><dt>安装目录</dt><dd>{job.installation.root}</dd><dt>输入 SHA256</dt><dd>{job.inputSha256}</dd><dt>报告 SHA256</dt><dd>{job.reportSha256 ?? '尚未封存'}</dd><dt>原事件</dt><dd>{job.nativeSummary.notifications} 项</dd></dl></details>
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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<PurgeSourceAvailability>('/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<PurgeSourceAvailability>('/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 <section className="purge-strategy-control" aria-label="Purge 提示实验">
|
||||
<header><FlaskConical size={17} /><label><input type="checkbox" checked={value.enabled} disabled={busy} onChange={event => enabled(event.target.checked)} />启用 Purge 提示实验</label><span>{value.enabled ? '仅对本计划生效' : '默认关闭'}</span></header>
|
||||
<p>追加已封存的工程提示,继续使用原任务范围、检查审批和累计预算。实际收益需同题对照验证。</p>
|
||||
const original=value.kind==='purge-original-restricted-v1';
|
||||
return <section className="purge-strategy-control" aria-label={original?'Purge 原版受限模式':'Purge 提示实验'}>
|
||||
<header><FlaskConical size={17} /><label><input type="checkbox" checked={value.enabled} disabled={busy} onChange={event => enabled(event.target.checked)} />启用 Purge {original?'原版受限模式':'提示实验'}</label><span>{value.enabled ? '仅对本计划生效' : '默认关闭'}</span></header>
|
||||
<p>{original?'运行原版 1.1.78 的固定受限配置,继续使用工作台的工具审批和累计预算。原版效果需另行实测。':'追加已封存的工程提示,继续使用原任务范围、检查审批和累计预算。实际收益需同题对照验证。'}</p>
|
||||
{value.enabled && <div className="purge-strategy-fields">
|
||||
<label>执行模式<select aria-label="Purge 执行模式" value={value.kind} disabled={busy} onChange={event=>{request.current++;setDetecting(false);setError('');onChange({...value,kind:event.target.value as PurgeDraft['kind'],source:null});}}>
|
||||
<option value="purge-prompt-experiment">独立工程提示 · 不加载原版插件</option><option value="purge-original-restricted-v1">原版 1.1.78 · 固定受限配置</option>
|
||||
</select></label>
|
||||
<label>Purge 源码目录<input aria-label="Purge 源码目录" value={value.root} placeholder="留空检测已知来源,或填写绝对目录" disabled={busy} onChange={event => editRoot(event.target.value)} /></label>
|
||||
<button type="button" className="button secondary" disabled={busy || detecting} onClick={() => void detect()}>{detecting ? <LoaderCircle className="spin" size={14} /> : <ShieldCheck size={14} />}检测 Purge 来源</button>
|
||||
{value.source && <div className="purge-source-state" role="status"><strong>{value.source.status === 'available' ? '已核对 Purge ' + value.source.version : '来源尚不可用'}</strong><p>{value.source.message}</p>{value.source.sourceSha256 && <code>{value.source.sourceSha256}</code>}</div>}
|
||||
{value.source && <div className="purge-source-state" role="status"><strong>{value.source.status === 'available' ? '已核对 Purge ' + value.source.version : '来源尚不可用'}</strong><p>{value.source.message}</p>{value.source.sourceSha256 && <code>{value.source.sourceSha256}</code>}{original&&value.source.runtimeSha256&&<p>固定运行依赖 {value.source.runtimeInputs} 份 · <code>{value.source.runtimeSha256}</code></p>}</div>}
|
||||
{error && <p className="purge-source-error" role="alert">{error}</p>}
|
||||
<label>增强工程提示<textarea aria-label="增强工程提示" rows={5} maxLength={8000} value={value.prompt} disabled={busy} onChange={event => onChange({ ...value, prompt: event.target.value })} /></label>
|
||||
<small>{new TextEncoder().encode(value.prompt).length.toLocaleString()} / 24,000 字节 · 完整文本随计划保存,运行期间不能替换。</small>
|
||||
<details><summary>实验来源与执行范围</summary><p>独立提示装配参考 YuJunZhiXue / dsh-purge(Apache-2.0)。不加载上游完整插件;实验不开启宿主修改、权限绕过或自动重试。</p>{value.source?.inputs && <dl>{value.source.inputs.map(input => <div key={input.relative}><dt>{input.relative}</dt><dd>{input.sha256}</dd></div>)}</dl>}</details>
|
||||
<details><summary>实验来源与执行范围</summary><p>{original?'YuJunZhiXue / dsh-purge(Apache-2.0)原版入口,完整来源和运行副本逐份核对。自动更新、宿主修改、原版工具、自动重试和继续关闭;内部提示及钩子仍由原版装配。这是固定可信源码的 Windows x64 配置,Node 权限不等同于操作系统沙箱。':'独立提示装配参考 YuJunZhiXue / dsh-purge(Apache-2.0)。不加载上游完整插件;实验不开启宿主修改、权限绕过或自动重试。'}</p>{value.source?.inputs && <dl className="purge-source-inputs">{value.source.inputs.map(input => <div key={input.relative}><dt>{input.relative}</dt><dd>{input.sha256}</dd></div>)}</dl>}</details>
|
||||
</div>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowUpRight, Check, GitBranch, LoaderCircle, Play, RefreshCw, ShieldCheck, Square } from 'lucide-react';
|
||||
import { api, downloadBlob } from './api';
|
||||
import { Modal } from './components';
|
||||
import { PurgeStrategyControl, emptyPurgeDraft, purgeDraftReady } from './PurgeStrategyControl';
|
||||
import { PurgeStrategyControl, emptyPurgeDraft, purgeDraftReady, purgeStrategyInput } from './PurgeStrategyControl';
|
||||
import type { CollaborationGroup, Config, Session, WorkerView, ControlledEngineAvailability } from './types';
|
||||
import './WorkerPanel.css';
|
||||
|
||||
@@ -59,7 +59,7 @@ export function WorkerPanel({ session, config, busy, onSession, onNavigate, onRe
|
||||
const result = await api<{ group: CollaborationGroup; session: Session }>('/sessions/' + session.id + '/collaborations', {
|
||||
goal, children: (engineMode === 'deepseek' ? drafts.slice(0, 1) : drafts).map(child => ({ label: child.label, goal: child.goal, paths: splitPaths(child.paths) })),
|
||||
...(engineMode === 'deepseek' ? { engine: { id: 'deepseek-harness', root: engineInstallation?.root, controlledSha256: engineInstallation?.controlledSha256,
|
||||
...(purge.enabled ? { strategy: { kind: 'purge-prompt-experiment', root: purge.source?.root, sourceSha256: purge.source?.sourceSha256, prompt: purge.prompt } } : {}) } } : {}),
|
||||
...(purge.enabled ? { strategy: purgeStrategyInput(purge) } : {}) } } : {}),
|
||||
budget: { maxTokens: tokens, maxSteps: steps, maxToolCalls: toolCalls, maxDurationMs: duration * 60000 },
|
||||
});
|
||||
if (generation !== scope.current) return;
|
||||
@@ -95,7 +95,7 @@ export function WorkerPanel({ session, config, busy, onSession, onNavigate, onRe
|
||||
{(!group || creating) && <div className="worker-plan-form">
|
||||
<label>执行方式<select aria-label="执行方式" value={engineMode} onChange={event => setEngineMode(event.target.value as 'workbench' | 'deepseek')}><option value="workbench">工作台 · 两个受限子任务</option><option value="deepseek">DeepSeek Harness · 一个受控工程</option></select></label>
|
||||
{engineMode === 'deepseek' && <section className="worker-engine-install" aria-label="受控引擎安装"><label>Harness 安装目录<input value={engineRoot} placeholder="留空检测已知本地安装" onChange={event => { detection.current++; setEngineRoot(event.target.value); setEngineInstallation(null); setDetectingEngine(false); }} /></label><button className="button secondary" disabled={detectingEngine || !!action} onClick={() => void detectEngine()}>{detectingEngine ? <LoaderCircle size={14} className="spin" /> : <ShieldCheck size={14} />}检测受控安装</button>{engineInstallation && <div role="status"><strong>{engineReady ? '受控安装可用' : '安装尚不可用'}</strong><p>{engineInstallation.message}</p>{engineReady && <code>Harness {engineInstallation.version} · {engineInstallation.controlledSha256?.slice(0, 16)}</code>}</div>}<p className="worker-note">模型连接由工作台使用;引擎只提交范围内的提案与检查请求,应用和检查仍需审查。</p></section>}
|
||||
{engineMode === 'deepseek' && <PurgeStrategyControl value={purge} onChange={value => { setPurge(value); setError(''); }} busy={!!action} />}
|
||||
{engineMode === 'deepseek' && <PurgeStrategyControl value={purge} onChange={value => { setPurge(value); setError(''); }} busy={!!action} harnessRoot={engineInstallation?.root} />}
|
||||
<label>父目标<textarea value={goal} onChange={event => setGoal(event.target.value)} placeholder="描述需要交付的结果与验收要求" maxLength={20000} rows={3} /></label>
|
||||
<div className={'worker-lanes' + (engineMode === 'deepseek' ? ' single' : '')}>{visibleDrafts.map((child, index) => <fieldset key={index}><legend>{engineMode === 'deepseek' ? '引擎工程' : '子任务 ' + (index + 1)}</legend><label>任务名称<input value={child.label} maxLength={64} onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, label: event.target.value } : value))} /></label><label>独立子目标<textarea value={child.goal} maxLength={8000} rows={3} onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, goal: event.target.value } : value))} /></label><label>允许修改的文件或目录<textarea value={child.paths} rows={2} placeholder="例如 src/parser.mjs,每行一个相对路径" onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, paths: event.target.value } : value))} /></label></fieldset>)}</div>
|
||||
<div className="worker-budget-form"><label>总 token 预算<input type="number" min={1000} max={config.maxRunTokens} value={tokens} onChange={event => setTokens(Number(event.target.value))} /></label><label>总请求轮次<input type="number" min={2} max={200} value={steps} onChange={event => setSteps(Number(event.target.value))} /></label><label>总工具次数<input type="number" min={2} max={512} value={toolCalls} onChange={event => setToolCalls(Number(event.target.value))} /></label><label>总时限(分钟)<input type="number" min={1} max={Math.floor(config.maxRunDurationMs / 60000)} value={duration} onChange={event => setDuration(Number(event.target.value))} /></label></div>
|
||||
@@ -103,7 +103,7 @@ export function WorkerPanel({ session, config, busy, onSession, onNavigate, onRe
|
||||
<div className="worker-actions"><button className="button" disabled={!canPlan || !goal.trim() || visibleDrafts.some(child => !child.goal.trim() || !splitPaths(child.paths).length) || engineMode === 'deepseek' && (!engineReady || detectingEngine || !promptReady)} onClick={() => void create()}><ShieldCheck size={15} />封存分工计划</button>{creating && <button className="button secondary" onClick={() => setCreating(false)}>返回原协作</button>}</div>
|
||||
</div>}
|
||||
{group && !creating && <>
|
||||
{group.children[0]?.engine?.strategy && <p className="worker-engine-badge">本计划的 Purge 提示实验 · {group.children[0].engine.strategy.source.version} · {group.children[0].engine.strategy.sha256.slice(0, 16)}</p>}
|
||||
{group.children[0]?.engine?.strategy && <p className="worker-engine-badge">本计划的 Purge {group.children[0].engine.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {group.children[0].engine.strategy.source.version} · {group.children[0].engine.strategy.sha256.slice(0, 16)}</p>}
|
||||
{group.evaluation && <p className="worker-note">本协作属于固定工程评测。执行与采纳请使用「工程评测」;这里保留原任务导航和中断现场核对。</p>}<section className="worker-parent"><div className="worker-parent-top"><span className={'worker-status ' + (group.requiresVerification || group.status === 'conflict' ? 'attention' : '')}>{statusLabel(group.status)}</span><code>{group.source.identity.branch} · {group.source.identity.head.slice(0, 12)}</code></div><h3>{group.goal}</h3><p>{group.summary}</p><dl><div><dt>模型</dt><dd>{group.model.mode === 'demo' ? '离线演示' : group.model.model}</dd></div><div><dt>执行方式</dt><dd>{group.children[0].engine ? "DeepSeek Harness " + group.children[0].engine.version : "工作台受限子任务"}</dd></div><div><dt>总预算</dt><dd>{number(group.budget.maxTokens)} tokens / {group.budget.maxSteps} 轮 / {group.budget.maxToolCalls} 次工具</dd></div><div><dt>累计用量</dt><dd>{number(group.usage?.accountedTokens)} tokens / {group.usage?.steps ?? 0} 轮 / {group.usage?.toolCalls ?? 0} 次工具 / {group.usage?.requests ?? 0} 次模型请求</dd></div><div><dt>原修改</dt><dd>{group.source.changedPaths.length ? group.source.changedPaths.map(value => value.path).join('、') : '无未提交修改'}</dd></div></dl></section>
|
||||
<div className={"worker-lanes" + (group.children.length === 1 ? " single" : "")}>{(group.workers ?? []).map((child, index) => <section className="worker-lane" key={child.id}><div className="worker-lane-title"><span>通道 {index + 1}</span><span className={'worker-status ' + (child.requiresVerification ? 'attention' : '')}>{statusLabel(child.sessionStatus === 'awaiting_approval' ? 'awaiting_approval' : child.status)}</span></div><h3>{child.label}</h3>{child.engine && <p className="worker-engine-badge">DeepSeek Harness {child.engine.version} · 固定安装 {child.engine.controlledSha256?.slice(0, 12)}</p>}<p className="worker-goal">{child.goal}</p><div className="worker-scope"><span>允许修改</span>{child.paths.map(path => <code key={path}>{path}</code>)}</div><p className="worker-meter">{number(child.usage?.accountedTokens)} / {number(child.budget.maxTokens)} tokens · {child.usage?.steps ?? 0}/{child.budget.maxSteps} 轮</p><p className="worker-summary">{child.summary ?? '先创建独立工作区,再开始子任务。'}</p>{child.result && <div className="worker-proof"><Check size={14} />{child.result.paths.length} 个原改动 · 当前检查已封存</div>}<div className="worker-actions">{child.status !== 'unprepared' && <button className="button secondary" onClick={() => void onNavigate(child.projectId, child.sessionId, child.sessionStatus === "awaiting_approval" ? "approval" : child.sessionStatus === "needs_review" ? "changes" : "task")}>{child.sessionStatus === 'awaiting_approval' ? '查看并审批检查' : child.sessionStatus === 'needs_review' ? '审查子任务改动' : '打开子任务'}<ArrowUpRight size={13} /></button>}{!group.evaluation && ['ready', 'paused', 'failed', 'awaiting_review'].includes(child.status) && !running && child.sessionStatus !== 'needs_review' && <button className="text-button" disabled={!!action || config.mode === 'demo' || group.requiresVerification} onClick={() => setConfirmation({ group, operation: 'start', workerId: child.id })}><Play size={13} />继续子任务</button>}</div></section>)}</div>
|
||||
<section className="worker-review"><div className="worker-review-title"><GitBranch size={18} /><h3>父工程成果审查</h3></div>{group.collection ? <><p>{group.collection.paths.length} 个路径已核对,原记录 <code>{group.collection.sha256.slice(0, 16)}</code></p>{group.collection.conflicts.length > 0 && <ul className="worker-conflicts">{group.collection.conflicts.map((conflict, i) => <li key={i}><code>{conflict.path}</code><span>{conflict.reason}</span></li>)}</ul>}<button className="text-button" disabled={!!action} onClick={() => void showRecord(group, 'collection')}>查看原成果记录</button></> : <p>等待 {group.children.length} 个子任务完成实际修改与检查。重叠路径、来源变化或原证据失效会阻止合并。</p>}{group.merge?.changeSetId && <button className="button secondary" onClick={onReview}>打开父工程变更集审查<ArrowUpRight size={14} /></button>}</section>
|
||||
|
||||
+8
-1
@@ -303,18 +303,25 @@ export interface EngineJob {
|
||||
export interface ControlledEngineAvailability extends EngineAvailability {
|
||||
controlledStatus: string; controlledSha256?: string; scope: string; bridgeSha256?: string;
|
||||
controlledCapabilities?: { text: boolean; nativeSessionResume: boolean; nativeModelCredentials: boolean; cancellationUnit: string };
|
||||
strategy?: PurgePromptStrategy;
|
||||
strategy?: PurgePromptStrategy | PurgeOriginalStrategy;
|
||||
}
|
||||
export interface PurgeSourceAvailability {
|
||||
status: string; root: string | null; message: string; version?: string; sourceSha256?: string;
|
||||
defaultEnabled: boolean; defaultPrompt: string; supportedVersions: string[];
|
||||
inputs?: { relative: string; path: string; bytes: number; sha256: string }[];
|
||||
kind?: 'purge-prompt-experiment' | 'purge-original-restricted-v1'; runtimeSha256?: string; runtimeInputs?: number;
|
||||
}
|
||||
export interface PurgePromptStrategy {
|
||||
kind: 'purge-prompt-experiment'; enabled: true; sha256: string; prompt: string; promptSha256: string;
|
||||
source: { root: string; version: string; sourceSha256: string };
|
||||
section: { name: string; order: number; interpolate: false; text: string; textSha256: string };
|
||||
}
|
||||
export interface PurgeOriginalStrategy {
|
||||
kind: 'purge-original-restricted-v1'; enabled: true; sha256: string; prompt: string; promptSha256: string;
|
||||
source: { root: string; version: string; sourceSha256: string };
|
||||
runtime: { root: string; sha256: string; inputs: { path: string; sha256: string }[]; nativeAddons: { path: string; sha256: string }[] };
|
||||
originalConfig: { autoRetry: false; autoContinue: false; hooksDenyBypass: false; postPrompt: string };
|
||||
}
|
||||
export interface EngineRunView {
|
||||
id: string; projectId: string; sessionId: string; taskId: string; runId: string; workerId: string; collaborationId: string;
|
||||
installation: ControlledEngineAvailability; sdkSessionId: string; status: string; requiresVerification: boolean; verified: boolean;
|
||||
|
||||
@@ -9,7 +9,8 @@ import { isId } from '../../shared/contracts/execution.mjs';
|
||||
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
|
||||
import { CONTROLLED_BRIDGE_PLUGIN } from './controlled-plugin.mjs';
|
||||
import { assertControlledInstallation, controlledDigest, controlledPatch, controlledToolCatalogue, CONTROLLED_ENGINE_SCOPE } from './controlled-installation.mjs';
|
||||
import { assertPurgeStrategy } from './purge-strategy.mjs';
|
||||
import { assertPurgeStrategy, PURGE_PROMPT_KIND, ORIGINAL_PURGE_KIND } from './purge-strategy.mjs';
|
||||
import { OriginalPurgeRuntime } from './original-purge-runtime.mjs';
|
||||
|
||||
const allowedEnvironment = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i;
|
||||
const at = () => new Date().toISOString();
|
||||
@@ -51,7 +52,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
const pluginConfig = { owner: this.owner, sdkSessionId, tools: catalogue, catalogueSha256, nonce, marker,
|
||||
llmModule: this.installation.llmModule, endpoint: 'http://127.0.0.1:' + this.guard.address().port,
|
||||
maximumFrameBytes: this.maximumFrameBytes, model: config.model, maxOutputTokens: config.maxOutputTokens, contextLimit: config.contextLimit,
|
||||
...(strategy ? { promptExperiment: { sha256: strategy.sha256, section: strategy.section } } : {}) };
|
||||
...(strategy?.kind===PURGE_PROMPT_KIND ? { promptExperiment: { sha256: strategy.sha256, section: strategy.section } } : {}) };
|
||||
fs.writeFileSync(plugin, CONTROLLED_BRIDGE_PLUGIN, { flag: 'wx' }); fs.writeFileSync(patch, JSON.stringify(controlledPatch(plugin, pluginConfig)), { flag: 'wx' });
|
||||
this.report.launchInputs = { plugin: engineFileIdentity(plugin), patch: engineFileIdentity(patch), cwd: fs.realpathSync.native(cwd),
|
||||
disabledPlugins: this.installation.disabledPlugins, catalogue, catalogueSha256 };
|
||||
@@ -59,8 +60,12 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
for (const name of Object.keys(process.env)) if (allowedEnvironment.test(name)) env[name] = process.env[name];
|
||||
Object.assign(env, { DSH_HOME: home, DSH_AGENTS_HOME: agents, DSH_TELEMETRY_DISABLED: 'true' });
|
||||
signal?.throwIfAborted(); assertControlledInstallation(this.installation);
|
||||
this.client = this.clientFactory({ executable: this.installation.node.path,
|
||||
args: [this.installation.entry, '--profile', this.installation.profile, '--patch', patch], cwd, env },
|
||||
let launch={executable:this.installation.node.path,args:[this.installation.entry,'--profile',this.installation.profile,'--patch',patch],cwd,env};
|
||||
if(strategy?.kind===ORIGINAL_PURGE_KIND){
|
||||
this.originalPurge=new OriginalPurgeRuntime(strategy,directory);this.report.originalPurge=this.originalPurge.report;
|
||||
launch=await this.originalPurge.prepare(launch,this.installation);this.report.launchInputs.patch=engineFileIdentity(patch);
|
||||
}
|
||||
this.client = this.clientFactory(launch,
|
||||
{ timeoutMs: this.timeoutMs, maximumFrameBytes: this.maximumFrameBytes, cancellationMethod: null });
|
||||
this.report.process = { pid: this.client.pid, connectionId: this.client.id, startedAt: this.client.startedAt, ownership: 'one-process-per-engine-run' };
|
||||
onState('starting', this.report.process);
|
||||
@@ -95,7 +100,8 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
if (controlledDigest(ready.owner) !== controlledDigest(this.owner) || ready.sdkSessionId !== sdkSessionId
|
||||
|| ready.catalogueSha256 !== catalogueSha256 || controlledDigest(ready.catalogue) !== catalogueSha256
|
||||
|| JSON.stringify(ready.providers) !== JSON.stringify(['agent-workbench'])
|
||||
|| (ready.promptExperimentSha256 ?? null) !== (strategy?.sha256 ?? null)) throw engineError('启动后工具、模型、实验提示或Run目录不符合封存契约。');
|
||||
|| (ready.promptExperimentSha256 ?? null) !== (strategy?.kind===PURGE_PROMPT_KIND?strategy.sha256:null)) throw engineError('启动后工具、模型、实验提示或Run目录不符合封存契约。');
|
||||
this.originalPurge?.verify({ready:true,pid:this.client.pid});
|
||||
this.verifyLaunch(); onState('initializing', { readiness: ready });
|
||||
const initialized = await this.request('initialize', { cwd, provider: 'agent-workbench', model: config.model, maxTokens: config.maxOutputTokens });
|
||||
if (controlledDigest(initialized.serverInfo) !== controlledDigest(this.installation.serverInfo)) throw engineError('受控SDK返回身份不符合固定发行。');
|
||||
@@ -109,6 +115,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
for (const input of [this.report.launchInputs.plugin, this.report.launchInputs.patch]) {
|
||||
if (engineFileIdentity(input.path).sha256 !== input.sha256) throw engineError('所属叠加插件或启动输入发生变化。');
|
||||
}
|
||||
this.originalPurge?.verify();
|
||||
}
|
||||
async captureTree(publish = true) {
|
||||
const info = this.report.process, tree = await this.processTreeReader(info);
|
||||
@@ -211,6 +218,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
}
|
||||
if (this.guard) { this.guard.closeAllConnections(); await new Promise(resolve => this.guard.close(resolve)); }
|
||||
await Promise.allSettled([...this.pending]);
|
||||
if(this.originalPurge){try{this.originalPurge.verify();}catch(error){failure??=error;}finally{await this.originalPurge.close();}}
|
||||
if (!interrupted && this.report.launchInputs) { try { this.verifyLaunch(); } catch (error) { failure ??= error; } }
|
||||
if (!interrupted && this.report.cleanup?.exit?.code !== 0) failure ??= engineError('所属引擎未正常退出。');
|
||||
this.report.finishedAt = at(); this.report.status = this.client && (!this.report.cleanup?.rootExited || !this.report.cleanup?.treeConfirmed)
|
||||
|
||||
@@ -32,7 +32,7 @@ export class EngineRunner {
|
||||
if (installation.controlledStatus !== 'available' || installation.controlledSha256 !== input.controlledSha256) {
|
||||
throw engineError('受控引擎与刚才检测的程序/插件身份不一致,请重新检测后制定新计划。');
|
||||
}
|
||||
return { ...installation, ...(input.strategy === undefined ? {} : { strategy: selectPurgeStrategy(input.strategy, this.appDirectory) }) };
|
||||
return { ...installation, ...(input.strategy === undefined ? {} : { strategy: selectPurgeStrategy(input.strategy, this.appDirectory, installation) }) };
|
||||
}
|
||||
assertCurrent(session, run) {
|
||||
const driver = this.drivers.get(run.id);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,205 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import {createHash,randomUUID,timingSafeEqual} from 'node:crypto';
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import {engineCanonicalDigest as digest,engineError} from '../../shared/contracts/engines.mjs';
|
||||
import {engineFileIdentity} from './deepseek-installation.mjs';
|
||||
import {assertOriginalPurgeStrategy} from './original-purge-source.mjs';
|
||||
|
||||
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
||||
const equal=(left,right)=>typeof left==='string'&&Buffer.byteLength(left)===Buffer.byteLength(right)&&timingSafeEqual(Buffer.from(left),Buffer.from(right));
|
||||
export function originalPurgeReadRoots(directories,metadata=[]){
|
||||
const inside=(base,file)=>{const relative=path.relative(base,file);return relative===''||relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);};
|
||||
const roots=[...new Set(directories.map(root=>fs.realpathSync.native(root)))];
|
||||
// Node 24's Windows permission trie can deny an allowed ancestor when both
|
||||
// it and a descendant are supplied. Keep only the encompassing read grant.
|
||||
const minimal=roots.filter(root=>!roots.some(other=>other!==root&&inside(other,root)));
|
||||
return [...minimal,...new Set(metadata.filter(file=>!minimal.some(root=>inside(root,file))))];
|
||||
}
|
||||
|
||||
export const ORIGINAL_PURGE_WRAPPER=String.raw`import fs from 'node:fs';
|
||||
export const name='workbench-original-purge-restricted';
|
||||
export const inject=['systemPrompt','tools','appReady'];
|
||||
export async function apply(ctx,config){
|
||||
const blockedTools=[];
|
||||
const tools=new Proxy(ctx.tools,{get(target,key){if(key==='register')return definition=>{
|
||||
if(!['purge_status','purge_apply','purge_revert'].includes(definition.name))throw new Error('Unexpected original tool registration.');
|
||||
blockedTools.push(definition.name);return ()=>{};
|
||||
};const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;}});
|
||||
const facade=new Proxy(ctx,{get(target,key){if(key==='tools')return tools;if(key==='get')return name=>name==='tools'?tools:target.get(name);
|
||||
const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;}});
|
||||
const original=await import(config.entry);await original.apply(facade,config.originalConfig);
|
||||
fs.writeFileSync(config.marker,JSON.stringify({schemaVersion:1,pid:process.pid,strategySha256:config.strategySha256,
|
||||
originalEntryLoaded:true,originalApplyCalled:true,blockedTools,originalConfig:config.originalConfig,upstreamPatchInstalled:false}),{flag:'wx'});
|
||||
}
|
||||
`;
|
||||
|
||||
// The only executable inputs allowed after this preload are the frozen original
|
||||
// files, pinned Harness JS/JSON and the two generated, hashed host adapters.
|
||||
// Node permissions are defense in depth for this trusted-source profile, not an
|
||||
// OS sandbox. Native builtins belong to the pinned Node executable. Only the
|
||||
// fixed require-builtin addon may use dlopen; it is recorded separately.
|
||||
export const ORIGINAL_PURGE_PRELOAD=String.raw`import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath,pathToFileURL} from 'node:url';
|
||||
import {registerHooks,syncBuiltinESMExports,createRequire} from 'node:module';
|
||||
import {createHash} from 'node:crypto';
|
||||
const policy=JSON.parse(fs.readFileSync(process.env.AWB_ORIGINAL_PURGE_POLICY,'utf8'));
|
||||
const originalRead=fs.readFileSync.bind(fs),inputs=new Map(policy.inputs.map(input=>[input.path,input])),seen=new Set();
|
||||
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
||||
const fileInput=url=>{if(!url.startsWith('file:'))throw new Error('Unsealed module protocol.');
|
||||
let file;try{file=fs.realpathSync.native(fileURLToPath(url));}catch(error){process.stderr.write('AWB_MODULE_LOOKUP_REFUSED '+url+'\n'+error.stack+'\n');throw error;}const input=inputs.get(file);
|
||||
if(!input||hash(originalRead(file))!==input.sha256){process.stderr.write('AWB_MODULE_REFUSED '+file+'\n');throw new Error('Unsealed or changed module: '+file);}return input;};
|
||||
const originalDlopen=process.dlopen;
|
||||
process.dlopen=function(module,file,...args){const input=fileInput(pathToFileURL(String(file)).href);
|
||||
if(!policy.nativeAddons.some(native=>native.path===input.path&&native.sha256===input.sha256))throw Object.assign(new Error('Unsealed native addon.'),{code:'ERR_ACCESS_DENIED'});
|
||||
const result=originalDlopen.call(this,module,file,...args);
|
||||
fs.appendFileSync(policy.nativeModules,JSON.stringify({...input,operation:'actual-process-dlopen'})+'\n');return result;};
|
||||
registerHooks({resolve(specifier,context,next){
|
||||
if(context.parentURL?.startsWith(policy.originalUrl)&&specifier==='@deepseek-ai/dsh-llm')return {url:policy.llmModule,shortCircuit:true};
|
||||
const result=next(specifier,context);if(!result.url.startsWith('node:'))fileInput(result.url);return result;
|
||||
},load(url,context,next){
|
||||
if(url.startsWith('node:'))return next(url,context);
|
||||
const input=fileInput(url),result=next(url,context),source=result.source==null?null:Buffer.from(result.source);
|
||||
if(source&&hash(source)!==input.sha256)throw new Error('Loaded source differs from sealed bytes.');
|
||||
if(!seen.has(input.path)){
|
||||
if(seen.size>=1024)throw new Error('Loaded module count exceeded.');seen.add(input.path);
|
||||
fs.appendFileSync(policy.modules,JSON.stringify({...input,format:result.format??null,sourceSha256:source?hash(source):null})+'\n');
|
||||
}return result;
|
||||
}});
|
||||
const koffiModule=createRequire(import.meta.url)(policy.koffiEntry),koffi=koffiModule.default??koffiModule,originalLibraryLoad=koffi.load.bind(koffi);
|
||||
koffi.load=function(name,...args){const library=policy.platformLibraries.find(input=>name.toLowerCase()===input.name||name===input.path);
|
||||
if(!library||hash(originalRead(library.path))!==library.sha256)throw new Error('Unsealed native library.');
|
||||
const result=originalLibraryLoad(library.path,...args);
|
||||
fs.appendFileSync(policy.nativeLibraries,JSON.stringify({...library,operation:'actual-koffi-load'})+'\n');return result;};
|
||||
const delegatedStat=(file,options)=>{if(options?.bigint)return null;const item=policy.directoryMetadata[path.resolve(String(file))];
|
||||
if(!item)return null;const value=Object.assign(Object.create(fs.Stats.prototype),item);
|
||||
for(const key of ['atime','mtime','ctime','birthtime'])value[key]=new Date(value[key]);return value;};
|
||||
let deniedCount=0;const logDenied=(name,file,error)=>{if(error?.code==='ERR_ACCESS_DENIED'&&deniedCount++<24)process.stderr.write('AWB_ACCESS_REFUSED '+name+' '+String(file)+' resource='+String(error.resource)+'\n'+error.stack+'\n');};
|
||||
for(const name of ['statSync','lstatSync','readFileSync','realpathSync','readdirSync','accessSync']){const original=fs[name];
|
||||
const wrapped=function(file,...args){try{return original.call(this,file,...args);}catch(error){logDenied(name,file,error);throw error;}};
|
||||
Object.assign(wrapped,original);fs[name]=wrapped;}
|
||||
for(const name of ['readFile','stat','lstat','realpath','readdir','access','open']){const original=fs[name];
|
||||
const wrap=fn=>function(file,...args){const callback=args.at(-1);if(typeof callback==='function')args[args.length-1]=function(error,...values){logDenied(name,file,error);return callback.call(this,error,...values);};
|
||||
try{return fn.call(this,file,...args);}catch(error){logDenied(name,file,error);throw error;}};
|
||||
const wrapped=wrap(original);Object.assign(wrapped,original);if(original.native)wrapped.native=wrap(original.native);fs[name]=wrapped;}
|
||||
const stat=fs.promises.stat;fs.promises.stat=async function(file,options){try{return await stat.call(this,file,options);}catch(error){
|
||||
const value=error.code==='ERR_ACCESS_DENIED'&&delegatedStat(file,options);if(value)return value;logDenied('promises.stat',file,error);throw error;}};
|
||||
for(const name of ['lstat','readFile','realpath','readdir','access','mkdir','opendir']){const original=fs.promises[name];fs.promises[name]=async function(file,...args){
|
||||
try{return await original.call(this,file,...args);}catch(error){logDenied('promises.'+name,file,error);throw error;}};}
|
||||
const open=fs.promises.open;fs.promises.open=async function(file,...args){let handle;try{handle=await open.call(this,file,...args);}catch(error){logDenied('promises.open',file,error);throw error;}const sync=handle.sync.bind(handle);
|
||||
handle.sync=async()=>{try{return await sync();}catch(error){if(error.code!=='ERR_ACCESS_DENIED')throw error;
|
||||
const stat=await handle.stat({bigint:true}),response=await fetch(policy.durabilityEndpoint,{method:'POST',signal:AbortSignal.timeout(10000),
|
||||
headers:{'Content-Type':'application/json',Authorization:'Bearer '+process.env.AWB_ORIGINAL_PURGE_DURABILITY_NONCE},
|
||||
body:JSON.stringify({path:String(file),dev:String(stat.dev),ino:String(stat.ino),size:String(stat.size)})});
|
||||
if(!response.ok)throw new Error('Owned durability synchronization refused.');await response.json();
|
||||
}};return handle;};
|
||||
syncBuiltinESMExports();
|
||||
`;
|
||||
|
||||
export class OriginalPurgeRuntime {
|
||||
constructor(strategy,directory){
|
||||
assertOriginalPurgeStrategy(strategy);this.strategy=strategy;this.directory=fs.realpathSync.native(directory);this.inputs=[];
|
||||
this.report={schemaVersion:1,kind:strategy.kind,strategySha256:strategy.sha256,runtimeSha256:strategy.runtime.sha256,
|
||||
isolation:strategy.isolation,originalConfig:strategy.originalConfig,upstreamPatchInstalled:false,
|
||||
durabilityReceipts:[],durabilityRejections:[],loadedModules:[],nativeLoads:[],nativeLibraries:[],readiness:null};
|
||||
}
|
||||
async prepare(launch,installation){
|
||||
const directory=this.directory,source=path.join(directory,'original-purge');fs.mkdirSync(source);
|
||||
for(const input of this.strategy.source.inputs){
|
||||
const raw=fs.readFileSync(input.path);if(sha(raw)!==input.sha256)throw engineError('复制前原版输入已变化。');
|
||||
const target=path.join(source,input.relative);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,raw,{flag:'wx'});
|
||||
this.inputs.push({...engineFileIdentity(target),relative:input.relative});
|
||||
}
|
||||
this.marker=path.join(directory,'original-purge-ready.json');this.modules=path.join(directory,'original-purge-modules.jsonl');this.nativeModules=path.join(directory,'original-purge-native-modules.jsonl');
|
||||
this.nativeLibraries=path.join(directory,'original-purge-native-libraries.jsonl');
|
||||
const wrapper=path.join(directory,'original-purge-wrapper.mjs'),preload=path.join(directory,'original-purge-preload.mjs'),policyFile=path.join(directory,'original-purge-policy.json');
|
||||
fs.writeFileSync(wrapper,ORIGINAL_PURGE_WRAPPER,{flag:'wx'});fs.writeFileSync(preload,ORIGINAL_PURGE_PRELOAD,{flag:'wx'});
|
||||
const nonce=randomUUID();this.server=http.createServer((request,response)=>this.handleDurability(request,response,nonce));
|
||||
await new Promise((resolve,reject)=>{this.server.once('error',reject);this.server.listen(0,'127.0.0.1',resolve);});
|
||||
const directoryMetadata={};
|
||||
for(let ancestor=path.dirname(directory);;ancestor=path.dirname(ancestor)){
|
||||
if(fs.lstatSync(ancestor).isSymbolicLink())throw engineError('所属运行目录祖先不能是链接。');
|
||||
const stat=fs.statSync(ancestor);directoryMetadata[ancestor]=stat;directoryMetadata[path.toNamespacedPath(ancestor)]=stat;
|
||||
if(path.dirname(ancestor)===ancestor)break;
|
||||
}
|
||||
const patchFile=launch.args.at(-1),patch=JSON.parse(fs.readFileSync(patchFile));
|
||||
patch.push({insert:[{id:'workbench-original-purge-restricted',name:wrapper,config:{entry:pathToFileURL(path.join(source,'lib/index.js')).href,
|
||||
originalConfig:this.strategy.originalConfig,strategySha256:this.strategy.sha256,marker:this.marker}}]});fs.writeFileSync(patchFile,JSON.stringify(patch));
|
||||
const executableInputs=[...this.strategy.runtime.inputs,...this.inputs,engineFileIdentity(wrapper),engineFileIdentity(path.join(directory,'bridge.mjs'))];
|
||||
this.expectedModules=new Map(executableInputs.map(input=>[input.path,input]));
|
||||
const policy={schemaVersion:1,inputs:executableInputs,modules:this.modules,nativeModules:this.nativeModules,nativeLibraries:this.nativeLibraries,
|
||||
platformLibraries:this.strategy.runtime.platformLibraries,koffiEntry:path.join(installation.root,'node_modules/.pnpm/koffi@3.1.1/node_modules/koffi/index.js'),
|
||||
nativeAddons:this.strategy.runtime.nativeAddons,directoryMetadata,
|
||||
originalUrl:pathToFileURL(source+path.sep).href,llmModule:installation.llmModule,durabilityEndpoint:'http://127.0.0.1:'+this.server.address().port+'/fsync'};
|
||||
fs.writeFileSync(policyFile,JSON.stringify(policy),{flag:'wx'});
|
||||
this.launchInputs=[engineFileIdentity(wrapper),engineFileIdentity(preload),engineFileIdentity(policyFile),...this.inputs];
|
||||
const metadataReads=[];
|
||||
for(const anchor of [installation.root,launch.cwd,source])for(let ancestor=path.dirname(anchor);;ancestor=path.dirname(ancestor)){
|
||||
metadataReads.push(path.join(ancestor,'node_modules','*'),path.join(ancestor,'package.json'));if(path.dirname(ancestor)===ancestor)break;
|
||||
}
|
||||
const readRoots=originalPurgeReadRoots([installation.root,path.dirname(installation.node.path),directory,launch.cwd],
|
||||
[...metadataReads,...this.strategy.runtime.platformLibraries.map(input=>input.path)]);
|
||||
launch.args=['--permission','--allow-addons',...[...new Set(readRoots)].flatMap(root=>['--allow-fs-read='+root,'--allow-fs-read='+path.toNamespacedPath(root)]),
|
||||
'--allow-fs-write='+directory,'--allow-fs-write='+path.toNamespacedPath(directory),'--import',pathToFileURL(preload).href,...launch.args];
|
||||
Object.assign(launch.env,{USERPROFILE:path.join(directory,'home'),APPDATA:path.join(directory,'home'),LOCALAPPDATA:path.join(directory,'home'),
|
||||
NARB_DISABLE_NATIVE_CACHE:'1',AWB_ORIGINAL_PURGE_POLICY:policyFile,AWB_ORIGINAL_PURGE_DURABILITY_NONCE:nonce});
|
||||
this.report.launchInputs=this.launchInputs;this.report.originalCopies=this.inputs;
|
||||
this.report.permissionPolicy={readRoots,writeRoot:directory,arguments:launch.args,cwd:launch.cwd,nativeCache:false};
|
||||
return launch;
|
||||
}
|
||||
async handleDurability(request,response,nonce){
|
||||
try{
|
||||
if(this.closed||request.method!=='POST'||request.url!=='/fsync'||request.headers.origin!==undefined||request.headers['content-type']!=='application/json'
|
||||
||!equal(request.headers.authorization,'Bearer '+nonce))throw engineError('同步请求不属于当前运行。');
|
||||
const chunks=[];let size=0;for await(const chunk of request){size+=chunk.length;if(size>4096)throw engineError('同步输入超限。');chunks.push(chunk);}
|
||||
const value=JSON.parse(Buffer.concat(chunks)),file=path.resolve(value.path);
|
||||
if(Object.keys(value).sort().join(',')!=='dev,ino,path,size'||!file.startsWith(this.directory+path.sep)||fs.realpathSync.native(file)!==file)throw engineError('同步路径不属于运行目录。');
|
||||
for(let current=file;current!==this.directory;current=path.dirname(current))if(fs.lstatSync(current).isSymbolicLink())throw engineError('同步路径不能经过链接。');
|
||||
const fd=fs.openSync(file,'r+');try{
|
||||
const stat=fs.fstatSync(fd,{bigint:true});if(!stat.isFile()||stat.size>64n*1024n*1024n)throw engineError('同步文件超限。');
|
||||
for(const key of ['dev','ino','size'])if(String(stat[key])!==value[key])throw engineError('同步文件身份已变化。');
|
||||
fs.fsyncSync(fd);const bytes=fs.readFileSync(fd);
|
||||
if(BigInt(bytes.length)!==stat.size)throw engineError('同步期间文件发生变化。');
|
||||
this.report.durabilityReceipts.push({path:path.relative(this.directory,file),dev:value.dev,ino:value.ino,size:value.size,sha256:sha(bytes),operation:'actual-parent-fsync'});
|
||||
}finally{fs.closeSync(fd);}
|
||||
response.writeHead(200,{'Content-Type':'application/json',Connection:'close'});response.end('{"flushed":true}');
|
||||
}catch(error){this.report.durabilityRejections.push({at:new Date().toISOString(),reason:error.message});
|
||||
if(!response.destroyed){response.writeHead(409,{'Content-Type':'application/json',Connection:'close'});response.end('{"error":"Owned durability request refused"}');}}
|
||||
}
|
||||
verify({ready=false,pid=null}={}){
|
||||
assertOriginalPurgeStrategy(this.strategy);
|
||||
for(const input of this.launchInputs??[])if(engineFileIdentity(input.path).sha256!==input.sha256)throw engineError('所属原版运行副本或适配输入已变化。',409,'ENGINE_INPUT_CHANGED');
|
||||
if(ready||this.report.readiness){
|
||||
const marker=JSON.parse(fs.readFileSync(this.marker));
|
||||
if(marker.schemaVersion!==1||marker.pid!==(pid??this.report.readiness?.pid)||marker.strategySha256!==this.strategy.sha256
|
||||
||marker.originalEntryLoaded!==true||marker.originalApplyCalled!==true||marker.upstreamPatchInstalled!==false
|
||||
||digest(marker.originalConfig)!==digest(this.strategy.originalConfig)
|
||||
||digest([...marker.blockedTools].sort())!==digest(['purge_apply','purge_revert','purge_status']))throw engineError('原版入口、受限配置或外部工具门控不符合封存策略。');
|
||||
this.report.readiness=marker;
|
||||
}
|
||||
if(fs.existsSync(this.modules)){
|
||||
if(fs.statSync(this.modules).size>4*1024*1024)throw engineError('原版模块收据超限。');
|
||||
const lines=fs.readFileSync(this.modules,'utf8').trimEnd().split('\n');
|
||||
this.report.loadedModules=lines.filter(Boolean).map(line=>{const item=JSON.parse(line),expected=this.expectedModules.get(item.path);
|
||||
if(!expected||item.sha256!==expected.sha256||item.bytes!==expected.bytes||item.sourceSha256!==null&&item.sourceSha256!==expected.sha256)throw engineError('实际加载模块与封存输入不符。');return item;});
|
||||
if(this.report.loadedModules.length>1024)throw engineError('原版模块收据数量超限。');
|
||||
}
|
||||
if(fs.existsSync(this.nativeModules)){
|
||||
if(fs.statSync(this.nativeModules).size>65536)throw engineError('原生加载收据超限。');
|
||||
this.report.nativeLoads=fs.readFileSync(this.nativeModules,'utf8').trimEnd().split('\n').filter(Boolean).map(line=>{const item=JSON.parse(line);
|
||||
if(!this.strategy.runtime.nativeAddons.some(expected=>expected.path===item.path&&expected.sha256===item.sha256&&expected.bytes===item.bytes)
|
||||
||item.operation!=='actual-process-dlopen')throw engineError('实际原生加载不属于固定清单。');return item;});
|
||||
}
|
||||
if(fs.existsSync(this.nativeLibraries)){
|
||||
if(fs.statSync(this.nativeLibraries).size>65536)throw engineError('原生库加载收据超限。');
|
||||
this.report.nativeLibraries=fs.readFileSync(this.nativeLibraries,'utf8').trimEnd().split('\n').filter(Boolean).map(line=>{const item=JSON.parse(line);
|
||||
if(!this.strategy.runtime.platformLibraries.some(expected=>expected.path===item.path&&expected.sha256===item.sha256&&expected.bytes===item.bytes)
|
||||
||item.operation!=='actual-koffi-load')throw engineError('实际原生库加载不属于固定清单。');return item;});
|
||||
}
|
||||
if(ready&&this.report.nativeLoads.length!==this.strategy.runtime.nativeAddons.length)throw engineError('未核对固定原生模块的实际加载。');
|
||||
return this.report;
|
||||
}
|
||||
async close(){if(this.closed)return;this.closed=true;if(this.server){this.server.closeAllConnections();await new Promise(resolve=>this.server.close(resolve));}}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {createHash} from 'node:crypto';
|
||||
import lock from './original-purge-lock.json' with {type:'json'};
|
||||
import {engineCanonicalDigest as digest,engineError} from '../../shared/contracts/engines.mjs';
|
||||
import {engineFileIdentity} from './deepseek-installation.mjs';
|
||||
|
||||
export const ORIGINAL_PURGE_KIND='purge-original-restricted-v1';
|
||||
export const ORIGINAL_PURGE_LOCK_SHA256=digest(lock);
|
||||
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
||||
const changed=message=>engineError(message,409,'ENGINE_INPUT_CHANGED');
|
||||
function directory(root){
|
||||
if(typeof root!=='string'||!path.isAbsolute(root)||!fs.lstatSync(root).isDirectory()||fs.lstatSync(root).isSymbolicLink())throw changed('原版来源需要普通绝对目录。');
|
||||
return fs.realpathSync.native(root);
|
||||
}
|
||||
function pinnedInputs(root,expected,{original=false}={}){
|
||||
const inputs=expected.map(input=>{
|
||||
const file=path.join(root,input.relative),identity=engineFileIdentity(file,8*1024*1024);
|
||||
if(!identity.path.startsWith(root+path.sep)||identity.bytes!==input.bytes||identity.sha256!==input.sha256)throw changed('固定原版输入已变化:'+input.relative);
|
||||
if(original){
|
||||
for(let current=file;current!==root;current=path.dirname(current))if(fs.lstatSync(current).isSymbolicLink())throw changed('原版输入不能经过链接。');
|
||||
}
|
||||
return {...identity,relative:input.relative};
|
||||
});
|
||||
if(original){
|
||||
const found=[];function walk(relative){const file=path.join(root,relative),stat=fs.lstatSync(file);
|
||||
if(stat.isSymbolicLink())throw changed('原版 lib 不能包含链接。');
|
||||
if(stat.isDirectory()){for(const name of fs.readdirSync(file))walk(path.join(relative,name));}
|
||||
else if(stat.isFile())found.push(relative.replaceAll('\\','/'));else throw changed('原版 lib 包含非普通文件。');
|
||||
if(found.length>128)throw changed('原版 lib 文件数量超出固定版本。');
|
||||
}walk('lib');
|
||||
if(digest(found.sort())!==digest(expected.filter(item=>item.relative.startsWith('lib/')).map(item=>item.relative).sort()))throw changed('原版 lib 文件集合已变化。');
|
||||
}
|
||||
return inputs;
|
||||
}
|
||||
export function originalPurgeSource(root){
|
||||
root=directory(root);const inputs=pinnedInputs(root,lock.original,{original:true});
|
||||
const source={name:'dsh-purge',version:lock.purgeVersion,dshTarget:lock.harnessVersion,license:'Apache-2.0',attribution:'YuJunZhiXue / dsh-purge',root,inputs,lockSha256:ORIGINAL_PURGE_LOCK_SHA256};
|
||||
return {...source,sourceSha256:digest(source)};
|
||||
}
|
||||
export function originalPurgeRuntime(installation){
|
||||
if(process.platform!=='win32'||process.arch!=='x64')throw changed('当前原版受限配置仅核验 Windows x64。');
|
||||
if(installation?.controlledStatus!=='available'||installation.version!==lock.harnessVersion)throw changed('原版受限模式需要已检测的 Harness 0.2.1-rc.2。');
|
||||
const root=directory(installation.root),inputs=pinnedInputs(root,lock.harness);
|
||||
const platformLibraries=['kernel32.dll','advapi32.dll'].map(name=>({...engineFileIdentity(path.join(process.env.SystemRoot,'System32',name)),name}));
|
||||
const runtime={root,inputs,node:installation.node,lockSha256:ORIGINAL_PURGE_LOCK_SHA256,platformLibraries,
|
||||
nativeAddons:lock.nativeAddons.map(input=>({...input,path:path.join(root,input.relative)}))};
|
||||
return {...runtime,sha256:digest(runtime)};
|
||||
}
|
||||
export function originalPurgeStrategy(source,runtime,prompt){
|
||||
const postPrompt='[Agent Workbench original Purge '+source.sourceSha256+' / '+hash(Buffer.from(prompt))+']\n'+prompt+'\n[/Agent Workbench original Purge]';
|
||||
const config={enabled:true,autoApplyOnStart:false,autoUpdateOnStart:false,autoRevertOnMissing:false,injectOnce:false,stripMnemon:true,verbose:false,
|
||||
autoRetry:false,retryMax:0,autoContinue:false,continueMax:0,capabilityProtocol:true,hooksDenyBypass:false,postPromptOrder:5100,postPrompt};
|
||||
const strategy={schemaVersion:1,kind:ORIGINAL_PURGE_KIND,enabled:true,source,runtime,prompt,promptSha256:hash(Buffer.from(prompt)),originalConfig:config,
|
||||
implementation:'workbench-original-entry-restricted-v1',upstreamPluginLoaded:true,automaticRetry:false,hostModification:false,
|
||||
isolation:{profile:'fixed-trusted-source-node-permissions-v1',osSandbox:false,pinnedNativeAddons:true,arbitraryNativeAddons:false,originalTools:false,credentials:false}};
|
||||
return {...strategy,sha256:digest(strategy)};
|
||||
}
|
||||
export function assertOriginalPurgeStrategy(strategy){
|
||||
const source=originalPurgeSource(strategy.source?.root),runtime=originalPurgeRuntime({controlledStatus:'available',version:lock.harnessVersion,...strategy.runtime});
|
||||
const node=engineFileIdentity(strategy.runtime.node.path,256*1024*1024);
|
||||
if(node.sha256!==strategy.runtime.node.sha256||node.bytes!==strategy.runtime.node.bytes||strategy.runtime.node.version!==process.versions.node
|
||||
||digest(originalPurgeStrategy(source,runtime,strategy.prompt))!==digest(strategy))throw changed('原版策略、运行器或固定加载输入已变化,请保留原记录并封存新计划。');
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import { createHash } from 'node:crypto';
|
||||
import { engineError, engineCanonicalDigest } from '../../shared/contracts/engines.mjs';
|
||||
import { engineFileIdentity } from './deepseek-installation.mjs';
|
||||
import { registeredSourceRoots } from './registered-sources.mjs';
|
||||
import { ORIGINAL_PURGE_KIND, originalPurgeSource, originalPurgeRuntime, originalPurgeStrategy, assertOriginalPurgeStrategy } from './original-purge-source.mjs';
|
||||
export { ORIGINAL_PURGE_KIND } from './original-purge-source.mjs';
|
||||
|
||||
export const PURGE_SOURCE_FILES = Object.freeze(['package.json', 'lib/index.js', 'lib/identity.js', 'lib/core.js',
|
||||
'lib/continue-retry.js', 'lib/capability-protocol.js', 'cordis.patch.yml', 'LICENSE', 'NOTICE']);
|
||||
@@ -69,7 +71,22 @@ function strategyFor(source, prompt) {
|
||||
implementation: 'workbench-independent-prompt-v1', upstreamPluginLoaded: false, automaticRetry: false, hostModification: false };
|
||||
return { ...strategy, sha256: engineCanonicalDigest(strategy) };
|
||||
}
|
||||
export function selectPurgeStrategy(input, appDirectory = process.cwd()) {
|
||||
export function resolveOriginalPurgeSource(appDirectory=process.cwd(),root,installation) {
|
||||
const detected=resolvePurgeSource(appDirectory,root),base={...detected,kind:ORIGINAL_PURGE_KIND,supportedVersions:['1.1.78']};
|
||||
try {
|
||||
const source=originalPurgeSource(detected.root),runtime=originalPurgeRuntime(installation);
|
||||
return {...base,...source,status:'available',runtimeSha256:runtime.sha256,runtimeInputs:runtime.inputs.length,
|
||||
message:'原版 1.1.78 完整文件与固定 Harness 依赖已核对。使用独立运行副本;自动重试、继续和原版修改工具关闭。'};
|
||||
}catch(error){return {...base,status:'unavailable',sourceSha256:undefined,message:'原版受限模式尚不可用:'+error.message};}
|
||||
}
|
||||
export function selectPurgeStrategy(input, appDirectory = process.cwd(), installation) {
|
||||
if(input?.kind===ORIGINAL_PURGE_KIND){
|
||||
if(Object.keys(input).some(key=>!['kind','root','sourceSha256','runtimeSha256','prompt'].includes(key)))throw engineError('原版受限模式不接受权限或自动重试参数。',400);
|
||||
promptText(input.prompt);
|
||||
const source=resolveOriginalPurgeSource(appDirectory,input.root,installation);
|
||||
if(source.status!=='available'||source.sourceSha256!==input.sourceSha256||source.runtimeSha256!==input.runtimeSha256)throw engineError('原版来源或运行依赖与刚才的检测不一致,请重新检测并封存新计划。');
|
||||
return originalPurgeStrategy(originalPurgeSource(source.root),originalPurgeRuntime(installation),input.prompt);
|
||||
}
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['kind', 'root', 'sourceSha256', 'prompt'].includes(key))
|
||||
|| input.kind !== PURGE_PROMPT_KIND || typeof input.root !== 'string' || !/^[a-f0-9]{64}$/.test(input.sourceSha256 ?? '')) {
|
||||
throw engineError('实验策略只接受已检测来源与完整工程提示。', 400);
|
||||
@@ -81,6 +98,7 @@ export function selectPurgeStrategy(input, appDirectory = process.cwd()) {
|
||||
}
|
||||
export function assertPurgeStrategy(strategy) {
|
||||
if (strategy === undefined) return;
|
||||
if(strategy?.kind===ORIGINAL_PURGE_KIND){promptText(strategy.prompt);return assertOriginalPurgeStrategy(strategy);}
|
||||
if (!strategy || strategy.kind !== PURGE_PROMPT_KIND || strategy.enabled !== true || !strategy.source) throw engineError('原提示实验策略无效。');
|
||||
const source = resolvePurgeSource(process.cwd(), strategy.source.root);
|
||||
if (source.status !== 'available' || source.sourceSha256 !== strategy.source.sourceSha256) throw engineError('Purge 来源已变化,原提示实验不能继续;请保留记录并封存新计划。', 409, 'ENGINE_INPUT_CHANGED');
|
||||
@@ -93,7 +111,8 @@ export function nativeSystemTexts(input) {
|
||||
}
|
||||
export function assertPurgeModelInput(input, strategy) {
|
||||
if (!strategy) return;
|
||||
if (nativeSystemTexts(input).reduce((count, text) => count + text.split(strategy.section.text).length - 1, 0) !== 1) {
|
||||
const expected=strategy.kind===ORIGINAL_PURGE_KIND?strategy.originalConfig.postPrompt:strategy.section.text;
|
||||
if (nativeSystemTexts(input).reduce((count, text) => count + text.split(expected).length - 1, 0) !== 1) {
|
||||
throw engineError('实际模型输入缺少唯一完整的封存提示实验段,未发送请求。');
|
||||
}
|
||||
}
|
||||
|
||||
+14
-3
@@ -9,7 +9,7 @@ import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
import { publicEngineJob } from '../shared/contracts/engines.mjs';
|
||||
import { publicEngineRun, verifyEngineInput, originalEngineRun } from '../shared/contracts/engine-execution.mjs';
|
||||
import { resolvePurgeSource } from '../core/engines/purge-strategy.mjs';
|
||||
import { resolvePurgeSource,resolveOriginalPurgeSource,ORIGINAL_PURGE_KIND } from '../core/engines/purge-strategy.mjs';
|
||||
import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
|
||||
@@ -24,7 +24,12 @@ import { readInstallationProgress } from '../core/desktop/installation-progress.
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
const payload = (session.eventSeq ? 'id: ' + session.eventSeq + '\n' : '') + 'data: ' + JSON.stringify({ kind: 'session', seq: session.eventSeq, session }) + '\n\n';
|
||||
const snapshot = JSON.stringify({ kind: 'session', seq: session.eventSeq, session });
|
||||
// Large source/Run receipts stay in the session API. Repeatedly queueing
|
||||
// them on SSE can disconnect a healthy reader before it receives a cursor.
|
||||
const data = Buffer.byteLength(snapshot) <= 64 * 1024 ? snapshot : JSON.stringify({ kind: 'session_changed', seq: session.eventSeq,
|
||||
sessionId: session.id, projectId: session.projectId, revision: session.revision });
|
||||
const payload = (session.eventSeq ? 'id: ' + session.eventSeq + '\n' : '') + 'data: ' + data + '\n\n';
|
||||
for (const response of clients) {
|
||||
if (response.destroyed || response.writableEnded || response.writableLength > 2 * 1024 * 1024) { response.destroy(); clients.delete(response); }
|
||||
else response.write(payload);
|
||||
@@ -243,7 +248,13 @@ return async (request, response) => {
|
||||
if (method === 'GET' && route === '/api/research/availability') return json(response, runtime.researchManager().availability());
|
||||
if (method === 'GET' && route === '/api/engines/deepseek/availability') return json(response, runtime.engineManager().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
|
||||
if (method === 'GET' && route === '/api/engines/deepseek/controlled-availability') return json(response, runtime.engineRunner().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
|
||||
if (method === 'GET' && route === '/api/engines/purge/source') return json(response, resolvePurgeSource(appDirectory, url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
|
||||
if (method === 'GET' && route === '/api/engines/purge/source') {
|
||||
const root=url.searchParams.has('root')?url.searchParams.get('root'):undefined;
|
||||
if(url.searchParams.get('kind')===ORIGINAL_PURGE_KIND)return json(response,resolveOriginalPurgeSource(appDirectory,root,
|
||||
runtime.engineRunner().availability(url.searchParams.has('harnessRoot')?url.searchParams.get('harnessRoot'):undefined)));
|
||||
if(url.searchParams.has('kind')&&url.searchParams.get('kind')!=='purge-prompt-experiment')throw Object.assign(new Error('未知 Purge 策略。'),{status:400});
|
||||
return json(response,resolvePurgeSource(appDirectory,root));
|
||||
}
|
||||
if (method === 'GET' && route === '/api/events') {
|
||||
const cursor = Math.max(cursorNumber(url.searchParams.get('after')), cursorNumber(request.headers['last-event-id']));
|
||||
if (cursor > store.eventCursor) throw Object.assign(new Error('事件游标超出当前历史,请重新加载工作台。'), { status: 409 });
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
# Agent Workbench:核心代理能力研究与产品计划
|
||||
|
||||
## 当前接续 D:原版 Purge 生产策略
|
||||
|
||||
接续研究/封存 7b4f7ee / 1408e7a,A/B/C 不重做;独立端口和自有夹具,正式宿主与 Key 不操作。继续沿用 planning-with-files 与 product-ui-ux;本轮不启动子代理。
|
||||
|
||||
1. [complete] D1 原版 60 文件、393 份 Harness/元数据/原生文件固定;REA 静态核对两原生模块的导入与延迟导入。原版策略和九文件提示实验分开。
|
||||
2. [complete] D2 可复用运行副本/入口 facade/权限/实际 fsync broker 已接入 ControlledDeepSeekSession。生产适配的正常完成/模型失败不重试/宿主拒绝工具三场景通过;原生模块两项逐实际 dlopen、系统 DLL 绝对路径/hash 及加载收据保留,不宣称 OS 沙箱。
|
||||
3. [in_progress] D3 复用 Task/Run 消费和预算门控,默认关闭的原版模式/完整来源检测/策略明细已实现。宿主四场景和原生32K工程五组开发轮通过;界面实际发现大体积会话反复SSE推送导致积压断开,已改有游标的有界变更通知,最终冻结/回归及UI重验接续。
|
||||
4. [pending] D4 专项回归、实际 Harness/自有 HTTP 工程链路、编译界面两视口、来源/进程退出/证据封存及本地 Git 回顾。必要项未通过不标 D 完成。
|
||||
5. [pending] E 新真实交付和原版 AB/BA 对照;D 通过后另冻结来源,保留原六例与全部失败分母,不续跑旧任务。
|
||||
|
||||
恢复读取时三次批读总输出超过工具上限,截断内容不作为审查依据;后续限制每批总输出和具体短段。
|
||||
|
||||
本轮原失败保持:host零请求时缺consumption暴露验证器缺陷;原版16K固定指令/工具/余量不适配,0HTTP拒绝,单列32K不修改旧原轮;UI异步导航竞态已等待真实检视区,后续两次UI四功能通过但事件连接断开判失败,不能忽略;实际定位publisher超过2MiB队列时destroy。build第二轮npm脚本子进程误用PATH内Node16失败,第三轮显式前置Node24后通过,不改系统全局配置。
|
||||
|
||||
## 当前修复B/C:连接阶段诊断与实际模型身份
|
||||
|
||||
A已提交0a58c0d/6257bba并封存。继续先完成网络与报告中的确定问题,再校准后续预算和原版插件隔离;不请求真实模型,不改正式Provider。原GPT失败是UND_ERR_CONNECT_TIMEOUT、约10秒连接阶段,而非300秒响应等待;当前没有HTTP(S)_PROXY环境设置,不能推断是Key或模型拒绝。
|
||||
|
||||
@@ -4,6 +4,26 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { fixture, launchWorkbench, compatibleFixture, until, assertToolPairs } from './helpers.mjs';
|
||||
import { createSessionPublisher } from '../src/server/app.mjs';
|
||||
|
||||
test('large source receipts use cursor-preserving invalidation without filling the event stream or changing the session', () => {
|
||||
const session = { id: 'owned-session', projectId: 'owned-project', revision: 10, eventSeq: 42, source: '汉'.repeat(24000) };
|
||||
let queued = 0, destroyed = false; const chunks = [];
|
||||
const response = { get writableLength() { return queued; }, write(value) { queued += Buffer.byteLength(value); chunks.push(value); }, destroy() { destroyed = true; } };
|
||||
const publish = createSessionPublisher(new Set([response]));
|
||||
for (let i = 0; i < 100; i++) publish(session);
|
||||
assert.equal(destroyed, false); assert.ok(queued < 64 * 1024);
|
||||
assert.ok(chunks.every(value => value.startsWith('id: 42\ndata: ')));
|
||||
assert.deepEqual(JSON.parse(chunks[0].split('\ndata: ')[1]), { kind: 'session_changed', seq: 42, sessionId: session.id, projectId: session.projectId, revision: 10 });
|
||||
assert.equal(session.source, '汉'.repeat(24000)); assert.equal(session.eventSeq, 42);
|
||||
});
|
||||
|
||||
test('small event updates retain the current session and actual cursor', () => {
|
||||
const session = { id: 'owned-small', projectId: 'owned-project', revision: 3, eventSeq: 7, status: 'awaiting_approval' }, chunks = [];
|
||||
createSessionPublisher(new Set([{ write(value) { chunks.push(value); } }]))(session);
|
||||
assert.deepEqual(JSON.parse(chunks[0].split('\ndata: ')[1]), { kind: 'session', seq: 7, session });
|
||||
assert.ok(chunks[0].startsWith('id: 7\n'));
|
||||
});
|
||||
|
||||
test('the bundled local service enforces host, origin, token and JSON object contracts', async t => {
|
||||
const f = fixture(t), server = await launchWorkbench(t, f.data); f.onCleanup(server.close);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {spawnSync} from 'node:child_process';
|
||||
import {fixture} from './helpers.mjs';
|
||||
import {originalPurgeSource,ORIGINAL_PURGE_KIND} from '../src/core/engines/original-purge-source.mjs';
|
||||
import {resolveOriginalPurgeSource,selectPurgeStrategy,assertPurgeModelInput} from '../src/core/engines/purge-strategy.mjs';
|
||||
import {originalPurgeReadRoots,OriginalPurgeRuntime} from '../src/core/engines/original-purge-runtime.mjs';
|
||||
import lock from '../src/core/engines/original-purge-lock.json' with {type:'json'};
|
||||
|
||||
function source(f){const root=path.join(f.root,'original');fs.mkdirSync(root);
|
||||
for(const input of lock.original){const target=path.join(root,input.relative);fs.mkdirSync(path.dirname(target),{recursive:true});
|
||||
fs.copyFileSync(path.resolve('docs/original-purge-load-evidence/upstream',input.relative),target);}
|
||||
return root;
|
||||
}
|
||||
test('original source locks all 60 byte-identical files including modules outside the nine-file prompt experiment',t=>{
|
||||
const f=fixture(t),root=source(f),before=originalPurgeSource(root);assert.equal(before.inputs.length,60);assert.equal(before.version,'1.1.78');
|
||||
const file=before.inputs.find(input=>input.relative==='lib/host.js');assert.ok(file);
|
||||
fs.appendFileSync(file.path,'\n// changed outside old prompt lock\n');assert.throws(()=>originalPurgeSource(root),/固定原版输入已变化/);
|
||||
});
|
||||
test('a new original executable or missing license cannot silently join the fixed trusted-source profile',t=>{
|
||||
const f=fixture(t),root=source(f);fs.writeFileSync(path.join(root,'lib/unsealed.js'),'export const added=true;');
|
||||
assert.throws(()=>originalPurgeSource(root),/文件集合已变化/);fs.unlinkSync(path.join(root,'lib/unsealed.js'));fs.unlinkSync(path.join(root,'NOTICE'));
|
||||
assert.throws(()=>originalPurgeSource(root));
|
||||
});
|
||||
test('original mode has a separate source identity and does not accept retry or privilege fields',t=>{
|
||||
const f=fixture(t),root=source(f),available=resolveOriginalPurgeSource(f.root,root,{controlledStatus:'unavailable'});
|
||||
assert.equal(available.kind,ORIGINAL_PURGE_KIND);assert.equal(available.status,'unavailable');assert.equal(available.sourceSha256,undefined);
|
||||
assert.match(available.message,/Harness/);
|
||||
for(const field of ['automaticRetry','hooksDenyBypass','hostModification'])assert.throws(()=>selectPurgeStrategy({kind:ORIGINAL_PURGE_KIND,root,prompt:'owned task',[field]:true}),/不接受/);
|
||||
});
|
||||
test('actual original model input requires the complete postPrompt once in system context and cannot borrow a user or tool copy',()=>{
|
||||
const strategy={kind:ORIGINAL_PURGE_KIND,originalConfig:{postPrompt:'[sealed original engineering prompt]'}};
|
||||
const system=text=>({system:text,messages:[]});assertPurgeModelInput(system(strategy.originalConfig.postPrompt),strategy);
|
||||
assert.throws(()=>assertPurgeModelInput(system(strategy.originalConfig.postPrompt.repeat(2)),strategy),/唯一完整/);
|
||||
assert.throws(()=>assertPurgeModelInput({messages:[{role:'user',content:[{type:'text',text:strategy.originalConfig.postPrompt}]}]},strategy),/唯一完整/);
|
||||
});
|
||||
test('Windows directory permissions normalize overlapping grants without allowing an unrelated sibling',t=>{
|
||||
const f=fixture(t),workspace=path.join(f.root,'workspace'),native=path.join(workspace,'native'),sibling=path.join(f.root,'unrelated');
|
||||
fs.mkdirSync(native,{recursive:true});fs.mkdirSync(sibling);fs.writeFileSync(path.join(sibling,'sentinel.txt'),'protected');
|
||||
const roots=originalPurgeReadRoots([native,workspace],[]);assert.deepEqual(roots,[fs.realpathSync.native(workspace)]);
|
||||
const script='const fs=require("node:fs");fs.realpath.native(process.argv[1],(error,result)=>{if(error)throw error;try{fs.readFileSync(process.argv[2]);process.exitCode=2;}catch(error){if(error.code!=="ERR_ACCESS_DENIED")throw error;process.stdout.write("allowed-directory-and-denied-sibling");}});';
|
||||
const result=spawnSync(process.execPath,['--permission',...roots.flatMap(root=>['--allow-fs-read='+root,'--allow-fs-read='+path.toNamespacedPath(root)]),'-e',script,workspace,path.join(sibling,'sentinel.txt')],{encoding:'utf8',windowsHide:true});
|
||||
assert.equal(result.status,0,result.stderr);assert.equal(result.stdout,'allowed-directory-and-denied-sibling');
|
||||
});
|
||||
test('durability broker rejects foreign authentication, outside paths and wrong file identity before real fsync',async t=>{
|
||||
const f=fixture(t),directory=path.join(f.root,'run');fs.mkdirSync(directory);const file=path.join(directory,'owned.jsonl');fs.writeFileSync(file,'owned\n');
|
||||
// Exercise the public broker handler with an explicitly declared object;
|
||||
// original-source loading is verified separately by the actual Harness driver.
|
||||
const broker=Object.assign(Object.create(OriginalPurgeRuntime.prototype),{directory,report:{durabilityReceipts:[],durabilityRejections:[]}});
|
||||
const {Readable}=await import('node:stream');
|
||||
const run=async(value,authorization='Bearer owned')=>{
|
||||
const request=Readable.from([Buffer.from(JSON.stringify(value))]);Object.assign(request,{method:'POST',url:'/fsync',headers:{'content-type':'application/json',authorization}});
|
||||
const response={writeHead(status){this.status=status;},end(body){this.body=body;}};
|
||||
await broker.handleDurability(request,response,'owned');return response;
|
||||
};
|
||||
const stat=fs.statSync(file,{bigint:true}),value={path:file,dev:String(stat.dev),ino:String(stat.ino),size:String(stat.size)};
|
||||
assert.equal((await run(value,'Bearer foreign')).status,409);assert.equal((await run({...value,path:path.join(f.root,'outside')})).status,409);
|
||||
assert.equal((await run({...value,ino:'0'})).status,409);assert.equal(broker.report.durabilityReceipts.length,0);
|
||||
assert.equal((await run(value)).status,200);assert.equal(broker.report.durabilityReceipts.length,1);assert.equal(broker.report.durabilityReceipts[0].operation,'actual-parent-fsync');
|
||||
});
|
||||
Reference in New Issue
Block a user