okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a16109803
main
1/** 2* The chat Mode menu (Manual / Plan / Bypass) as real Harness behaviour. 3* 4* The Harness is real: its process, its sandbox, its approval gate, its tools, its `/permission` command. 5* Only the model is scripted (tests/helpers/scripted-worker.mjs), and it behaves like a careful model: when the 6* sandbox denies a change and offers an escalation, it retries the exact call once with `sandbox_permissions`. 7* Every test checks the file on disk, not only the frames, because the frames are what the Harness reports. 8* 9* Needs STRATA_HARNESS_DIR (a built Harness); without it these tests skip, loudly. 10*/ 11import test from 'node:test' ; 12import assert from 'node:assert/strict' ; 13import { existsSync , mkdtempSync , mkdirSync , readFileSync , rmSync , writeFileSync } from 'node:fs' ; 14import { tmpdir } from 'node:os' ; 15import { join } from 'node:path' ; 16import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 17import { createAgentBridge } from '../server/agent/agent-bridge.mjs' ; 18import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 19import { MODE_PRESETS , modeOf , buildProfile } from '../server/agent/profile.mjs' ; 20import { NOT_IN_MODE , TurnProjector } from '../server/agent/events.mjs' ; 21 22const HARNESS = process . env . STRATA_HARNESS_DIR ; 23const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 24const cleanup = dir => { try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } }; 25const sleep = ms => new Promise ( r => setTimeout ( r , ms )); 26const lines = file => readFileSync ( file , 'utf8' ). split ( / \r ? \n / ). filter ( Boolean ). length ; 27const tools = frames => frames . filter ( f => f . type === 'agent-tool' ); 28const states = frames => tools ( frames ). map ( f => f . tool . state ); 29const text = frames => frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ); 30 31async function rig ( t ) { 32const worker = await startScriptedWorker ({}); 33const dir = mkdtempSync ( join ( tmpdir (), 'strata-modes-' )); 34const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 35const local = [{ id :'inst-1' , label :'Scripted' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 }]; 36const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => local , connections :() => [], env :process . env , startTimeoutMs :90_000 }); 37t . after ( async () => { await bridge . close (); await worker . close (); cleanup ( dir ); }); 38/** One turn in `mode`; `answer` decides what the person says to an approval card (approve | deny | undefined = nobody answers). */ 39const run = async ( chatId , message , { mode, answer, onFrame} = {}) => { 40const frames = []; 41await bridge . runTurn ({ 42 chatId, message, workspacePath :ws , mode, 43onFrame :f => { 44frames . push ( f ); onFrame ?.( f ); 45if ( answer && f . type === 'agent-tool' && f . tool . state === 'proposed' ) void bridge . approve ({ chatId, callId :f . tool . id , decision :answer }). catch ( e => frames . push ({ type :'test-error' , message :e . message })); 46}, 47}); 48return frames ; 49}; 50/** The preset the Harness itself reports for the chat's session. */ 51const preset = async chatId => { 52const { rt} = bridge . _debug (); 53const r = await rt . gw . rpc ( 'session/projections' , { request :{ sessionId :bridge . sessionOf ( chatId ), keys :[ 'permissions' ] } }); 54return r . values . permissions . currentValue ; 55}; 56return { worker, bridge, dir, ws, run, preset}; 57} 58 59test ( 'mode mapping: three presets, Manual by default, unknown values fall back to Manual' , () => { 60assert . deepEqual ( Object . keys ( MODE_PRESETS ), [ 'manual' , 'plan' , 'bypass' ]); 61// Manual leaves the sandbox open and asks BEFORE a change through the Strata gate (plugins/strata-gate.mjs). 62assert . deepEqual ([ MODE_PRESETS . manual . sandbox , MODE_PRESETS . manual . approval ], [ 'danger-full-access' , 'ask' ]); 63assert . deepEqual ([ MODE_PRESETS . plan . sandbox , MODE_PRESETS . plan . approval ], [ 'read-only' , 'never' ]); 64assert . deepEqual ([ MODE_PRESETS . bypass . sandbox , MODE_PRESETS . bypass . approval ], [ 'danger-full-access' , 'never' ]); 65for ( const v of [ 'manual' , 'plan' , 'bypass' ]) assert . equal ( modeOf ( v ), v ); 66for ( const v of [ undefined , null , '' , 'auto' , 'accept-edits' , 'danger-full-access' , 'constructor' ]) assert . equal ( modeOf ( v ), 'manual' , String ( v )); 67// Only Bypass gives full access WITHOUT asking, and the profile names our three and nothing else. 68const entry = JSON . parse ( buildProfile ({ local :[] }). patch . split ( '\n' ). slice ( 1 ). join ( '\n' )). find ( e => e . id === 'permission' ); 69assert . deepEqual ( Object . keys ( entry . config . presets ), [ 'strata-manual' , 'strata-plan' , 'strata-bypass' ]); 70assert . equal ( entry . config . defaultPreset , 'strata-manual' ); 71assert . deepEqual ( Object . entries ( entry . config . presets ). filter (([, p ]) => p . sandbox === 'danger-full-access' && p . approval === 'never' ). map (([ k ]) => k ), [ 'strata-bypass' ]); 72assert . deepEqual ( Object . entries ( entry . config . presets ). filter (([, p ]) => p . sandbox !== 'danger-full-access' ). map (([ k ]) => k ), [ 'strata-plan' ]); 73}); 74 75test ( 'projection: under "never" no card ever offers Approve; "ask" marks the approved card' , () => { 76const call = { type :'event' , event :{ seq :1 , time :1 , type :'tool/call' , data :{ callId :'c1' , name :'write' , arguments :{ file_path :'x.txt' , content :'x' } } } }; 77const asked = { type :'event' , event :{ seq :2 , time :2 , type :'approval/asked' , data :{ id :'a1' , callId :'c1' , reason :'escalate sandbox to workspace-write: because' } } }; 78const rejected = { type :'event' , event :{ seq :3 , time :3 , type :'approval/decided' , data :{ id :'a1' , outcome :'rejected' } } }; 79const failed = { type :'event' , event :{ seq :4 , time :4 , type :'tool/result' , data :{ message :{ toolCallId :'c1' , isError :true , content :[{ type :'text' , text :'Error: the user rejected escalating' }] } } } }; 80const never = new TurnProjector ({ policy :'never' }); 81const frames = [ call , asked , rejected , failed ]. flatMap ( i => never . consume ( i )); 82assert . deepEqual ( frames . map ( f => f . tool . state ), [ 'running' , 'denied' , 'denied' ]); 83assert . ok ( frames . every ( f => ! f . tool . approved )); 84assert . equal ( frames . at ( - 1 ). tool . result , NOT_IN_MODE ); 85 86const ask = new TurnProjector ({ policy :'ask' }); 87const ok = { type :'event' , event :{ seq :3 , time :3 , type :'approval/decided' , data :{ id :'a1' , outcome :'allowed-once' } } }; 88const done = { type :'event' , event :{ seq :4 , time :4 , type :'tool/result' , data :{ message :{ toolCallId :'c1' , isError :false , content :[{ type :'text' , text :'Created file' }] } } } }; 89const f2 = [ call , asked , ok , done ]. flatMap ( i => ask . consume ( i )); 90assert . deepEqual ( f2 . map ( f => f . tool . state ), [ 'running' , 'proposed' , 'running' , 'done' ]); 91assert . equal ( f2 . at ( - 1 ). tool . approved , true ); 92// A call that never asked finishes without the flag. 93const plain = new TurnProjector ({ policy :'ask' }); 94const f3 = [ call , done ]. flatMap ( i => plain . consume ( i )); 95assert . equal ( f3 . at ( - 1 ). tool . state , 'done' ); assert . equal ( f3 . at ( - 1 ). tool . approved , undefined ); 96}); 97 98test ( 'MODE Manual: an in-workspace write is held for the person, and runs once after Approve' , { skip}, async t => { 99const r = await rig ( t ); 100let fileWhileAsking = null ; 101const frames = await r . run ( 'm-manual-write' , 'SCRIPT:retrywrite approved.txt hello' , { 102mode :'manual' , answer :'approve' , 103onFrame :f => { if ( f . type === 'agent-tool' && f . tool . state === 'proposed' ) fileWhileAsking = existsSync ( join ( r . ws , 'approved.txt' )); }, 104}); 105assert . equal ( fileWhileAsking , false , 'the file must not exist while the card is asking' ); 106const final = tools ( frames ). at ( - 1 ). tool ; 107assert . equal ( final . state , 'done' ); assert . equal ( final . approved , true ); assert . equal ( final . scope , 'write' ); 108assert . ok ( states ( frames ). includes ( 'proposed' )); 109assert . equal ( lines ( join ( r . ws , 'approved.txt' )), 1 ); 110assert . equal ( frames . find ( f => f . type === 'start' ). mode , 'manual' ); 111assert . equal ( await r . preset ( 'm-manual-write' ), MODE_PRESETS . manual . key ); 112assert . equal ( frames . at ( - 1 ). type , 'done' ); 113}); 114 115test ( 'MODE Manual: Deny leaves the file absent, and a shell command that writes is held too' , { skip}, async t => { 116const r = await rig ( t ); 117const denied = await r . run ( 'm-manual-deny' , 'SCRIPT:retrywrite denied.txt nope' , { mode :'manual' , answer :'deny' }); 118assert . equal ( existsSync ( join ( r . ws , 'denied.txt' )), false ); 119assert . equal ( states ( denied ). at ( - 1 ), 'denied' ); 120assert . equal ( denied . at ( - 1 ). type , 'done' ); 121 122const shell = await r . run ( 'm-manual-shell' , 'SCRIPT:retryshell shell.txt via-shell' , { mode :'manual' , answer :'approve' }); 123assert . ok ( states ( shell ). includes ( 'proposed' ), 'the shell write asked first' ); 124const card = tools ( shell ). at ( - 1 ). tool ; 125assert . equal ( card . scope , 'shell' ); assert . equal ( card . state , 'done' ); assert . equal ( card . approved , true ); 126assert . equal ( lines ( join ( r . ws , 'shell.txt' )), 1 ); 127}); 128 129test ( 'MODE Manual: reading needs no question' , { skip}, async t => { 130const r = await rig ( t ); 131writeFileSync ( join ( r . ws , 'notes.txt' ), 'plain notes\n' ); 132const frames = await r . run ( 'm-manual-read' , 'SCRIPT:read notes.txt' , { mode :'manual' }); 133assert . deepEqual ([ ...new Set ( states ( frames ))], [ 'running' , 'done' ]); 134assert . equal ( tools ( frames ). at ( - 1 ). tool . approved , undefined ); 135assert . match ( tools ( frames ). at ( - 1 ). tool . result , / plain notes / ); 136}); 137 138test ( 'MODE Plan: a write is refused with no question, the file never appears, reading still works' , { skip}, async t => { 139const r = await rig ( t ); 140const frames = await r . run ( 'm-plan' , 'SCRIPT:retrywrite plan.txt nope' , { mode :'plan' }); 141assert . equal ( existsSync ( join ( r . ws , 'plan.txt' )), false ); 142assert . ok ( ! states ( frames ). includes ( 'proposed' ), 'Plan never shows an Approve card' ); 143assert . equal ( states ( frames ). at ( - 1 ), 'denied' ); 144assert . equal ( tools ( frames ). at ( - 1 ). tool . result , NOT_IN_MODE ); 145assert . equal ( frames . at ( - 1 ). type , 'done' , 'the turn still settles; the agent answers' ); 146assert . equal ( await r . preset ( 'm-plan' ), MODE_PRESETS . plan . key ); 147assert . equal ( r . bridge . status (). pendingApprovals , 0 ); 148 149const shell = await r . run ( 'm-plan-shell' , 'SCRIPT:retryshell plan-shell.txt nope' , { mode :'plan' }); 150assert . equal ( existsSync ( join ( r . ws , 'plan-shell.txt' )), false ); 151assert . ok ( ! states ( shell ). includes ( 'proposed' )); 152 153writeFileSync ( join ( r . ws , 'readme.txt' ), 'readable in plan mode\n' ); 154const read = await r . run ( 'm-plan-read' , 'SCRIPT:read readme.txt' , { mode :'plan' }); 155assert . equal ( tools ( read ). at ( - 1 ). tool . state , 'done' ); 156assert . match ( tools ( read ). at ( - 1 ). tool . result , / readable in plan mode / ); 157}); 158 159test ( 'MODE Bypass is full access: in-workspace and outside writes run without asking' , { skip}, async t => { 160const r = await rig ( t ); 161const frames = await r . run ( 'm-bypass' , 'SCRIPT:retrywrite free.txt hello' , { mode :'bypass' }); 162assert . ok ( ! states ( frames ). includes ( 'proposed' ), 'Bypass asks nothing' ); 163assert . equal ( lines ( join ( r . ws , 'free.txt' )), 1 ); 164const card = tools ( frames ). at ( - 1 ). tool ; 165assert . equal ( card . state , 'done' ); assert . equal ( card . approved , undefined , 'it ran; nobody approved it' ); 166assert . equal ( await r . preset ( 'm-bypass' ), MODE_PRESETS . bypass . key ); 167 168const shell = await r . run ( 'm-bypass-shell' , 'SCRIPT:retryshell free-shell.txt hello' , { mode :'bypass' }); 169assert . ok ( ! states ( shell ). includes ( 'proposed' )); 170assert . equal ( lines ( join ( r . ws , 'free-shell.txt' )), 1 ); 171 172// Bypass is the Harness's full access with no prompts: a call that asks for danger-full-access runs, in the workspace or outside it. 173const wide = await r . run ( 'm-bypass-wide' , 'SCRIPT:tool wide.txt x' , { mode :'bypass' }); 174assert . ok ( ! states ( wide ). includes ( 'proposed' ), 'full access asks nothing' ); 175assert . equal ( lines ( join ( r . ws , 'wide.txt' )), 1 ); 176assert . equal ( states ( wide ). at ( - 1 ), 'done' ); 177const outside = join ( r . dir , 'outside-workspace.txt' ); 178const out = await r . run ( 'm-bypass-outside' , `SCRIPT:tool ${ outside } y` , { mode :'bypass' }); 179assert . ok ( ! states ( out ). includes ( 'proposed' )); 180assert . equal ( lines ( outside ), 1 , 'a path outside the workspace was written' ); 181assert . equal ( states ( out ). at ( - 1 ), 'done' ); 182}); 183 184test ( 'MODE the choice follows the chat: it changes on the next turn, keeps the session, and an unknown value is Manual' , { skip}, async t => { 185const r = await rig ( t ); 186await r . run ( 'm-switch' , 'SCRIPT:echo one' , { mode :'manual' }); 187const session = r . bridge . sessionOf ( 'm-switch' ); 188assert . equal ( await r . preset ( 'm-switch' ), MODE_PRESETS . manual . key ); 189await r . run ( 'm-switch' , 'SCRIPT:echo two' , { mode :'plan' }); 190assert . equal ( await r . preset ( 'm-switch' ), MODE_PRESETS . plan . key ); 191const bypass = await r . run ( 'm-switch' , 'SCRIPT:retrywrite switched.txt hi' , { mode :'bypass' }); 192assert . equal ( lines ( join ( r . ws , 'switched.txt' )), 1 ); 193assert . ok ( ! states ( bypass ). includes ( 'proposed' )); 194// Back to Manual: asks again, on the same session, and the earlier turns are still its history. 195const manual = await r . run ( 'm-switch' , 'SCRIPT:retrywrite switched-again.txt hi' , { mode :'manual' , answer :'approve' }); 196assert . ok ( states ( manual ). includes ( 'proposed' )); 197assert . equal ( r . bridge . sessionOf ( 'm-switch' ), session ); 198// A mode the app does not offer (older stored value) or none at all is Manual, never something looser. 199for ( const [ chat , mode ] of [[ 'm-odd-1' , 'auto' ], [ 'm-odd-2' , undefined ], [ 'm-odd-3' , 'danger-full-access' ]]) { 200const f = await r . run ( chat , 'SCRIPT:retrywrite odd.txt x' , { mode, answer :'deny' }); 201assert . ok ( states ( f ). includes ( 'proposed' ), ` ${ mode } asks like Manual` ); 202} 203assert . equal ( existsSync ( join ( r . ws , 'odd.txt' )), false ); 204}); 205 206test ( 'MODE changing the mode while a turn runs does not touch that turn' , { skip}, async t => { 207const r = await rig ( t ); 208const frames = []; 209const slow = r . bridge . runTurn ({ chatId :'m-mid' , message :'SCRIPT:slow 120' , workspacePath :r . ws , mode :'manual' , onFrame :f => frames . push ( f ) }); 210for ( let i = 0 ; i < 200 && frames . filter ( f => f . type === 'delta' ). length < 3 ; i ++ ) await sleep ( 50 ); 211assert . ok ( frames . filter ( f => f . type === 'delta' ). length >= 3 , 'the turn must be live first' ); 212// The person flips the menu to Bypass and sends again. The second send is refused (a chat runs one turn at a time) and, 213// because it is refused before anything is applied, the running turn's permissions do not move. 214await assert . rejects ( r . bridge . runTurn ({ chatId :'m-mid' , message :'SCRIPT:echo x' , workspacePath :r . ws , mode :'bypass' , onFrame :() => {} }), / still working / ); 215assert . equal ( await r . preset ( 'm-mid' ), MODE_PRESETS . manual . key ); 216// Another chat in another mode is its own session and does not move this one either. 217await r . run ( 'm-mid-other' , 'SCRIPT:echo y' , { mode :'bypass' }); 218assert . equal ( await r . preset ( 'm-mid' ), MODE_PRESETS . manual . key ); 219await slow ; 220assert . equal ( frames . filter ( f => f . type === 'delta' ). length , 120 , 'the running turn completed untouched' ); 221assert . equal ( frames . at ( - 1 ). finishReason , 'stop' ); 222// And the new choice is what the next turn uses. 223await r . run ( 'm-mid' , 'SCRIPT:echo z' , { mode :'bypass' }); 224assert . equal ( await r . preset ( 'm-mid' ), MODE_PRESETS . bypass . key ); 225}); 226 227test ( 'MODE the mode survives a restart of the agent process: the chat resumes in the mode it is asked for' , { skip}, async t => { 228const r = await rig ( t ); 229await r . run ( 'm-restart' , 'SCRIPT:echo one' , { mode :'plan' }); 230const session = r . bridge . sessionOf ( 'm-restart' ); 231await r . bridge . close (); 232// A new bridge over the same data directory: the persisted session is resumed, then put in the requested mode. 233const worker2 = r . worker ; 234const bridge2 = createAgentBridge ({ dataDir :r . dir , localInstances :() => [{ id :'inst-1' , label :'Scripted' , baseUrl :worker2 . url , modelId :'scripted-model' , context :32768 }], connections :() => [], env :process . env , startTimeoutMs :90_000 }); 235t . after (() => bridge2 . close ()); 236const frames = []; 237await bridge2 . runTurn ({ chatId :'m-restart' , message :'SCRIPT:retrywrite resumed.txt hi' , workspacePath :r . ws , mode :'bypass' , onFrame :f => frames . push ( f ) }); 238assert . equal ( bridge2 . sessionOf ( 'm-restart' ), session , 'the same session' ); 239assert . equal ( lines ( join ( r . ws , 'resumed.txt' )), 1 ); 240const { rt} = bridge2 . _debug (); 241const now = await rt . gw . rpc ( 'session/projections' , { request :{ sessionId :session , keys :[ 'permissions' ] } }); 242assert . equal ( now . values . permissions . currentValue , MODE_PRESETS . bypass . key ); 243});