okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3d9c21509
main
1/** 2* Helper agents (the Harness's subagents) in the chat: rows, concurrency, one approval card, Stop, and /goal. 3* 4* Pure tests always run; the rest need a built Harness (STRATA_HARNESS_DIR) and skip loudly without it. 5* The model is scripted; the Harness, its subagent runtime, its approval service, the gate and the bridge are real. 6*/ 7import test from 'node:test' ; 8import assert from 'node:assert/strict' ; 9import { existsSync , mkdtempSync , mkdirSync , readFileSync , rmSync } from 'node:fs' ; 10import { tmpdir } from 'node:os' ; 11import { join } from 'node:path' ; 12import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 13import { createAgentBridge , plainBlocker , goalEnding , plainGoalError } from '../server/agent/agent-bridge.mjs' ; 14import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 15import { ChildProjector , activityOf } from '../server/agent/children.mjs' ; 16 17const HARNESS = process . env . STRATA_HARNESS_DIR ; 18const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 19const cleanup = dir => { try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }; 20const fwd = p => p . replaceAll ( '\\' , '/' ); 21 22// ---------------------------------------------------------------------------------------------------------- pure 23 24const ev = ( type , data , extra = {}) => ({ type :'event' , event :{ seq :1 , time :extra . time ?? 1000 , type, data} }); 25 26test ( 'a helper row follows its helper: queued, working, completed with its closing words, tokens counted' , () => { 27let t = 0 ; 28const cp = new ChildProjector ({ id :'c1' , name :'Check the tests' , task :'Run the unit tests and report' , now :() => ( t += 100 ) }); 29assert . equal ( cp . agent (). status , 'queued' ); 30assert . equal ( cp . agent (). description , 'Waiting for its turn. Run the unit tests and report' ); 31cp . consume ( ev ( 'step/start' , { turn :1 , step :1 })); 32assert . equal ( cp . agent (). status , 'queued' , 'a request that was sent is still waiting until the engine says its first word' ); 33cp . consume ({ type :'assistant-stream' , frame :{ type :'chunk' , chunk :{ type :'text-delta' , text :'Running' } } }); 34assert . equal ( cp . agent (). status , 'working' ); 35assert . equal ( cp . agent (). description , 'Run the unit tests and report' ); 36cp . consume ({ type :'assistant-stream' , frame :{ type :'chunk' , chunk :{ type :'usage' , usage :{ inputTokens :100 , outputTokens :20 } } } }); 37assert . equal ( cp . agent (). tokens , 120 ); 38cp . consume ( ev ( 'assistant/message' , { message :{ content :[{ type :'text' , text :'All 12 tests pass.' }] } })); 39cp . consume ( ev ( 'turn/end' , { turn :1 , reason :{ kind :'completed' } })); 40const row = cp . agent (); 41assert . equal ( row . status , 'completed' ); assert . equal ( row . description , 'All 12 tests pass.' ); 42assert . ok ( row . durationMs > 0 ); 43assert . ok ([ 'id' , 'name' , 'description' , 'status' , 'durationMs' , 'tokens' , 'updatedAt' ]. every ( k => k in row ), 'exactly the fields the existing rows read' ); 44}); 45 46test ( 'a helper that failed or was stopped says so in plain words' , () => { 47const failed = new ChildProjector ({ id :'f' , name :'A' }); 48failed . consume ( ev ( 'step/start' , {})); 49failed . consume ( ev ( 'turn/end' , { reason :{ kind :'error' , error :{ message :'fetch failed: ECONNREFUSED' } } })); 50assert . equal ( failed . agent (). status , 'failed' ); assert . match ( failed . agent (). description , / not reachable / ); 51const stopped = new ChildProjector ({ id :'s' , name :'B' }); 52stopped . consume ( ev ( 'turn/end' , { reason :{ kind :'aborted' } })); 53assert . deepEqual ([ stopped . agent (). status , stopped . agent (). description ], [ 'cancelled' , 'Stopped.' ]); 54}); 55 56test ( 'only a helper request that needs the person becomes a card, and its id names the helper' , () => { 57const cp = new ChildProjector ({ id :'child-1' , name :'Writer' }); 58assert . deepEqual ( cp . consume ( ev ( 'tool/call' , { callId :'k1' , name :'read' , arguments :'{"file_path":"a"}' })). frames , [], 'a read is not a card' ); 59cp . consume ( ev ( 'tool/result' , { message :{ toolCallId :'k1' , content :[{ type :'text' , text :'x' }] } })); 60cp . consume ( ev ( 'tool/call' , { callId :'k2' , name :'write' , arguments :'{"file_path":"C:/a.txt","content":"x"}' })); 61const asked = cp . consume ( ev ( 'approval/asked' , { id :'a1' , callId :'k2' , reason :'Create or replace the file C:/a.txt' })). frames [ 0 ]. tool ; 62assert . equal ( asked . id , 'child-1:k2' ); assert . equal ( asked . state , 'proposed' ); assert . match ( asked . effect , / ^Writer asks: Create or replace the file / ); 63assert . equal ( cp . consume ( ev ( 'approval/decided' , { id :'a1' , outcome :'rejected' })). frames [ 0 ]. tool . result , 'Denied. Nothing ran.' ); 64const done = cp . consume ( ev ( 'tool/result' , { message :{ toolCallId :'k2' , isError :true , content :[{ type :'text' , text :'Error: the user rejected tool "write"' } ] } })). frames [ 0 ]. tool ; 65assert . equal ( done . state , 'denied' ); assert . equal ( done . result , 'Denied. Nothing ran.' ); 66assert . equal ( activityOf ( 'pwsh' ), 'Running a command' ); 67}); 68 69test ( 'goal wording: plain, never a code' , () => { 70assert . match ( plainBlocker ({ code :'round-limit' }), / most steps / ); 71assert . match ( goalEnding ({ phase :'complete' }), / complete / ); 72assert . match ( plainGoalError ( new Error ( 'goal "x" is not finished; an unfinished goal must be edited' )), / already has a goal / ); 73assert . doesNotMatch ( plainGoalError ( new Error ( 'boom' )), / boom / ); 74}); 75 76// ------------------------------------------------------------------------------------------------- real Harness 77 78async function rig ( t , { slots= 4 , serial= false , onGoal} = {}) { 79const worker = await startScriptedWorker ({ serial}); 80const dir = mkdtempSync ( join ( tmpdir (), 'strata-kids-' )); 81const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 82const local = [{ id :'inst-1' , label :'Scripted' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 , slots}]; 83const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => local , connections :() => [], env :process . env , startTimeoutMs :90_000 , ...( onGoal ?{ onGoal} :{}) }); 84t . after ( async () => { await bridge . close (); await worker . close (); cleanup ( dir ); }); 85const run = async ( chatId , message , { mode= 'bypass' , answer, onFrame, goal} = {}) => { 86const frames = []; 87const on = f => { 88frames . push ({ ...f , at :Date . now () }); onFrame ?.( f ); 89if ( 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 })); 90}; 91const result = goal ?await bridge . runTurn ({ chatId, workspacePath :ws , mode, goal, onFrame :on }) :await bridge . runTurn ({ chatId, message, workspacePath :ws , mode, onFrame :on }); 92return { frames, result}; 93}; 94return { worker, bridge, dir, ws, run}; 95} 96const rows = frames => { const m = new Map (); for ( const f of frames . filter ( x => x . type === 'agent' )) m . set ( f . agent . id , [ ...( m . get ( f . agent . id ) ?? []), f . agent ]); return m ; }; 97const text = frames => frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ); 98 99test ( 'two helpers run at the same time as two rows, the run ends when both have reported, and the delegation tool shows no raw card' , { skip}, async ( t ) => { 100const r = await rig ( t ); 101const { frames} = await r . run ( 'kids' , 'SCRIPT:spawn 2 slow 40' ); 102const byId = rows ( frames ); 103assert . equal ( byId . size , 2 ); 104const names = [ ...byId . values ()]. map ( history => history . at ( - 1 ). name ). sort (); 105assert . deepEqual ( names , [ 'Helper 1' , 'Helper 2' ]); 106for ( const history of byId . values ()) { 107assert . ok ( history . some ( a => a . status === 'working' ), 'it worked' ); 108assert . equal ( history . at ( - 1 ). status , 'completed' ); 109assert . ok ( history . at ( - 1 ). tokens > 0 && history . at ( - 1 ). durationMs > 0 ); 110assert . match ( history [ 1 ]?. description ?? history [ 0 ]. description , / SCRIPT:slow 40 / , 'the row names its task' ); 111} 112// concurrent: both were working before either finished (by the order the frames arrived in, not by the clock: a loaded computer delays a frame, it does not reorder it) 113const agentFrames = frames . filter ( f => f . type === 'agent' ); 114const firstDone = agentFrames . findIndex ( f => f . agent . status === 'completed' ); 115for ( const id of byId . keys ()) { 116const working = agentFrames . findIndex ( f => f . agent . id === id && f . agent . status === 'working' ); 117assert . ok ( working >= 0 && working < firstDone , `helper ${ id } was working before the first helper finished` ); 118} 119assert . equal ( frames . filter ( f => f . type === 'agent-tool' ). length , 0 , 'no card for the delegation tool itself' ); 120assert . match ( text ( frames ), / Noted / , 'the parent answered after the helpers reported back' ); 121assert . equal ( frames . at ( - 1 ). type , 'done' ); 122assert . ok ( frames . at ( - 1 ). at >= Math . max ( ...frames . filter ( f => f . type === 'agent' && f . agent . status === 'completed' ). map ( f => f . at )), 'done comes after the last helper' ); 123assert . equal ( r . bridge . isRunning ( 'kids' ), false ); 124assert . equal ( r . worker . requests . filter ( q => q . directive === 'slow' ). length , 2 ); 125}); 126 127test ( 'helpers are limited to the Harness cap (4, or the slot count if larger); the fifth is refused with a message the model reads' , { skip}, async ( t ) => { 128const r = await rig ( t , { slots :2 }); 129const { frames} = await r . run ( 'few' , 'SCRIPT:spawn 5 slow 30' ); 130assert . equal ( rows ( frames ). size , 4 ); 131}); 132 133test ( 'Manual: a helper that wants to change a file reaches the person as the same single Approve card, and the answer is honoured' , { skip}, async ( t ) => { 134const r = await rig ( t ); 135const approved = join ( r . ws , 'from-helper.txt' ), denied = join ( r . ws , 'denied.txt' ); 136const ok = await r . run ( 'kid-ok' , `SCRIPT:spawn 1 call write ${ JSON . stringify ({ file_path : fwd ( approved ), content : 'by helper' })} ` , { mode :'manual' , answer :'approve' }); 137const okCards = ok . frames . filter ( f => f . type === 'agent-tool' ). map ( f => f . tool ); 138assert . deepEqual ([ ...new Set ( okCards . map ( c => c . state ))], [ 'proposed' , 'running' , 'done' ]); 139assert . equal ( new Set ( okCards . map ( c => c . id )). size , 1 ); assert . match ( okCards [ 0 ]. id , / ^ [ 0 - 9a - f- ]{ 36 } : / ); 140assert . match ( okCards [ 0 ]. effect , / ^Helper 1 asks: Create or replace the file / ); 141assert . equal ( readFileSync ( approved , 'utf8' ). trim (), 'by helper' ); 142const no = await r . run ( 'kid-no' , `SCRIPT:spawn 1 call write ${ JSON . stringify ({ file_path : fwd ( denied ), content : 'x' })} ` , { mode :'manual' , answer :'deny' }); 143assert . equal ( existsSync ( denied ), false ); 144assert . equal ( no . frames . filter ( f => f . type === 'agent-tool' ). at ( - 1 ). tool . state , 'denied' ); 145assert . equal ( no . frames . filter ( f => f . type === 'agent-tool' ). at ( - 1 ). tool . result , 'Denied. Nothing ran.' ); 146assert . equal ( rows ( no . frames ). size , 1 ); 147}); 148 149test ( "a chat cannot answer another chat's helper question" , { skip}, async ( t ) => { 150const r = await rig ( t ); 151let asked = null ; 152const file = join ( r . ws , 'x.txt' ); 153const run = r . run ( 'owner' , `SCRIPT:spawn 1 call write ${ JSON . stringify ({ file_path : fwd ( file ), content : 'x' })} ` , { mode :'manual' , onFrame :f => { if ( f . type === 'agent-tool' && f . tool . state === 'proposed' ) asked = f . tool ; } }); 154for ( let i = 0 ; i < 200 && ! asked ; i ++ ) await new Promise ( res => setTimeout ( res , 50 )); 155assert . ok ( asked , 'the question reached the person' ); 156await assert . rejects ( r . bridge . approve ({ chatId :'someone-else' , callId :asked . id , decision :'approve' }), / no longer waiting / ); 157assert . equal ( r . bridge . pendingFor ( 'owner' ). length , 1 ); 158await r . bridge . approve ({ chatId :'owner' , callId :asked . id , decision :'deny' }); 159await run ; 160assert . equal ( existsSync ( file ), false ); 161}); 162 163test ( 'Stop on the chat stops its helpers, ends the run quickly and starts no further turn' , { skip}, async ( t ) => { 164const r = await rig ( t ); 165const started = Date . now (); 166let stopped = null ; 167const { frames} = await r . run ( 'stopper' , 'SCRIPT:spawn 2 slow 2000' , { onFrame :f => { 168if ( f . type === 'agent' && f . agent . status === 'working' && ! stopped ) stopped = new Promise ( res => setTimeout ( res , 300 )). then (() => r . bridge . stop ( 'stopper' )); 169} }); 170const result = await stopped ; 171assert . equal ( result . stopped , true ); 172const final = [ ...rows ( frames ). values ()]. map ( h => h . at ( - 1 ). status ); 173assert . deepEqual ( final , [ 'cancelled' , 'cancelled' ]); 174assert . ok ( Date . now () - started < 40_000 , 'seconds, not the 80 s the helpers would have taken (a generous bound: a loaded computer is slow, never that slow)' ); 175const done = frames . at ( - 1 ); 176assert . equal ( done . type , 'done' ); assert . equal ( done . cancelled , true ); 177assert . equal ( r . bridge . isRunning ( 'stopper' ), false ); 178assert . ok ( ! /Noted / . test ( text ( frames )), 'the parent was not woken to comment on stopped helpers' ); 179}); 180 181test ( '/goal: sets a goal, runs its rounds in the chat, says how it ended, refuses a second unfinished goal, and Stop pauses it' , { skip}, async ( t ) => { 182const r = await rig ( t ); 183const frames = []; 184const say = line => { const out = []; return r . bridge . goalCommand ({ chatId :'g' , line, workspacePath :r . ws , mode :'bypass' , onFrame :f => { out . push ( f ); frames . push ( f ); } }). then (() => out ); }; 185assert . match ( text ( await say ( '' )), / No goal is set / ); 186const ran = await r . run ( 'g' , null , { goal :{ action :'create' , objective :'say hello a few times' , maxRounds :3 } }); 187// The round is a live status now (it used to be an italic line of text that stayed on screen after the model moved on). 188assert . ok ( ! /Working on the goal / . test ( text ( ran . frames )), 'no goal-step text in the message' ); 189assert . ok ( ran . frames . some ( f => f . type === 'status' && f . phase === 'goal' && f . code === 'goal-step' && / ^Working on the goal…$ / . test ( f . text ) && f . args . round >= 1 ), 'a goal-step status was sent' ); 190const goalFrames = ran . frames . filter ( f => f . type === 'goal' ); 191assert . ok ( goalFrames . length >= 2 && goalFrames [ 0 ]. goal . objective === 'say hello a few times' && goalFrames [ 0 ]. goal . maxRounds === 3 , 'the goal frame carries the objective and the round limit' ); 192assert . equal ( goalFrames . at ( - 1 ). goal . phase , 'blocked' ); assert . match ( goalFrames . at ( - 1 ). goal . blocked , / most steps / ); 193assert . equal ( ran . frames . filter ( f => f . type === 'status' ). at ( - 1 ). phase , 'idle' , 'the status line is cleared before the end' ); 194assert . ok ( ran . frames . findIndex ( f => f . type === 'status' && f . phase === 'idle' ) < ran . frames . findIndex ( f => f . type === 'done' )); 195assert . match ( text ( ran . frames ), / The goal stopped: it worked for the most steps / ); 196assert . equal ( ran . frames . at ( - 1 ). type , 'done' ); 197assert . match ( text ( await say ( '' )), / stopped / ); 198assert . match (( await say ( 'a different goal' )). find ( f => f . type === 'error' ). message , / already has a goal / ); 199assert . match ( text ( await say ( 'clear' )), / cleared / ); 200// a long goal is paused by Stop, and can be resumed 201const slowGoal = r . run ( 'g2' , null , { goal :{ action :'create' , objective :'keep going' , maxRounds :50 } }); 202r . worker . requests . length = 0 ; 203await new Promise ( res => setTimeout ( res , 3500 )); 204const stop = await r . bridge . stop ( 'g2' ); 205assert . equal ( stop . stopped , true ); 206await slowGoal ; 207const before = r . worker . requests . length ; 208await new Promise ( res => setTimeout ( res , 1500 )); 209assert . equal ( r . worker . requests . length , before , 'no further round starts after Stop' ); 210assert . match ( text ( await r . bridge . goalCommand ({ chatId :'g2' , line :'' , workspacePath :r . ws , mode :'bypass' , onFrame :f => frames . push ( f ) }). then (() => frames . filter ( f => f . type === 'delta' ). slice ( - 1 ))), / paused / ); 211}); 212 213test ( 'one request slot: the second helper shows as waiting for its turn, then works, and the run still ends cleanly' , { skip}, async ( t ) => { 214const r = await rig ( t , { slots :1 , serial :true }); 215const { frames} = await r . run ( 'queue' , 'SCRIPT:spawn 2 slow 25' ); 216const byId = rows ( frames ); 217assert . equal ( byId . size , 2 , 'both helpers exist (they are not refused)' ); 218const histories = [ ...byId . values ()]; 219// walk the frames in order: at some moment one helper was working while the other was waiting for its turn 220const now = new Map (); let overlap = null ; 221for ( const f of frames . filter ( x => x . type === 'agent' )) { 222now . set ( f . agent . id , f . agent ); 223const all = [ ...now . values ()]; 224const waiting = all . find ( a => a . status === 'queued' && a . description . startsWith ( 'Waiting for its turn.' )); 225if ( waiting && all . some ( a => a . status === 'working' )) overlap ??= waiting ; 226} 227assert . ok ( overlap , 'one helper visibly waited for its turn while the other worked' ); 228for ( const h of histories ) assert . equal ( h . at ( - 1 ). status , 'completed' ); 229assert . equal ( frames . at ( - 1 ). type , 'done' ); 230}); 231 232test ( 'goal bar: the state, pause, edit and remove work from outside a turn, and every change is announced' , { skip}, async ( t ) => { 233const announced = []; 234const r = await rig ( t , { onGoal :( chatId , goal ) => announced . push ({ chatId, goal}) }); 235assert . equal ( await r . bridge . goalState ( 'bar' ), null , 'no goal in a chat that never had one' ); 236await assert . rejects ( r . bridge . goalControl ({ chatId :'bar' , action :'pause' }), / no goal / i ); 237await r . run ( 'bar' , null , { goal :{ action :'create' , objective :'say hello a few times' , maxRounds :1 } }); 238const shown = await r . bridge . goalState ( 'bar' ); 239assert . equal ( shown . objective , 'say hello a few times' ); assert . equal ( shown . maxRounds , 1 ); assert . ok ([ 'blocked' , 'complete' , 'paused' , 'active' ]. includes ( shown . phase )); 240await assert . rejects ( r . bridge . goalControl ({ chatId :'bar' , action :'edit' , text :' ' }), / few words / ); 241const edited = await r . bridge . goalControl ({ chatId :'bar' , action :'edit' , text :'say goodbye instead' }); 242assert . equal ( edited . goal . objective , 'say goodbye instead' ); 243assert . equal ( announced . at ( - 1 ). goal . objective , 'say goodbye instead' , 'the edit was announced for the bar' ); 244const cleared = await r . bridge . goalControl ({ chatId :'bar' , action :'clear' }); 245assert . deepEqual ( cleared , { goal :null }); assert . equal ( announced . at ( - 1 ). goal , null ); 246assert . equal ( await r . bridge . goalState ( 'bar' ), null ); 247await assert . rejects ( r . bridge . goalControl ({ chatId :'bar' , action :'explode' }), / no goal | not known / i ); 248}); 249 250test ( 'mode change mid-run: Manual to Bypass settles the question already waiting and the very next tool call does not ask again' , { skip}, async ( t ) => { 251const r = await rig ( t ); 252const first = join ( r . ws , 'before.txt' ); 253let asked = null ; const cards = []; 254const run = r . run ( 'mid' , `SCRIPT:spawn 1 call write ${ JSON . stringify ({ file_path : fwd ( first ), content : 'one' })} ` , { mode :'manual' , onFrame :f => { if ( f . type === 'agent-tool' ) { cards . push ( f . tool ); if ( f . tool . state === 'proposed' ) asked = f . tool ; } } }); 255for ( let i = 0 ; i < 200 && ! asked ; i ++ ) await new Promise ( res => setTimeout ( res , 50 )); 256assert . ok ( asked , 'Manual asked first' ); 257const switched = await r . bridge . setMode ( 'mid' , 'bypass' ); 258assert . deepEqual ({ applied :switched . applied , mode :switched . mode }, { applied :true , mode :'bypass' }); 259assert . equal ( switched . settled , 1 , 'the waiting question was settled by the new mode' ); 260await run ; 261assert . equal ( readFileSync ( first , 'utf8' ). trim (), 'one' ); 262assert . equal ( r . bridge . pendingFor ( 'mid' ). length , 0 ); 263// Bypass then Plan: nothing waiting, and the chat now reports Plan to the next call. 264assert . equal (( await r . bridge . setMode ( 'mid' , 'plan' )). mode , 'plan' ); 265assert . deepEqual ( await r . bridge . setMode ( 'nobody-yet' , 'manual' ), { applied :false , mode :'manual' , reason :'no session yet' }); 266}); 267 268test ( 'the gate stops a helper asking once the chat has left Manual' , async () => { 269const { apply, MANUAL_PRESET } = await import ( '../server/agent/plugins/strata-gate.mjs' ); 270let handler ; const appended = []; 271const parent = { header :{ origin :'user' } }; 272const child = { header :{ origin :'subagent' , parentSession :'p' }, append :( type , data ) => appended . push ([ type , data . policy ]) }; 273let preset = MANUAL_PRESET ; let override = 'ask' ; 274apply ({ on :( _e , h ) => { handler = h ; }, inject :() => {}, sessions :new Map ([[ 'p' , parent ]]), permissionPresets :{ current :() => preset }, approval :{ overrideOf :() => override } }); 275const exec = { name :'write' , agent :{ session :child }, input :{ file_path :'x' } }; 276await handler ( exec , async () => ({ kind :'allow' })); 277assert . deepEqual ( appended , [], 'in Manual the helper keeps asking' ); 278preset = 'strata-bypass-ish' ; 279await handler ( exec , async () => ({ kind :'allow' })); 280assert . deepEqual ( appended , [[ 'approval/policy' , 'never' ]], 'the first call after the switch un-pins the helper' ); 281override = 'never' ; 282await handler ( exec , async () => ({ kind :'allow' })); 283assert . equal ( appended . length , 1 , 'and does it once' ); 284});