Files
stack/packages/seat/tests/model-markers-confined.test.mjs
jason.woltje 362893d043 feat: integrate reviewed proxy page and managed model keys
Source-candidate: poe d9a564e6d20f5f0fd75ce45b12cbbf8bb4c9d568\nSource-candidate: magica38ba5762b06716db1dee00d0afec162656488f5c\nValidated321whole-file phase plus whole bus1349/model-proxy100/webui490; final gate tooling checks pending, not landed.
2026-10-26 12:04:21 -05:00

46 lines
6.3 KiB
JavaScript

// #650 direct marker proof through the existing confined runner and writable runDir.
// No new mounts, fake client configuration or live proxy.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Store } from '../../bus/src/store.mjs';
import { Broker } from '../../bus/src/broker.mjs';
import { serve } from '../../bus/src/server.mjs';
import { newRun, runnerOf, sessionEnv, spawnSession, writeSessionFile } from '../src/session.mjs';
import { startTimeOf } from '../src/proc.mjs';
import { sandboxProblem } from '../src/sandbox.mjs';
import { createLoader } from '../../plugins/src/loader.mjs';
const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
async function confined(t,{enabled=false}={}){
const root=fs.realpathSync(fs.mkdtempSync(join(tmpdir(),'marker650-')));let store,server,child,exited,runDir;
t.after(async()=>{const failures=[];if(child){try{child.kill('SIGTERM');let timer;try{await Promise.race([exited,new Promise(resolve=>{timer=setTimeout(()=>{child.kill('SIGKILL');resolve();},5000);})]);await exited;}finally{clearTimeout(timer);}}catch{failures.push('own-child-close');}}try{await server?.close();}catch{failures.push('server-close');}try{store?.close();}catch{failures.push('store-close');}try{fs.rmSync(root,{recursive:true,force:true});}catch{failures.push('root-cleanup');}if(failures.length)throw new AggregateError(failures.map(code=>Error(code)),'owned marker fixture cleanup failed');});
const dataRoot=join(root,'data');fs.mkdirSync(dataRoot,{mode:0o700});store=new Store(dataRoot);
const broker=new Broker({store,businesses:{demo:{id:'demo',human:'jason',arbiters:{technical:'pm',delivery:'pm'},roles:{pm:{authority:{withinRole:['message.send'],crossRole:[]}},coder:{authority:{withinRole:['message.send'],crossRole:[]}}}}}});
const brokerSocket=join(root,'bus.sock');server=await serve({broker,path:brokerSocket});
const made=newRun(dataRoot,'demo'),run=made.run;runDir=made.runDir;const workspace=join(root,'ws'),bundle=join(runDir,'bundle');fs.mkdirSync(workspace);fs.mkdirSync(bundle,{mode:0o700});
fs.writeFileSync(join(bundle,'prompt.md'),'# test\n');fs.writeFileSync(join(bundle,'policy.json'),JSON.stringify({harness:'pi',workspace,tools:[],typed:[],network:'none',needs:[],credentials:[]}));fs.writeFileSync(join(bundle,'tools.json'),'[]');
const adapter=join(root,'adapter.sh');fs.writeFileSync(adapter,"printf '%s' 'fx650-private-output'\nprintf 'done\\n' > \"$MOSAIC_TURN_MARKER\"\n",{mode:0o644});
if(enabled)fs.writeFileSync(join(runDir,'proxy-first-turn-enabled'),'enabled\n',{mode:0o600,flag:'wx'});
writeSessionFile(runDir,{business:'demo',instance:'coder',run,launchedBy:'pm',harness:'pi',provider:'fake',model:'fake-model',brokerSocket,workspace,sessionDir:join(runDir,'session'),adapter,bundle:{prompt:join(bundle,'prompt.md'),policy:join(bundle,'policy.json'),tools:join(bundle,'tools.json')},toolSocket:join(runDir,'tools.sock'),turnMarker:join(runDir,'turn.done'),turnEnd:'marker',harnessEnv:{},pollInterval:50});
const loader=createLoader({log:()=>{}}),loaded=await loader.load({harness:['pi']});assert.deepEqual(loaded.refused,[]);const harnessMounts=loader.modules('harness')[0].mounts({env:{}});
child=spawnSession({runDir,env:sessionEnv({HOME:process.env.HOME,PATH:process.env.PATH},run),paths:{workspace,adapter,harnessMounts,brokerSocket},business:'demo',role:'coder'});
exited=new Promise((resolve,reject)=>{child.once('error',reject);child.once('close',(code,signal)=>resolve({code,signal}));});await runnerOf(child);
const cap=broker.bindLaunch({business:'demo',role:'coder',run,harness:'pi',pid:child.pid,startTime:startTimeOf(child.pid)}),pm=broker.bindLaunch({business:'demo',role:'pm',run:'marker-pm',harness:'pi'});broker.request(pm,{verb:'role.claim'});child.stdin.end(JSON.stringify({cap})+'\n');
async function ask(body){const sent=broker.request(pm,{verb:'message.send',args:{to:'coder',body,class:'REQUEST'}}),deadline=Date.now()+15000;while(Date.now()<deadline){const reply=broker.request(pm,{verb:'message.receive'}).find(r=>r.in_reply_to===sent.id);if(reply)return reply.body;await delay(25);}throw Error('confined marker response not observed');}
return {runDir,ask,store,exited,send:body=>broker.request(pm,{verb:'message.send',args:{to:'coder',body,class:'REQUEST'}})};
}
const skip=sandboxProblem()??false; // Any unavailable confinement is UNVERIFIED, never green evidence.
test('650 confined actual stdout writes fixed output marker in existing runDir without changing reply',{skip,timeout:60000},async t=>{
const f=await confined(t),file=join(f.runDir,'proxy-first-output');await delay(150);assert.equal(fs.existsSync(file),false,'idle confined runner has no output marker');
assert.equal(await f.ask('first'),'fx650-private-output');assert.equal(fs.readFileSync(file,'utf8'),'output\n');assert.equal(fs.statSync(file).mode&0o777,0o600);
const stat=fs.statSync(file);assert.equal(await f.ask('second'),'fx650-private-output');assert.equal(fs.statSync(file).mtimeMs,stat.mtimeMs);assert.equal(fs.readFileSync(file,'utf8').includes('fx650-private-output'),false);assert.equal(fs.existsSync(join(f.runDir,'proxy-first-turn')),false,'non-proxy actual turns never publish first-turn timestamps');
});
test('650 confined actual adapter turn publishes first timestamp once and idle stays unarmed',{skip,timeout:60000},async t=>{
const f=await confined(t,{enabled:true}),file=join(f.runDir,'proxy-first-turn');await delay(150);assert.equal(fs.existsSync(file),false,'idle confined runner has no turn marker');
const before=process.hrtime.bigint();assert.equal(await f.ask('first'),'fx650-private-output');assert.equal(fs.existsSync(file),true,'actual confined turn publishes first-turn marker');
const value=fs.readFileSync(file,'utf8');assert.match(value,/^turn [0-9]+\n$/);const stamp=BigInt(value.trim().split(' ')[1]);assert.ok(stamp>=before&&stamp<=process.hrtime.bigint(),'host and confined process share monotonic clock');assert.equal(fs.statSync(file).mode&0o777,0o600);
const stat=fs.statSync(file);assert.equal(await f.ask('second'),'fx650-private-output');assert.equal(fs.readFileSync(file,'utf8'),value);assert.equal(fs.statSync(file).mtimeMs,stat.mtimeMs);assert.equal(fs.readdirSync(f.runDir).some(n=>n.startsWith('.proxy-first-turn-')),false,'atomic publication leaves no temp marker');
});