feat: integrate DSH with audited isolated Git repairs
This commit is contained in:
1 parent
7104b6745c
commit
e2b3e66a5b
29 files changed
+381
-50
No files matched your search
@@ -22,16 +22,16 @@ test('chat UI persists conversations, shows escaped messages and explicit fixed
|
||||
const {base,store,checks}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_UI_KEY',allowActions:true});
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));page.setDefaultTimeout(15000);
|
||||
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();
|
||||
await page.getByLabel('发送给 ZCode',{exact:true}).fill('分析订单运行状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();assert.equal(await page.locator('.assistant-reply img').count(),0);assert.equal(checks(),0);
|
||||
await page.getByLabel('发送给 DSH',{exact:true}).fill('分析订单运行状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();assert.equal(await page.locator('.assistant-reply img').count(),0);assert.equal(checks(),0);
|
||||
await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();await page.getByText('操作已完成',{exact:true}).waitFor();assert.equal(checks(),1);await page.reload();await page.locator('.assistant-reply').getByText('已读取运行状态。<img src=x onerror=alert(1)>',{exact:true}).waitFor();
|
||||
await page.getByLabel('发送给 ZCode',{exact:true}).fill('挂起诊断');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'停止回复',exact:true}).click();await page.getByText('已停止本轮回复。',{exact:true}).waitFor();
|
||||
await page.getByLabel('发送给 DSH',{exact:true}).fill('挂起诊断');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'停止回复',exact:true}).click();await page.getByText('已停止本轮回复。',{exact:true}).waitFor();
|
||||
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/zcode-chat-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
|
||||
test('a long action displays persisted sampling progress before its POST completes',{timeout:60000},async t=>{
|
||||
const {base,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_PROGRESS_KEY',allowActions:true});
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(8000);
|
||||
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.getByLabel('发送给 ZCode',{exact:true}).fill('读取状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).waitFor();
|
||||
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.getByLabel('发送给 DSH',{exact:true}).fill('读取状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).waitFor();
|
||||
let started=false,finished=false,release;const gate=new Promise(resolve=>release=resolve);t.after(()=>release());
|
||||
await page.route('**/api/assistant/conversations/*',async route=>{const response=await route.fetch(),data=await response.json();if(started)for(const turn of data.turns)for(const action of turn.actions||[])Object.assign(action,{status:finished?'success':'running',progress:{completed:1,total:3,captured:1,failed:0}});await route.fulfill({json:data});});
|
||||
await page.route('**/api/assistant/conversations/*/actions/*/execute',async route=>{started=true;await gate;finished=true;await route.fulfill({json:{status:'success'}});});
|
||||
@@ -49,3 +49,8 @@ test('personal conversation UI archives, pages and restores evidence without sen
|
||||
await page.getByLabel('会话范围',{exact:true}).selectOption('active');await page.locator('[data-assistant-conversation]').first().waitFor();
|
||||
assert.equal(store.listConversations(store.db.prepare('SELECT owner FROM conversations').get().owner,{scope:'archived'}).total,0);assert.equal(store.usage().calls,0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
});
|
||||
test('admin reviews selected code changes before isolated repair and sees the rollback result',{timeout:120000},async t=>{
|
||||
const {base,store,assistant}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/anthropic',model:'fixture',apiKey:'PRIVATE_REPAIR_KEY',allowActions:true,allowCodeRepair:true,repairRepository:process.cwd()});let runs=0;assistant.repairFactory=()=>({readSources:paths=>{assert.deepEqual(paths,['src/demo.cjs']);return {baselineCommit:'a'.repeat(40),files:[{path:'src/demo.cjs',content:'BEFORE'}]};},run:async()=>{runs++;return {operationId:'repair-test',status:'rolled_back',previousCommit:'a'.repeat(40),resultCommit:'b'.repeat(40),testOutcome:'failed'};}});assistant.runtime.chat=async()=>JSON.stringify({reply:'修复建议',actions:[],repair:{files:[{path:'src/demo.cjs',content:'AFTER'}]}});
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:1440,height:1000}});await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByText('提出代码修复',{exact:true}).click();await page.locator('#repair-paths').fill('src/demo.cjs');await page.locator('#repair-goal').fill('修复问题');await page.getByRole('button',{name:'生成修复建议',exact:true}).click();await page.getByText('修复建议',{exact:true}).waitFor();assert.equal(runs,0);await page.getByText('src/demo.cjs · 查看修改前后',{exact:true}).click();await page.getByText('BEFORE',{exact:true}).waitFor();await page.getByText('AFTER',{exact:true}).waitFor();await page.getByRole('button',{name:'执行:审查并执行隔离代码修复',exact:true}).click();await page.getByText('测试未通过,已回退',{exact:true}).waitFor();assert.equal(runs,1);
|
||||
});
|
||||
test('operation history loads older audit events instead of hiding everything beyond the newest hundred',{timeout:120000},async t=>{const {base,assistant}=await fixture(t);const events=Array.from({length:125},(_,i)=>({id:125-i,operationId:'op-'+i,actor:'admin-fixture',createdAt:'2026-10-27T01:00:00Z',step:'model',status:'success',detail:'TRACE-'+i}));assistant.journal={list:({beforeId})=>events.filter(e=>!beforeId||e.id<beforeId).slice(0,100)};const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByText('TRACE-0',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-124',{exact:true}).count(),0);await page.getByRole('button',{name:'加载更早记录',exact:true}).click();await page.getByText('TRACE-124',{exact:true}).waitFor();assert.equal(await page.getByText('TRACE-0',{exact:true}).count(),1);});
|
||||
@@ -70,9 +70,9 @@ test('a cancellation signal alone cannot label an unconfirmed runtime failure as
|
||||
await new Promise(resolve=>setImmediate(resolve));service.cancel(c.id,admin);await service.running.get(turn.id).task;
|
||||
assert.equal(store.conversation(c.id,admin.user.id).turns[0].status,'error');
|
||||
});
|
||||
test('only a matching installed runtime is discovered, without enabling the model',async t=>{
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),crypto=require('node:crypto'),root=await fs.mkdtemp(path.join(os.tmpdir(),'order-zcode-discovery-')),dir=path.join(root,'assistant'),install=path.join(root,'zcode-runtime'),runtimePath=path.join(install,'3.14.3/package/resources/glm/zcode.cjs');t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
await fs.mkdir(path.dirname(runtimePath),{recursive:true});await fs.writeFile(runtimePath,'fixture');await fs.writeFile(path.join(install,'manifest.json'),JSON.stringify({releaseVersion:'3.14.3',cliVersion:'0.16.9',runtimePath,runtimeSha256:'sha256:'+crypto.createHash('sha256').update('fixture').digest('hex')}));
|
||||
const store=new AssistantStore(dir);assert.equal(store.settings().runtimePath,runtimePath);assert.equal(store.settings().enabled,false);assert.equal(store.settings().hasApiKey,false);store.close();
|
||||
await fs.writeFile(runtimePath,'modified');const changed=new AssistantStore(dir);try{assert.equal(changed.settings().runtimePath,'');}finally{changed.close();}
|
||||
test('only a pinned DSH runtime is discovered without enabling a model',async t=>{
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs');
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'order-dsh-discovery-')),old=process.env.LOCALAPPDATA;process.env.LOCALAPPDATA=root;t.after(async()=>{if(old===undefined)delete process.env.LOCALAPPDATA;else process.env.LOCALAPPDATA=old;await fs.rm(root,{recursive:true,force:true});});
|
||||
const base=path.join(root,'OrderNotificationAutomationRuntimes/dsh-0.2.1-rc.2/node_modules/@deepseek-ai/dsh'),runtimePath=path.join(base,'lib/bin.js');await fs.mkdir(path.dirname(runtimePath),{recursive:true});await fs.writeFile(runtimePath,'fixture');await fs.writeFile(path.join(base,'package.json'),JSON.stringify({name:'@deepseek-ai/dsh',version:'0.2.1-rc.2'}));
|
||||
const store=new AssistantStore(path.join(root,'assistant'));assert.equal(store.settings().runtimePath,runtimePath);assert.equal(store.settings().enabled,false);assert.equal(store.settings().hasApiKey,false);store.close();await fs.writeFile(path.join(base,'package.json'),JSON.stringify({name:'@deepseek-ai/dsh',version:'unverified'}));const changed=new AssistantStore(path.join(root,'assistant'));try{assert.equal(changed.settings().runtimePath,'');}finally{changed.close();}
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {AssistantStore}=require('../../src/modules/assistant/store.cjs'),{AssistantService}=require('../../src/modules/assistant/service.cjs'),{OperationJournal}=require('../../src/modules/assistant/operation-journal.cjs');
|
||||
const admin={user:{id:'u1',username:'admin',role:'admin'}},viewer={user:{id:'u2',username:'viewer',role:'viewer'}};
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'controlled-ai-')),store=new AssistantStore(dir),journal=new OperationJournal({file:path.join(dir,'ops.sqlite')});t.after(async()=>{await service.stop();journal.close();store.close();fs.rmSync(dir,{recursive:true,force:true});});store.saveSettings({...store.settings(),apiKey:'TEST-KEY-PRIVATE',enabled:true,runtimePath:path.join(dir,'runtime.js'),apiBase:'https://example.test/anthropic',model:'fixture',allowActions:true,allowCodeRepair:true,repairRepository:dir});let called=0;const repair={readSources:()=>({baselineCommit:'a'.repeat(40),files:[{path:'src/a.cjs',content:'module.exports=1;'}]}),run:async input=>{called++;assert.equal(input.expectedCommit,'a'.repeat(40));return {operationId:'repair-1',status:'rolled_back',previousCommit:input.expectedCommit,resultCommit:'b'.repeat(40),testOutcome:'failed'};}};const runtime={probe:async()=>({available:true}),chat:async input=>{assert.equal(input.context.repair.files[0].path,'src/a.cjs');return JSON.stringify({reply:'修复建议',actions:[],repair:{files:[{path:'src/a.cjs',content:'module.exports=2;'}]}});}};const service=new AssistantService({store,runtime,journal,repairFactory:()=>repair});return {store,journal,service,calls:()=>called};}
|
||||
test('admin selected source becomes a reviewed repair proposal; execution and rollback result remain auditable',async t=>{const f=fixture(t),c=f.store.create('u1'),turn=f.service.sendRepair(c.id,admin,'修复测试',['src/a.cjs']);await f.service.running.get(turn.id).task;const saved=f.store.conversation(c.id,'u1').turns[0];assert.equal(saved.status,'success',saved.error);assert.equal(f.calls(),0);const action=saved.actions[0];assert.equal(action.kind,'repair_code');assert.equal(action.beforeFiles[0].content,'module.exports=1;');const result=await f.service.executeAction(c.id,action.id,admin);assert.equal(result.result.status,'rolled_back');assert.equal(f.calls(),1);assert(f.service.operations(admin).length>=4);assert.deepEqual(f.service.operations(viewer),[]);assert.doesNotMatch(JSON.stringify(f.service.operations(admin)),/TEST-KEY-PRIVATE/);await assert.rejects(f.service.executeAction(c.id,action.id,admin),e=>e.status===409);});
|
||||
test('repair permission is checked again at execution and viewers cannot request code',async t=>{const f=fixture(t),c=f.store.create('u1'),turn=f.service.sendRepair(c.id,admin,'修复测试',['src/a.cjs']);await f.service.running.get(turn.id).task;const a=f.store.conversation(c.id,'u1').turns[0].actions[0];f.store.saveSettings({...f.store.settings(),apiKey:'',allowCodeRepair:false});await assert.rejects(f.service.executeAction(c.id,a.id,admin),e=>e.status===403);assert.equal(f.calls(),0);assert.throws(()=>f.service.sendRepair(c.id,viewer,'修改',['src/a.cjs']),e=>e.status===403);});
|
||||
test('repair response cannot change unselected paths or expose the configured model key',()=>{const {parseRepairResponse}=require('../../src/modules/assistant/repair-response.cjs'),context={baselineCommit:'a'.repeat(40),files:[{path:'src/a.cjs',content:'old'}]};for(const file of [{path:'src/b.cjs',content:'new'},{path:'src/a.cjs',content:'SECRET-CONFIG-KEY'}])assert.throws(()=>parseRepairResponse(JSON.stringify({reply:'proposal',actions:[],repair:{files:[file]}}),{},admin.user,context,'SECRET-CONFIG-KEY'));assert.throws(()=>parseRepairResponse(JSON.stringify({reply:'proposal',actions:[],repair:{files:[{path:'src/a.cjs',content:'new'}]}}),{},admin.user,null,''));});
|
||||
test('audit failure stops before calling the model and leaves a recoverable error turn',async t=>{const f=fixture(t),c=f.store.create('u1');f.journal.append=()=>{throw Error('journal unavailable');};assert.throws(()=>f.service.sendRepair(c.id,admin,'repair',['src/a.cjs']),e=>e.status===503);assert.equal(f.store.conversation(c.id,'u1').turns[0].status,'error');assert.equal(f.service.running.size,0);});
|
||||
test('business diagnosis includes authorized automatic orders and blockers without fields or frozen mail bodies',()=>{const {snapshot}=require('../../src/modules/assistant/policy.cjs'),rows={orders:[{id:'own',sample:{connectionId:'a',fields:{secret:'PRIVATE-FIELD'}},event:{orderNo:'123',connectionId:'a',processName:'流程',nodeName:'通知'},status:'pending',archive:{files:[{}]}},{id:'hidden',sample:{connectionId:'b'},event:{orderNo:'999'},status:'failed'}],batches:[], 'execution-tasks':[{id:'task',connectionId:'a',status:'blocked',error:'missing field',row:{processName:'流程',nodeName:'通知'}}]},workspace={snapshot:()=>({connections:[{id:'a',owner:'operator'},{id:'b',owner:'other'}],exceptions:[]}),recordSources:()=>[{id:'a',owner:'operator'},{id:'b',owner:'other'}]},s=snapshot({workspace,orderRules:{all:k=>rows[k]||[]}},{id:'op',username:'operator',role:'operator'});assert.equal(s.business.orders.length,1);assert.equal(s.business.blockers[0].id,'task');assert.doesNotMatch(JSON.stringify(s.business),/PRIVATE-FIELD|999/);});
|
||||
@@ -0,0 +1,7 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),path=require('node:path'),{spawnSync}=require('node:child_process');
|
||||
test('DSH installer read-only check verifies the pinned installed runtime',t=>{
|
||||
if(!require('../../src/modules/assistant/dsh-runtime.cjs').installedRuntime())return t.skip('Pinned DSH runtime is not installed');
|
||||
const result=spawnSync(process.execPath,[path.resolve(__dirname,'../../scripts/install-dsh-runtime.cjs'),'--check'],{encoding:'utf8',windowsHide:true});assert.equal(result.status,0,result.stderr);const value=JSON.parse(result.stdout);assert.equal(value.version,'0.2.1-rc.2');assert.equal(value.package,'@deepseek-ai/dsh');assert.equal(value.available,true);assert.ok(value.runtimePath.endsWith(path.join('dsh','lib','bin.js')));
|
||||
});
|
||||
test('DSH installer rejects unknown options before installation',()=>{const result=spawnSync(process.execPath,[path.resolve(__dirname,'../../scripts/install-dsh-runtime.cjs'),'--unsafe'],{encoding:'utf8',windowsHide:true});assert.equal(result.status,1);assert.match(result.stderr,/Unsupported option/);});
|
||||
@@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),http=require('node:http');
|
||||
const adapter=()=>require('../../src/modules/assistant/dsh-runtime.cjs');
|
||||
test('NDJSON requires one successful final and never returns reasoning',()=>{
|
||||
const {parseOutput}=adapter();
|
||||
assert.equal(parseOutput('{"type":"thinking","text":"secret reasoning"}\n{"type":"status","phase":"turn_end","reason":{"kind":"completed"}}\n{"type":"final","text":"{\\"reply\\":\\"ok\\",\\"actions\\":[]}"}\n'),'{"reply":"ok","actions":[]}');
|
||||
for(const value of ['garbage','{"type":"thinking","text":"private"}','{"type":"final","reason":"max_tokens","text":"partial"}','{"type":"error","message":"provider secret"}\n{"type":"final","reason":{"kind":"completed"},"text":"ok"}'])assert.throws(()=>parseOutput(value));
|
||||
});
|
||||
test('environment drops ambient secrets, proxy, node injection and DSH profile overrides',()=>{
|
||||
const {environment}=adapter();process.env.NODE_OPTIONS='--inspect';process.env.DSH_SYSTEM_PROMPT='override';process.env.HTTP_PROXY='http://bad';
|
||||
try{const env=environment('C:/isolated','key-only-child');assert.equal(env.NODE_OPTIONS,undefined);assert.equal(env.DSH_SYSTEM_PROMPT,undefined);assert.equal(env.HTTP_PROXY,undefined);assert.equal(env.DEEPSEEK_API_KEY,'key-only-child');assert.equal(env.DSH_HOME,path.join('C:/isolated','.dsh'));}finally{delete process.env.NODE_OPTIONS;delete process.env.DSH_SYSTEM_PROMPT;delete process.env.HTTP_PROXY;}
|
||||
});
|
||||
function sse(text){return [
|
||||
{type:'message_start',message:{id:'local-test',type:'message',role:'assistant',model:'deepseek-flash',content:[],usage:{input_tokens:3,output_tokens:0}}},
|
||||
{type:'content_block_start',index:0,content_block:{type:'text',text}},
|
||||
{type:'content_block_stop',index:0},
|
||||
{type:'message_delta',delta:{stop_reason:'end_turn'},usage:{output_tokens:5}},
|
||||
{type:'message_stop'}].map(e=>`event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join('');}
|
||||
test('installed official DSH calls local Messages endpoint without native tools and cleans profile',{timeout:90000},async t=>{
|
||||
const {DshRuntime,installedRuntime}=adapter();const entry=installedRuntime();if(!entry)return t.skip('Pinned DSH runtime is not installed');
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-real-test-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
const requests=[];const server=http.createServer((req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{requests.push({url:req.url,headers:req.headers,body:JSON.parse(body)});res.writeHead(200,{'content-type':'text/event-stream'});res.end(sse('{"reply":"local model works","actions":[]}'));});});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
|
||||
const runtime=new DshRuntime({stateDir:root});assert.equal((await runtime.probe(entry)).available,true);
|
||||
const answer=await runtime.chat({config:{runtimePath:entry,apiBase:`http://127.0.0.1:${server.address().port}/anthropic`,apiKey:'local-test-secret',model:'deepseek-flash',timeoutSeconds:45,allowActions:false},text:'诊断',history:[],context:{status:'test'},signal:new AbortController().signal});
|
||||
assert.equal(JSON.parse(answer).reply,'local model works');assert.equal(requests.length,1);assert.equal(requests[0].url,'/anthropic/v1/messages');assert.deepEqual(requests[0].body.tools??[],[]);assert.equal(requests[0].headers['x-api-key'],'local-test-secret');assert.deepEqual(await fs.readdir(runtime.runs),[]);
|
||||
});
|
||||
|
||||
test('timeout terminates the Windows descendant tree and bounds output and cancellation',{timeout:20000},async t=>{
|
||||
const {invoke,environment}=adapter();const root=await fs.mkdtemp(path.join(os.tmpdir(),'dsh-child-test-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
||||
const childFile=path.join(root,'child.cjs');await fs.writeFile(childFile,"const fs=require('fs'),{spawn}=require('child_process');const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore',windowsHide:true});fs.writeFileSync('pid',String(child.pid));setInterval(()=>{},1000);");
|
||||
await assert.rejects(invoke(childFile,[],{cwd:root,env:environment(root),timeout:800}),e=>e.status===504);const pid=Number(await fs.readFile(path.join(root,'pid'),'utf8'));assert.throws(()=>process.kill(pid,0));
|
||||
await fs.writeFile(childFile,"process.stdout.write('x'.repeat(2048));setInterval(()=>{},1000)");await assert.rejects(invoke(childFile,[],{cwd:root,env:environment(root),maxBytes:1024,timeout:3000}),e=>e.status===502);
|
||||
const controller=new AbortController();controller.abort();await assert.rejects(invoke(childFile,[],{cwd:root,env:environment(root),signal:controller.signal}),e=>e.status===499);
|
||||
});
|
||||
test('profile never persists the model key and only approved repair content is included',()=>{
|
||||
const {profilePatch,prompt}=adapter(),config={apiBase:'https://example.com/anthropic',model:'deepseek-flash',apiKey:'sensitive-key',timeoutSeconds:30,allowActions:false};assert.ok(!profilePatch(config).includes('sensitive-key'));
|
||||
const content='x'.repeat(4000);const text=prompt({config,text:'review',history:[],context:{repair:{files:[{path:'src/test.cjs',content}]}}});assert.ok(text.includes(content));assert.ok(text.includes('repair:{files:'));
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{execFileSync}=require('node:child_process');
|
||||
const {OperationJournal}=require('../../src/modules/assistant/operation-journal.cjs');
|
||||
const {CodeRepairRunner}=require('../../src/modules/assistant/code-repair.cjs');
|
||||
function fixture(t,code='process.exit(0)'){
|
||||
const base=fs.mkdtempSync(path.join(os.tmpdir(),'repair-test-')),repo=path.join(base,'repo'),repairs=path.join(base,'repairs');fs.mkdirSync(repo);fs.mkdirSync(path.join(repo,'src'));fs.writeFileSync(path.join(repo,'src','app.cjs'),'original');
|
||||
const git=(...args)=>execFileSync('git',['-c','user.name=Test','-c','user.email=test@example.invalid',...args],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();git('init');git('add','.');git('commit','-m','baseline');
|
||||
const journal=new OperationJournal({file:path.join(base,'audit.sqlite'),secrets:['private-test-secret']});
|
||||
const runner=new CodeRepairRunner({repoRoot:repo,repairRoot:repairs,journal,validator:{command:process.execPath,args:['-e',code],timeoutMs:1000}});
|
||||
t.after(()=>{journal.close();fs.rmSync(base,{recursive:true,force:true});});return {base,repo,repairs,git,journal,runner};
|
||||
}
|
||||
const request={actor:'admin',isAdmin:true,files:[{path:'src/app.cjs',content:'changed'}]};
|
||||
test('successful validation keeps active checkout untouched and leaves committed proposal',async t=>{const f=fixture(t),baseline=f.git('rev-parse','HEAD'),r=await f.runner.run(request);assert.equal(r.status,'ready_for_review');assert.notEqual(r.resultCommit,baseline);assert.equal(f.git('rev-parse','HEAD'),baseline);assert.equal(fs.readFileSync(path.join(f.repo,'src/app.cjs'),'utf8'),'original');assert.equal(f.git('show',r.resultCommit+':src/app.cjs'),'changed');assert.match(r.diff,/changed/);});
|
||||
test('failed validation rolls isolated files back and retains proposal evidence',async t=>{const f=fixture(t,'process.exit(2)'),r=await f.runner.run(request);assert.equal(r.status,'rolled_back');assert.equal(fs.readFileSync(path.join(r.worktree,'src/app.cjs'),'utf8'),'original');assert.equal(f.git('show',r.resultCommit+':src/app.cjs'),'changed');assert.equal(f.git('rev-parse',r.branch),r.resultCommit);});
|
||||
test('rejects traversal, reserved files, credentials and non-admin callers before changes',async t=>{const f=fixture(t);for(const name of ['src/../app.cjs','src/.git/config','src/node_modules/a.js','src/.env','src/output/a.js','package.json','src/CON.js','src/foo:bar.js'])await assert.rejects(f.runner.run({...request,files:[{path:name,content:'x'}]}));await assert.rejects(f.runner.run({...request,isAdmin:false}));assert.equal(f.git('status','--porcelain'),'');});
|
||||
test('dirty active checkout is rejected',async t=>{const f=fixture(t);fs.writeFileSync(path.join(f.repo,'src/app.cjs'),'unsaved');await assert.rejects(f.runner.run(request),/dirty/i);});
|
||||
test('journal redacts secrets, enforces actor scope and records restart uncertainty',t=>{const f=fixture(t);f.journal.append({operationId:'one',actor:'alice',step:'repair',status:'running',detail:'token=abc private-test-secret'});f.journal.append({operationId:'two',actor:'bob',step:'repair',status:'done'});assert.equal(f.journal.list({actor:'alice'}).length,1);assert.equal(f.journal.list({actor:'root',isAdmin:true}).length,2);assert.doesNotMatch(JSON.stringify(f.journal.list({actor:'alice'})),/abc|private-test-secret/);f.journal.recoverRunning();assert.equal(f.journal.list({actor:'alice'})[0].status,'needs_review');assert.equal(f.journal.list({actor:'alice'}).length,2);});
|
||||
test('timeout is uncertain, never falsely reported as rollback',async t=>{const f=fixture(t,'setTimeout(()=>{},10000)'),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.equal(r.recovery,'manual_review');assert.equal(fs.readFileSync(path.join(r.worktree,'src/app.cjs'),'utf8'),'changed');});
|
||||
test('parallel requests cannot start a second repair',async t=>{const f=fixture(t,'setTimeout(()=>process.exit(0),150)'),pending=f.runner.run(request);await assert.rejects(f.runner.run(request),/already running/);assert.equal((await pending).status,'ready_for_review');});
|
||||
test('symlink or junction source ancestors cannot be proposed',async t=>{const f=fixture(t),external=path.join(f.base,'external');fs.mkdirSync(external);fs.writeFileSync(path.join(external,'example.js'),'outside');fs.symlinkSync(external,path.join(f.repo,'src','linked'),process.platform==='win32'?'junction':'dir');f.git('add','.');f.git('commit','-m','link');await assert.rejects(f.runner.run({...request,files:[{path:'src/linked/example.js',content:'bad'}]}),/Symlinks/);assert.equal(fs.readFileSync(path.join(external,'example.js'),'utf8'),'outside');});
|
||||
test('validator tampering with worktree git pointer requires manual review without following it',async t=>{const f=fixture(t,"require('node:fs').unlinkSync('.git');require('node:fs').writeFileSync('.git','gitdir: missing-git')"),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.equal(r.recovery,'manual_review');});
|
||||
test('validator moving HEAD cannot produce a ready result for the original proposal',async t=>{const f=fixture(t,"require('node:child_process').execFileSync('git',['-c','core.hooksPath=/dev/null','reset','--hard','HEAD~1'])"),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.equal(r.recovery,'manual_review');});
|
||||
test('unrelated untracked drafts survive while proposal collision is rejected',async t=>{const f=fixture(t);fs.mkdirSync(path.join(f.repo,'docs'));fs.writeFileSync(path.join(f.repo,'docs/draft.md'),'user draft');assert.equal((await f.runner.run(request)).status,'ready_for_review');assert.equal(fs.readFileSync(path.join(f.repo,'docs/draft.md'),'utf8'),'user draft');await assert.rejects(f.runner.run({...request,files:[{path:'docs/draft.md',content:'overwrite'}]}),/untracked/i);});
|
||||
test('source reads are bounded tracked allowlisted files with baseline and stale proposals rejected',async t=>{const f=fixture(t),snapshot=f.runner.readSources(['src/app.cjs']);assert.equal(snapshot.baselineCommit,f.git('rev-parse','HEAD'));assert.deepEqual(snapshot.files,[{path:'src/app.cjs',content:'original'}]);fs.writeFileSync(path.join(f.repo,'src/draft.js'),'untracked');assert.throws(()=>f.runner.readSources(['src/draft.js']),/tracked/i);await assert.rejects(f.runner.run({...request,expectedCommit:'0'.repeat(40)}),/stale/i);});
|
||||
test('source reads do not silently truncate source code',t=>{const f=fixture(t),content='// example\n'.repeat(1000);fs.writeFileSync(path.join(f.repo,'src/app.cjs'),content);f.git('add','.');f.git('commit','-m','long source');assert.equal(f.runner.readSources(['src/app.cjs']).files[0].content,content);});
|
||||
test('journal prevents rewriting audit history and redacts quoted credentials',t=>{const f=fixture(t);f.journal.append({operationId:'quoted',actor:'alice',step:'test',status:'done',detail:'{"password":"sensitive-value"}'});assert.doesNotMatch(JSON.stringify(f.journal.list({actor:'alice'})),/sensitive-value/);assert.throws(()=>f.journal.db.exec('DELETE FROM operation_events'),/append-only/);assert.throws(()=>f.journal.db.exec("UPDATE operation_events SET actor='bob'"),/append-only/);});
|
||||
test('timeout terminates validator child and grandchild processes on Windows',{skip:process.platform!=='win32'},async t=>{
|
||||
const f=fixture(t),receipt=path.join(f.base,'pids.txt');
|
||||
const grandchild="require('node:fs').appendFileSync("+JSON.stringify(receipt)+",process.pid+'\\n');setInterval(()=>{},1000)";
|
||||
const child="require('node:fs').appendFileSync("+JSON.stringify(receipt)+",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e',"+JSON.stringify(grandchild)+"],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)";
|
||||
f.runner.validator.args=['-e',"require('node:fs').appendFileSync("+JSON.stringify(receipt)+",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e',"+JSON.stringify(child)+"],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)"];
|
||||
f.runner.validator.timeoutMs=2000;
|
||||
t.after(()=>{if(fs.existsSync(receipt))for(const pid of fs.readFileSync(receipt,'utf8').trim().split(/\s+/).map(Number))try{process.kill(pid);}catch{}});
|
||||
const result=await f.runner.run(request),pids=fs.readFileSync(receipt,'utf8').trim().split(/\s+/).map(Number);assert.equal(pids.length,3);assert.equal(result.status,'needs_review');assert.equal(result.recovery,'manual_review');assert.equal(result.processCleanup.method,'taskkill-tree');assert.equal(result.processCleanup.commandSucceeded,true);assert.equal(result.processCleanup.rootExited,true);assert.ok(fs.existsSync(f.runner.lockPath));for(const pid of pids)assert.throws(()=>process.kill(pid,0),{code:'ESRCH'});
|
||||
});
|
||||
test('validator cannot install rollback hooks unnoticed',async t=>{const f=fixture(t,"require('node:fs').writeFileSync(require('node:path').join('..','.disabled-hooks','post-checkout'),'#!/bin/sh\\nexit 0\\n')"),r=await f.runner.run(request);assert.equal(r.status,'needs_review');assert.ok(fs.existsSync(f.runner.lockPath));});
|
||||
test('source requiring redaction is rejected instead of returned as altered complete code',t=>{const f=fixture(t);for(const content of ['module.exports={password:input.password};','const example="private-test-secret";']){fs.writeFileSync(path.join(f.repo,'src/app.cjs'),content);f.git('add','.');f.git('commit','-m','source requiring review');assert.throws(()=>f.runner.readSources(['src/app.cjs']),/sensitive|redaction/i);}});
|
||||
test('journal cursor pages older actor-scoped history without overlaps',t=>{const f=fixture(t);for(let i=0;i<125;i++){f.journal.append({operationId:'alice-operation',actor:'alice',step:'event',status:'done'});f.journal.append({operationId:'bob-operation',actor:'bob',step:'event',status:'done'});}const first=f.journal.list({actor:'alice'});assert.equal(first.length,100);const beforeId=first.at(-1).id,second=f.journal.list({actor:'alice',operationId:'alice-operation',beforeId});assert.equal(second.length,25);assert.equal(new Set([...first,...second].map(row=>row.id)).size,125);assert.ok(second.every(row=>row.id<beforeId&&row.actor==='alice'));assert.deepEqual(f.journal.list({actor:'alice',operationId:'bob-operation',beforeId}),[]);for(const cursor of [0,-1,1.5,'2',null,NaN,Number.MAX_SAFE_INTEGER+1])assert.throws(()=>f.journal.list({actor:'alice',beforeId:cursor}),/cursor/i);});
|
||||
test('repair journal names file changes, Git commit, validation and review steps',async t=>{const f=fixture(t),r=await f.runner.run(request),steps=f.journal.list({actor:request.actor}).filter(e=>e.operationId===r.operationId).map(e=>e.step);for(const step of ['prepare','files_written','commit','validate','review'])assert(steps.includes(step),step);});
|
||||
test('long validation logs retain the final test summary in the audit record',async t=>{const f=fixture(t,"console.log('x'.repeat(24000));console.log('FINAL_TEST_SUMMARY passed')"),r=await f.runner.run(request),last=f.journal.list({actor:request.actor}).find(e=>e.operationId===r.operationId&&e.step==='review');assert.match(last.detail,/FINAL_TEST_SUMMARY passed/);});
|
||||
Reference in new issue
Block a user