diff --git a/docs/LIVE-EXECUTION-REPAIR-PLAN.md b/docs/LIVE-EXECUTION-REPAIR-PLAN.md index 1c0a7955..ccee6508 100644 --- a/docs/LIVE-EXECUTION-REPAIR-PLAN.md +++ b/docs/LIVE-EXECUTION-REPAIR-PLAN.md @@ -13,3 +13,5 @@ | E:新批次真实复验 | A–D各自通过相关回归后冻结新来源;另开有界真实React/Python交付和原版Purge同源AB/BA对照。保留原本轮六例,不回写成功。 | 既定功能、原测试/构建、React两视口实际操作、父审查/Git、原暂存/未暂存保留均闭环;所有失败、监督审批、真实模型、用量与耗时可核对。 | 每个切片先封存原问题,再实现、验证、回顾和本地提交。网络、上下文与实际能力分别判定;不得通过只做加法题、修改测试、无限加容量或人工代写来让原样本“通过”。本轮不再继续消耗真实模型请求,后续新批次需在修复后的明确范围与预算中执行。 + +D 已完成无 Key 原版入口加载的可行性子切片:31 原模块、四场景/六桥调用、正常退出码 0、外部工具拒绝及三项落盘 broker 负例通过,见 [原版加载回顾](ORIGINAL-PURGE-LOAD-REVIEW.md)。这仍是研究驱动:上游宿主修改 patch 未安装,生产策略/Task 消费接线及原生隔离边界尚待实现,D 不标完成,E 尚未开跑。 diff --git a/docs/ORIGINAL-PURGE-LOAD-REVIEW.md b/docs/ORIGINAL-PURGE-LOAD-REVIEW.md new file mode 100644 index 00000000..bfafdaed --- /dev/null +++ b/docs/ORIGINAL-PURGE-LOAD-REVIEW.md @@ -0,0 +1,36 @@ +# 原版 Purge 隔离加载:可行性切片 + +已在独立 Harness 0.2.1-rc.2 进程中,实际调用原版 dsh-purge 1.1.78 的入口与 `apply`,核对 31 个原版模块及实际模型输入。源自用户已有目录,60 份包元数据、许可证和 lib 原文件逐字节复制,原目录与副本在退出后仍与启动前 SHA 一致;保留 Apache-2.0 LICENSE、NOTICE 和作者署名。 + +这是研究驱动 `scripts/verify-original-purge-load.mjs`,尚未作为工作台生产策略开放。未安装原发行的宿主修改 patch、未执行 postinstall、未接真实模型或正式 Key。效果结论仍为“原版收益未测”。 + +## 固定配置与实际场景 + +原版默认 `autoRetry=true`、`retryMax=3`、`hooksDenyBypass=true`。本切片明确采用受限配置:原入口启用,但自动应用、更新、回滚、重试、继续关闭,`hooksDenyBypass=false`;固定 postPrompt 在六个实际模型桥输入中均唯一存在。不能把该配置称为上游完整默认模式。 + +| 场景 | 实际模型桥调用 | 宿主工具回调 | 结果 | +| --- | ---: | ---: | --- | +| 正常返回 | 1 | 0 | 原 assistant/正常结束事件核对通过,shutdown 成功、退出码 0 | +| 模型失败 | 1 | 0 | 不自动重试,保存失败并关闭所属进程树 | +| 模型尝试 purge_apply | 2 | 0 | 原插件工具未注册到实际目录,未执行;下一桥调用由宿主拒绝供给响应,保留失败 | +| 模型尝试允许目录中的 owned_probe | 2 | 1 | 外部宿主明确拒绝;错误反馈后的下一桥调用被停止,未执行操作 | + +后两项的第二调用属于工具错误反馈后的下一模型轮次,不能算成原请求自动重试。全部六份原始桥输入保留,夹具只供给三份固定模型响应;它们均不是外部供应商 HTTP 或计费请求。 + +四个进程全部 rootExited/treeConfirmed、没有存活后代。原插件注册的 `purge_status`、`purge_apply`、`purge_revert` 三项由外部 facade 拒绝注册,实际工具目录继续由工作台桥核对。原插件仍安装内部 fullAccess 等钩子,不因一个配置字段就宣称这些钩子不存在;外部工具门控单独验证。 + +## Windows 落盘与权限 + +独立 home/agents/USERPROFILE/APPDATA、过滤环境和模型/工具桥均未带正式连接。Node 文件系统权限将写入限制在所属运行目录,外部自有哨兵的读取、写入和 child_process 三项实际拒绝。 + +Harness 的 Windows JSONL 实现会核对盘根和所有祖先目录,且 Node permission 模式禁用 fsync。没有开放盘根文件内容读取或跳过真实落盘:父进程只提供实际祖先目录 stat 元数据;文件同步通过所属 loopback broker,核对认证、运行目录真实路径和原文件 dev/ino/size,再实际 fsync 并保存 SHA 收据。错误认证、目录外路径和错误文件身份三项实际 409 拒绝,没有新增同步收据。 + +Harness 必须加载其 native builtin loader,因此实验进程需要 allow-addons。这使 Node 权限不能视为隔离任意原生代码的 OS 沙箱。本切片仅证明固定来源的无 Key 加载、外部工具门控和上述实际拒绝;生产接入前还需完成宿主边界设计与相关行为验证,不能将这份研究驱动直接开放给任意插件。 + +## 来源、原失败与后续 + +每场景观察并封存 335 个 JS/JSON 加载输入,四场景按路径共 338 个;有源正文的加载 SHA 与原文件 SHA 一致。60 份原包输入、31 模块闭包、原配置、生成桥/叠加/权限适配、实际六份模型输入、父进程同步收据和完整原结果均另行封存。这份 JS/JSON 观察清单不等于全部原生 DLL/操作系统依赖锁定。 + +开发失败保留:驱动早期传入 null 策略/空工具不符合已有契约;缺失目录的权限通配与祖先 package.json 探测;native loader 所需权限;JSONL 的祖先 stat/fsync;工具错误后的下一模型轮次被旧断言误当重试。早期两场景收据曾因漏核对正常退出而输出 passed=true,其原 processReport 实际 failed/强制退出,现明确作不合格开发来源,未覆盖原件。最终原轮增加退出码、状态和实际拒绝断言,四场景及三项 broker 负例均通过。 + +下一步仍在修复计划 D:把原版入口及其外部约束提取成可复用且版本化的策略契约,接入 Task/Run 消费账本、预算、审批、停止、恢复和逐请求来源核验;补齐原生依赖与隔离边界后再完成 D 生产验收。E 随后冻结新来源,另开真实自主工程和原版对照,沿用原失败分母,不重放旧六例。正式宿主本轮未操作。 diff --git a/findings.md b/findings.md index 4c6cfe45..753934f3 100644 --- a/findings.md +++ b/findings.md @@ -920,3 +920,5 @@ C新增发现:实际usage必须绑定实际线体本地估算和同Task/模型 C实际渲染回看:1440/390px原截图均显示55,017上游报告、35,000运行预算、20,017记账超出及未知0/0,原HTTP503仍在预算面板;窄屏完整换行、续接入口可达,无页面横向溢出。真实编译宿主的两视口续接预览/关闭/刷新均不增加HTTP、不替换原Task。验证器第三次原失败仅为label“新Run预算tokens”不匹配实际“新Run累计tokens”;修正选择器后独立UUID两组通过,产品字节未变。固定16K的Chat原生三模块/原九项失败与后续修复/父审查/Git五组已通过;Responses和最终相关回归仍在运行。本轮恢复期间一次批量读取及通配输出过大,后续精确限定文件和短段;一次误写修复计划文件名不存在,已按实际LIVE-EXECUTION-REPAIR-PLAN.md读取,不计作验证。 C后续审查:首冻结147/147通过后,Responses独立首轮4响应+1unknown/reset,未自动重发,原失败保留;原夹具catch直接destroy且未保存原因。增加只收集error的诊断后新UUID五组通过,不能把未复现断开归因于已知断言。另修正每次重试/切池前的预留核对:45,100已报告/70,000预算时虽尚未超额,剩余24,900已低于校准预留,legacy和池都必须只发一次并保留503。最终425输入重新冻结,首轮147不算新来源149通过。D只读确认原插件默认autoRetry=true/retryMax3/hooksDenyBypass=true;完整原patch另含身份与redteam组件,必须隔离配置/加载闭包,不能直接改正式宿主。 + +D原版加载实证:31模块闭包还依赖dsh-llm,60包输入不足以代表全部Harness/原生闭包,已追加每场景335个实际JS/JSON加载身份。原插件自动更新/应用可关闭,但仍注册三项宿主操作工具和fullAccess钩子,需外部门控。Windows Node权限对不存在目录需显式通配;Harness启动向祖先查package元数据,JSONL落盘从盘根逐级stat且fsync被权限模型禁用。采用祖先实际stat元数据委托及受认证/真路径/dev/ino/size限制的真实父fsync,不跳过同步;三负例通过。native builtin loader需allow-addons,故仍不是任意插件OS沙箱。最终正常退出0和四全树退出已核对;原两项passedtrue漏退出断言已在报告明确不合格。工具错误会正常触发下一模型轮次,与模型失败重试不同,所有六桥输入均保留,不能隐藏第二轮或计作真实模型请求。 diff --git a/progress.md b/progress.md index 2ae75bf9..de65042d 100644 --- a/progress.md +++ b/progress.md @@ -1402,3 +1402,5 @@ C最终接续:预算专项7/7、最终编译通过;新UI独立目录model-bu C最终结论:重试前剩余预算不足的两项回归补齐后,新425输入冻结保持,15文件149/149及编译通过;Chat controlled-context-417c46cd-bd9a-4600-a2cb-33a028b5568d、Responses controlled-context-6471c96c-cab2-4d8c-85fe-ec53876cdccc各5组;UI model-budget-ui-01f13fac-4234-4ea9-89f3-02225857cf31两组并已目视两张最终原图通过。此前147/147及原Responses未知失败、诊断复验均独立保留,不混作最终来源。A/B/原六例离线通过;真实请求0、正式宿主未动。D只读预研中两次猜测桥文件名不存在,随后由rg实际清单定位controlled-plugin/controlled-installation,未执行原插件。 C实现bb45dab;464份/19,086,976字节/425源码身份/446工件记录封存,manifest SHA d54905c5350996c8f1c205cfe20fada82fc32a1eefd492d1b4c863e325f17c9f;独立离线验证已通过,两最终链路20原生请求的原输入/校准来源核对保持。正式未部署,D/E继续,不将本机HTTP当真实收益。 + +D研究接续:实际原版入口/31模块及apply已在独立无Key Harness加载。最终original-purge-load-c6df89e7-8cd3-4e6c-b070-a8e6d02fec05四场景、六模型桥输入、外部工具拒绝、三项broker负例通过;正常原进程退出码0,四全树关闭。观察335模块/场景、338唯一路径;60原包文件与原目录/副本SHA保持。原始错误逐日志/UUID保留,早期两项passed=true因漏正常退出核对已明确不合格,未改原件。Windows JSONL祖先元数据及真实fsync通过有归属代理,不开放根目录读取;allow-addons不是OS沙箱,D生产接入/原生闭包仍待实现,不代表Purge收益。开发中一次rg误传PowerShell参数、两次猜测路径已纠正,未改变产品运行源码。真实请求0,正式宿主未动。 diff --git a/scripts/verify-original-purge-evidence.mjs b/scripts/verify-original-purge-evidence.mjs new file mode 100644 index 00000000..5f38d808 --- /dev/null +++ b/scripts/verify-original-purge-evidence.mjs @@ -0,0 +1,56 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {createHash} from 'node:crypto'; +import {execFileSync} from 'node:child_process'; +import {nativeSystemTexts} from '../src/core/engines/purge-strategy.mjs'; + +// Offline evidence checks only; never imports the original plugin or creates +// a Runtime, Provider, native process, network listener or model request. +const root=path.resolve('docs/original-purge-load-evidence'),sha=value=>createHash('sha256').update(value).digest('hex'); +const inside=relative=>{const file=path.resolve(root,relative);assert.ok(file.startsWith(root+path.sep));return file;}; +const raw=fs.readFileSync(inside('manifest.json')),manifest=JSON.parse(raw),read=relative=>JSON.parse(fs.readFileSync(inside(relative))); +assert.equal(manifest.schemaVersion,1);assert.equal(manifest.realModelRequests,0);assert.equal(manifest.productionStrategyImplemented,false); +const seen=new Set();let bytes=0; +for(const entry of manifest.entries){assert.ok(!seen.has(entry.path));seen.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(seen.size,manifest.count);assert.equal(bytes,manifest.bytes); +for(const input of manifest.sourceInputs){ + assert.match(input.path,/^scripts\/[a-z-]+\.mjs$/); + const blob=execFileSync('git',['show',manifest.sourceCommit+':'+input.path],{windowsHide:true,maxBuffer:1024*1024}); + assert.equal(sha(blob),input.gitBlobSha256);assert.equal(sha(fs.readFileSync(inside(input.snapshot))),input.sha256); +} +for(const input of manifest.upstreamInputs){const data=fs.readFileSync(inside(input.snapshot));assert.equal(sha(data),input.sha256);assert.equal(data.length,input.bytes);} +assert.equal(manifest.upstreamInputs.length,60); +const final=read(manifest.final.result),modelInputs=read(manifest.final.modelInputs); +assert.equal(final.passed,true);assert.equal(final.realModelRequests,0);assert.equal(final.productionStrategyImplemented,false); +assert.equal(final.upstreamPatchInstalled,false);assert.equal(final.nativeAddonIsolation,'not_an_os_sandbox');assert.equal(final.closure.length,31); +assert.deepEqual(final.externals,['@deepseek-ai/dsh-llm']); +for(const key of ['autoApplyOnStart','autoUpdateOnStart','autoRevertOnMissing','autoRetry','autoContinue','hooksDenyBypass'])assert.equal(final.config[key],false); +assert.deepEqual(final.results.map(value=>value.scenario),['completed','failed-no-retry','blocked-purge-apply','host-denied-tool']); +assert.deepEqual(final.results.map(value=>value.requests),[1,1,2,2]);assert.deepEqual(final.results.map(value=>value.toolCalls),[0,0,0,1]); +const nativeInputs=new Map(manifest.loadedModuleInputs.map(input=>[input.path,input]));let moduleRecords=0; +for(const result of final.results){ + assert.equal(result.ready.originalApplyCalled,true);assert.equal(result.ready.originalEntryLoaded,true);assert.equal(result.ready.loaded.length,31); + assert.deepEqual(result.ready.blockedTools,['purge_apply','purge_revert','purge_status']);assert.deepEqual(result.ready.denied,{read:true,write:true,child:true}); + assert.equal(result.processReport.cleanup.rootExited,true);assert.equal(result.processReport.cleanup.treeConfirmed,true);assert.deepEqual(result.processReport.cleanup.remainingProcesses,[]); + if(result.scenario==='completed'){ + assert.equal(result.error,null);assert.equal(result.processReport.status,'closed');assert.equal(result.processReport.cleanup.exit.code,0); + assert.equal(result.processReport.cleanup.forced,false);assert.deepEqual(result.brokerRejections.map(value=>[value.name,value.status]), + [['unowned-auth',409],['outside-runtime',409],['wrong-file-identity',409]]); + }else assert.ok(result.error); + assert.ok(result.durabilityReceipts.length>=2);assert.equal(result.moduleInputs.length,335); + for(const flush of result.durabilityReceipts){assert.equal(flush.operation,'actual-parent-fsync');assert.match(flush.sha256,/^[a-f0-9]{64}$/);assert.ok(!flush.path.split(/[\\/]/).includes('..'));} + for(const input of result.moduleInputs){const original=nativeInputs.get(input.path);assert.equal(original.sha256,input.sha256); + const data=fs.readFileSync(inside(original.snapshot));assert.equal(sha(data),input.sha256);assert.equal(data.length,input.bytes); + if(input.sourceSha256)assert.equal(input.sourceSha256,input.sha256);moduleRecords++;} +} +assert.equal(modelInputs.length,6);for(const {input} of modelInputs)assert.equal(nativeSystemTexts(input).join('\n').split(final.config.postPrompt).length-1,1); +for(const receipt of manifest.developmentReceipts){ + const result=read(receipt.result);if(receipt.classification==='insufficient_exit_assertions'){ + assert.equal(result.passed,true);assert.equal(result.results[0].processReport.status,'failed');assert.notEqual(result.results[0].processReport.cleanup.exit.code,0); + } +} +console.log(JSON.stringify({passed:true,sourceCommit:manifest.sourceCommit,manifestSha256:sha(raw),files:seen.size,bytes,upstreamFiles:60, + originalModules:31,moduleRecords,observedModulePaths:nativeInputs.size,scenarios:4,ownedBridgeCalls:6,realModelRequests:0, + scope:'Offline byte/source/actual-load/exit/external-denial checks only. Native OS isolation, production strategy and original Purge benefit remain incomplete.'})); diff --git a/scripts/verify-original-purge-load.mjs b/scripts/verify-original-purge-load.mjs new file mode 100644 index 00000000..b95db13f --- /dev/null +++ b/scripts/verify-original-purge-load.mjs @@ -0,0 +1,199 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import assert from 'node:assert/strict'; +import {createHash,randomUUID} from 'node:crypto'; +import {pathToFileURL} from 'node:url'; +import http from 'node:http'; +import ts from 'typescript'; +import {ControlledDeepSeekSession} from '../src/core/engines/controlled-session.mjs'; +import {resolveControlledInstallation,assertControlledInstallation} from '../src/core/engines/controlled-installation.mjs'; +import {engineFileIdentity} from '../src/core/engines/deepseek-installation.mjs'; +import {McpStdio} from '../src/core/tools/mcp-stdio.mjs'; + +// A research driver, not a production strategy or a real-model benchmark. It +// loads original, byte-identical modules in one owned Harness process with no +// credentials. It never installs the upstream patch or runs postinstall. +const directory=path.resolve('.qa','original-purge-load-'+randomUUID()),source=process.env.AGENT_WORKBENCH_PURGE_178_ROOT; +assert.ok(source&&path.isAbsolute(source),'Set the existing original 1.1.78 source directory.'); +const installation=resolveControlledInstallation(process.cwd(),process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT); +assert.equal(installation.controlledStatus,'available',installation.message); +const sha=value=>createHash('sha256').update(value).digest('hex'),inputs=[]; +fs.mkdirSync(directory);const ownSource=path.join(directory,'original-plugin');fs.mkdirSync(ownSource); +function copy(relative){const file=path.join(source,relative),stat=fs.lstatSync(file);assert.equal(stat.isSymbolicLink(),false); + if(stat.isDirectory()){fs.mkdirSync(path.join(ownSource,relative),{recursive:true});for(const entry of fs.readdirSync(file))copy(path.join(relative,entry));} + else{assert.ok(stat.isFile());assert.ok(stat.size<4*1024*1024);const raw=fs.readFileSync(file);fs.mkdirSync(path.dirname(path.join(ownSource,relative)),{recursive:true}); + fs.writeFileSync(path.join(ownSource,relative),raw,{flag:'wx'});inputs.push({relative:relative.replaceAll('\\','/'),bytes:raw.length,sha256:sha(raw)});}} +for(const file of ['package.json','LICENSE','NOTICE','lib'])copy(file); +const metadata=JSON.parse(fs.readFileSync(path.join(ownSource,'package.json')));assert.equal(metadata.version,'1.1.78');assert.equal(metadata.dshTarget,'0.2.1-rc.2'); +const pending=['lib/index.js'],closure=new Set(),externals=new Set(); +while(pending.length){const relative=pending.pop();if(closure.has(relative))continue;closure.add(relative); + assert.ok(!relative.startsWith('../'));const file=path.join(ownSource,relative),tree=ts.createSourceFile(file,fs.readFileSync(file,'utf8'),ts.ScriptTarget.Latest,true,ts.ScriptKind.JS); + function spec(value){if(value.startsWith('.'))pending.push(path.posix.normalize(path.posix.join(path.posix.dirname(relative),value)));else if(!value.startsWith('node:'))externals.add(value);} + function visit(node){if((ts.isImportDeclaration(node)||ts.isExportDeclaration(node))&&node.moduleSpecifier)spec(node.moduleSpecifier.text); + if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword){assert.ok(ts.isStringLiteral(node.arguments[0]),'Unbounded dynamic import');spec(node.arguments[0].text);}ts.forEachChild(node,visit);}visit(tree);} +assert.deepEqual([...externals],['@deepseek-ai/dsh-llm']); +const config=Object.freeze({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:'[Agent Workbench original Purge loading probe] Keep the owned task and external host permissions. [/Agent Workbench original Purge loading probe]'}); +const wrapper=String.raw`import fs from 'node:fs'; +import {registerHooks} from 'node:module'; +import {fileURLToPath,pathToFileURL} from 'node:url'; +import {createHash} from 'node:crypto'; +import {execFileSync} from 'node:child_process'; +export const name='workbench-original-purge-load-probe'; +export const inject=['systemPrompt','tools','appReady']; +export async function apply(ctx,config){ + const loaded=[],blockedTools=[],rawInputs=new Map(config.inputs.map(input=>[input.url,input])); + const hooks=registerHooks({resolve(specifier,context,next){ + if(context.parentURL?.startsWith(config.sourceUrl)){ + if(specifier==='@deepseek-ai/dsh-llm')return {url:config.llmModule,shortCircuit:true}; + if(!specifier.startsWith('.')&&!specifier.startsWith('node:'))throw new Error('Unexpected original dependency: '+specifier); + }return next(specifier,context);},load(url,context,next){ + if(url.startsWith(config.sourceUrl)&&url.endsWith('.js')){ + const input=rawInputs.get(url);if(!input)throw new Error('Original module is not sealed.'); + const raw=fs.readFileSync(fileURLToPath(url));if(createHash('sha256').update(raw).digest('hex')!==input.sha256)throw new Error('Original module changed.'); + loaded.push(url); + }return next(url,context);}}); + const toolProxy=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 toolProxy;if(key==='get')return name=>name==='tools'?toolProxy:target.get(name); + const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;}}); + const original=await import(config.entry);original.apply(facade,config.originalConfig); + const denied={}; + for(const action of ['read','write','child']){try{ + if(action==='read')fs.readFileSync(config.protectedPath); + else if(action==='write')fs.writeFileSync(config.protectedPath,'Unexpected write'); + else execFileSync(process.execPath,['-e','process.stdout.write("owned probe")']); + denied[action]=false; + }catch(error){denied[action]=error.code==='ERR_ACCESS_DENIED';}} + const marker={schemaVersion:1,pid:process.pid,loaded:[...new Set(loaded)],blockedTools,denied,originalConfig:config.originalConfig, + originalEntryLoaded:true,originalApplyCalled:true,profile:'original-entry-with-external-tool-policy',upstreamPatchInstalled:false}; + fs.writeFileSync(config.marker,JSON.stringify(marker)); + ctx.effect(()=>()=>hooks.deregister()); +} +`; +const wrapperFile=path.join(directory,'original-entry-wrapper.mjs');fs.writeFileSync(wrapperFile,wrapper); +const accessLogFile=path.join(directory,'access-log.mjs'); +fs.writeFileSync(accessLogFile,`import fs from 'node:fs';import path from 'node:path';import {syncBuiltinESMExports,registerHooks} from 'node:module';import {fileURLToPath} from 'node:url';import {createHash} from 'node:crypto'; +const directoryMetadata=JSON.parse(fs.readFileSync(process.env.AWB_OWNED_DIRECTORY_METADATA,'utf8')); +const moduleInputs=new Map(),digest=value=>createHash('sha256').update(value).digest('hex'); +registerHooks({load(url,context,next){const result=next(url,context);if(url.startsWith('file:')){ + const file=fileURLToPath(url),raw=fs.readFileSync(file),source=result.source==null?null:typeof result.source==='string'?Buffer.from(result.source):Buffer.from(result.source); + const identity={url,path:file,format:result.format,bytes:raw.length,sha256:digest(raw),sourceSha256:source?digest(source):null}; + const previous=moduleInputs.get(url);if(previous&&JSON.stringify(previous)!==JSON.stringify(identity))throw new Error('Owned loaded module changed.'); + if(!previous){moduleInputs.set(url,identity);fs.appendFileSync(process.env.AWB_OWNED_MODULE_INPUTS,JSON.stringify(identity)+'\\n');} +}return result;}}); +const log=(name,args,error)=>{if(error.code==='ERR_ACCESS_DENIED')process.stderr.write('OWNED_ACCESS_DENIED '+name+' '+String(args[0])+'\\n'+(name.startsWith('promises.')?error.stack+'\\n':''));}; +for(const name of ['existsSync','statSync','lstatSync','readFileSync','realpathSync','readdirSync','readFile','stat','lstat','realpath','readdir','access']){const original=fs[name];const wrapped=function(...args){try{return original.apply(this,args);}catch(error){log(name,args,error);throw error;}};Object.assign(wrapped,original);fs[name]=wrapped;} +for(const name of ['readFile','stat','lstat','realpath','readdir','access']){const original=fs.promises[name];fs.promises[name]=async function(...args){try{return await original.apply(this,args);}catch(error){ +if(error.code==='ERR_ACCESS_DENIED'&&name==='stat'&&!args[1]?.bigint&&directoryMetadata[path.resolve(String(args[0]))]){ + const value=Object.assign(Object.create(fs.Stats.prototype),directoryMetadata[path.resolve(String(args[0]))]);for(const key of ['atime','mtime','ctime','birthtime'])value[key]=new Date(value[key]);return value; +}log('promises.'+name,args,error);throw error;}};} +const open=fs.promises.open;fs.promises.open=async function(file,...args){const handle=await open.call(this,file,...args),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(process.env.AWB_OWNED_DURABILITY_ENDPOINT,{method:'POST',signal:AbortSignal.timeout(10000), + headers:{'Content-Type':'application/json',Authorization:'Bearer '+process.env.AWB_OWNED_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 broker rejected: '+await response.text());await response.json(); +}};return handle;};syncBuiltinESMExports();`); +const protectedPath=path.join(directory,'outside-runtime-owned-sentinel.txt');fs.writeFileSync(protectedPath,'Owned sentinel; this is not user data or a key.\n'); +const beforeSentinel=fs.readFileSync(protectedPath),modelInputs=[],results=[];let active,activeBroker; +const inputUrls=inputs.map(input=>({...input,url:pathToFileURL(path.join(ownSource,input.relative)).href})); +try{ + for(const scenario of ['completed','failed-no-retry','blocked-purge-apply','host-denied-tool']){ + const base=path.join(directory,scenario);fs.mkdirSync(base);const cwd=path.join(base,'workspace');fs.mkdirSync(cwd); + const runDirectory=path.join(base,'native'),marker=path.join(runDirectory,'original-loaded.json'),owner=Object.fromEntries(['sessionId','projectId','taskId','runId','jobId'].map(key=>[key,randomUUID()])); + const durabilityReceipts=[],brokerRejections=[],durabilityNonce=randomUUID(),broker=http.createServer(async(request,response)=>{ + try{ + assert.equal(request.method,'POST');assert.equal(request.url,'/fsync');assert.equal(request.headers.authorization,'Bearer '+durabilityNonce); + const chunks=[];let size=0;for await(const chunk of request){size+=chunk.length;assert.ok(size<4096);chunks.push(chunk);} + const value=JSON.parse(Buffer.concat(chunks)),file=path.resolve(value.path),real=fs.realpathSync.native(file); + assert.ok(real.startsWith(fs.realpathSync.native(runDirectory)+path.sep));assert.equal(real,file);assert.equal(fs.lstatSync(file).isSymbolicLink(),false); + const fd=fs.openSync(file,'r+');try{const stat=fs.fstatSync(fd,{bigint:true});assert.ok(stat.isFile()); + for(const key of ['dev','ino','size'])assert.equal(String(stat[key]),value[key]);fs.fsyncSync(fd); + durabilityReceipts.push({path:path.relative(runDirectory,file),dev:value.dev,ino:value.ino,size:value.size,operation:'actual-parent-fsync',sha256:sha(fs.readFileSync(fd))}); + }finally{fs.closeSync(fd);}response.writeHead(200,{'Content-Type':'application/json'});response.end('{"flushed":true}'); + }catch(error){response.writeHead(409);response.end(error.message);} + });await new Promise(resolve=>broker.listen(0,'127.0.0.1',resolve));activeBroker=broker; + let requests=0,toolCalls=0;const driver=new ControlledDeepSeekSession(installation,{timeoutMs:20000,clientFactory(launch,options){ + const isolatedProfile=path.join(runDirectory,'home'); + Object.assign(launch.env,{USERPROFILE:isolatedProfile,APPDATA:isolatedProfile,LOCALAPPDATA:isolatedProfile, + AWB_OWNED_DURABILITY_ENDPOINT:'http://127.0.0.1:'+broker.address().port+'/fsync',AWB_OWNED_DURABILITY_NONCE:durabilityNonce}); + // Windows JSONL durability checks stat every existing ancestor including + // the drive root. Delegate only these real directory metadata snapshots; + // granting root read would also grant unrelated file contents. + const directoryMetadata={}; + for(let ancestor=path.dirname(runDirectory);;ancestor=path.dirname(ancestor)){ + assert.equal(fs.lstatSync(ancestor).isSymbolicLink(),false);const stats=fs.statSync(ancestor);assert.ok(stats.isDirectory()); + directoryMetadata[ancestor]=stats;directoryMetadata[path.toNamespacedPath(ancestor)]=stats;if(path.dirname(ancestor)===ancestor)break; + } + const metadataFile=path.join(runDirectory,'ancestor-metadata.json');fs.writeFileSync(metadataFile,JSON.stringify(directoryMetadata)); + launch.env.AWB_OWNED_DIRECTORY_METADATA=metadataFile; + launch.env.AWB_OWNED_MODULE_INPUTS=path.join(runDirectory,'loaded-module-inputs.jsonl'); + const patchFile=launch.args.at(-1),patch=JSON.parse(fs.readFileSync(patchFile)); + patch.push({insert:[{id:'workbench-original-purge-probe',name:wrapperFile,config:{entry:pathToFileURL(path.join(ownSource,'lib/index.js')).href, + sourceUrl:pathToFileURL(ownSource+path.sep).href,llmModule:installation.llmModule,inputs:inputUrls, + originalConfig:config,protectedPath,marker}}]});fs.writeFileSync(patchFile,JSON.stringify(patch)); + driver.report.launchInputs.patch=engineFileIdentity(patchFile);driver.report.launchInputs.originalSource=inputs; + // Harness requires its native builtin loader. Node fs/child probes are + // checked below; this profile is NOT an OS sandbox for arbitrary addons. + // It is restricted to a byte-locked, keyless loading experiment. + const readRoots=[installation.root,path.dirname(process.execPath),path.resolve(path.dirname(process.execPath),'..','lib','node','*'),runDirectory,cwd,ownSource,wrapperFile,accessLogFile]; + for(const anchor of [installation.root,cwd,ownSource])for(let ancestor=path.dirname(anchor);;ancestor=path.dirname(ancestor)){ + readRoots.push(path.join(ancestor,'node_modules','*'),path.join(ancestor,'package.json'));if(path.dirname(ancestor)===ancestor)break; + } + const args=['--permission','--allow-addons',...readRoots.flatMap(root=>['--allow-fs-read='+root,'--allow-fs-read='+path.toNamespacedPath(root)]), + '--allow-fs-write='+runDirectory,'--allow-fs-write='+path.toNamespacedPath(runDirectory),'--import',pathToFileURL(accessLogFile).href,...launch.args]; + return new McpStdio({...launch,args},options); + }});active=driver; + const start=Date.now();let error=null,text=null,ready; + try{ + await driver.open({directory:runDirectory,cwd,owner,sdkSessionId:randomUUID(),tools:[{type:'function',function:{name:'owned_probe',description:'An owned probe that must not be called.',parameters:{type:'object',properties:{},additionalProperties:false}}}],config:{model:'owned-original-purge-probe',maxOutputTokens:512,contextLimit:16000,maxRunDurationMs:30000}, + onTool:async()=>{toolCalls++;throw new Error('No tool execution is permitted in this loading probe.');}, + onModel:async input=>{requests++;modelInputs.push({scenario,input}); + if(requests>1)throw new Error('Owned host stops after the first rejected tool result; no further model response is supplied.'); + if(scenario==='failed-no-retry')throw new Error('Owned failure; no upstream model contacted.'); + if(scenario==='blocked-purge-apply'||scenario==='host-denied-tool')return {message:{role:'assistant',content:'',tool_calls:[{id:'owned-rejected-call',type:'function', + function:{name:scenario==='blocked-purge-apply'?'purge_apply':'owned_probe',arguments:'{}'}}]},usage:{prompt_tokens:123,completion_tokens:7,total_tokens:130},finishReason:'tool_calls'}; + return {message:{role:'assistant',content:'Owned loading probe complete.'},usage:{prompt_tokens:123,completion_tokens:7,total_tokens:130},finishReason:'stop'};}}); + ready=JSON.parse(fs.readFileSync(marker));assert.equal(ready.originalApplyCalled,true);assert.equal(ready.pid,driver.client.pid); + assert.deepEqual(ready.blockedTools.sort(),['purge_apply','purge_revert','purge_status']);assert.ok(Object.values(ready.denied).every(Boolean)); + assert.equal(ready.loaded.length,closure.size); + if(scenario==='completed'){ + const before=durabilityReceipts.length,stat=fs.statSync(marker,{bigint:true}); + for(const [name,authorization,value] of [ + ['unowned-auth','Bearer owned-invalid-auth',{path:marker}], + ['outside-runtime','Bearer '+durabilityNonce,{path:protectedPath}], + ['wrong-file-identity','Bearer '+durabilityNonce,{path:marker,dev:String(stat.dev),ino:'0',size:String(stat.size)}], + ]){ + const response=await fetch('http://127.0.0.1:'+broker.address().port+'/fsync',{method:'POST',headers:{Authorization:authorization,'Content-Type':'application/json'},body:JSON.stringify(value)}); + await response.text();assert.equal(response.status,409);brokerRejections.push({name,status:response.status}); + } + assert.equal(durabilityReceipts.length,before);assert.deepEqual(fs.readFileSync(protectedPath),beforeSentinel); + } + await driver.prompt('Return the owned loading probe result. Do not call tools.');text=await driver.wait(); + }catch(failure){error=failure.stack;} + const processReport=await driver.close({force:!!error}).catch(failure=>({cleanupError:failure.stack,cleanup:null}));active=null;assertControlledInstallation(installation); + broker.closeAllConnections();await new Promise(resolve=>broker.close(resolve));activeBroker=null; + const moduleInputsFile=path.join(runDirectory,'loaded-module-inputs.jsonl'),moduleInputs=fs.existsSync(moduleInputsFile)?fs.readFileSync(moduleInputsFile,'utf8').trim().split(/\r?\n/).filter(Boolean).map(line=>JSON.parse(line)):[]; + for(const input of moduleInputs)assert.equal(sha(fs.readFileSync(input.path)),input.sha256); + const item={scenario,requests,toolCalls,text,error,ready,processReport,durabilityReceipts,brokerRejections,moduleInputs,elapsedMs:Date.now()-start};results.push(item); + fs.writeFileSync(path.join(base,'result.json'),JSON.stringify(item,null,2)); + assert.equal(requests,['blocked-purge-apply','host-denied-tool'].includes(scenario)?2:1,JSON.stringify({scenario,error,ready})); + if(scenario==='completed'){assert.equal(error,null);assert.equal(text,'Owned loading probe complete.');}else assert.ok(error); + assert.equal(toolCalls,scenario==='host-denied-tool'?1:0); + assert.equal(processReport.cleanup.rootExited,true);assert.equal(processReport.cleanup.treeConfirmed,true); + if(scenario==='completed'){assert.equal(processReport.status,'closed',processReport.error);assert.equal(processReport.cleanup.exit.code,0);} + } + assert.deepEqual(fs.readFileSync(protectedPath),beforeSentinel); + for(const input of inputs){assert.equal(sha(fs.readFileSync(path.join(source,input.relative))),input.sha256);assert.equal(sha(fs.readFileSync(path.join(ownSource,input.relative))),input.sha256);} + for(const {input} of modelInputs){const text=[input.system??'',...input.messages.filter(message=>message.role==='system').flatMap(message=>message.content.filter(block=>block.type==='text').map(block=>block.text))].join('\n'); + assert.equal(text.split(config.postPrompt).length-1,1);} + fs.writeFileSync(path.join(directory,'result.json'),JSON.stringify({passed:true,results,inputs,closure:[...closure].sort(),externals:[...externals],installation,config, + realModelRequests:0,upstreamPatchInstalled:false,productionStrategyImplemented:false,nativeAddonIsolation:'not_an_os_sandbox', + scope:'Original entry/load/config/permission/retry feasibility only; external tool registration restricted, original host-modifying patch omitted. No real model, autonomy or Purge benefit measured.'},null,2)); + console.log(JSON.stringify({passed:true,directory,scenarios:results.length,originalModules:closure.size,realModelRequests:0})); +}catch(error){fs.writeFileSync(path.join(directory,'result.json'),JSON.stringify({passed:false,error:error.stack,results,inputs,installation,config,realModelRequests:0},null,2)); + console.log(JSON.stringify({passed:false,directory,error:error.stack,realModelRequests:0}));process.exitCode=1; +}finally{await active?.close({force:true}).catch(()=>{});if(activeBroker){activeBroker.closeAllConnections();await new Promise(resolve=>activeBroker.close(resolve));}fs.writeFileSync(path.join(directory,'model-inputs.json'),JSON.stringify(modelInputs,null,2));} diff --git a/task_plan.md b/task_plan.md index 76d84c33..784dfae2 100644 --- a/task_plan.md +++ b/task_plan.md @@ -8,7 +8,7 @@ A已提交0a58c0d/6257bba并封存。继续先完成网络与报告中的确定 2. [complete] Provider所属双栈与代理/NO_PROXY连接策略;未知POST不自动重发/切池,明确完整预发送错误链才可重试。HTTP正文中断保留有界原片段、上游请求ID与未知消费;取消后关闭所属dispatcher,可显式重建。 3. [complete] 自有双栈/代理/绕过、未知POST/正文、取消复用与工具不重放包含在94/94相关回归;构建通过。engine-worker原14/14和最终编译宿主200/503正文中断、冷却后显式续接2/2分别通过。A原621份/646工件/20夹具请求离线核对保持。 4. [complete] C实际Task模型身份、同线路已知usage校准后续预留、每次重试/切池前核对、单次超额后保留原错误并停止均完成。最终425输入冻结后149/149、构建、Chat/Responses固定16K各5组工程链路和编译UI两视口通过并目视回看;A/B/原真实六例离线核验保持。见docs/QA-LIVE-BUDGET-C.md,源码与证据分次本地提交,不改正式宿主。 -5. [in_progress] D原版Purge隔离只读预研:确认默认重试/权限及原patch额外组件,下一固定完整加载输入和独立home/配置/工作区,保留宿主外部审批和受限桥。未加载原版插件、未发真实模型请求,E新真实批次仍待D验收。 +5. [in_progress] D无Key原版入口加载研究已完成:60原包文件/31模块、四场景/六桥调用/正常退出码0、外部工具拒绝和三项落盘broker负例通过;335观察模块/场景,逐原字节封存。明确autoRetry/continue/宿主修改关闭,外部权限适配与allow-addons的非OS沙箱限制见docs/ORIGINAL-PURGE-LOAD-REVIEW.md。生产策略/Task账本/原生隔离边界待实现,D不标完整完成,E新真实批次仍未开跑。 B原94/94、构建和A封存通过。编译/引擎首轮14/16与状态复核0/2保留:两项是验收在原连接冷却结束前立刻续接,最终按原cooldownUntil等待后2/2,未重复已通过14项。B见docs/QA-LIVE-NETWORK-B.md。一次猜测budget.mjs不存在已改按rg实际定位execution.mjs;文档新增尾空行已清理。