okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
52ba0b781
main
1// The turn guard: a search-heavy /plan that keeps failing searches and rewriting its plan is stopped by the app and ends with a plain message; 2// a context at 100% never ends silently. The pure counting always runs; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and 3// run the real search code on a pretend web that refuses (no network). 4import test from 'node:test' ; 5import assert from 'node:assert/strict' ; 6import { mkdtempSync , mkdirSync , rmSync , readFileSync } from 'node:fs' ; 7import { tmpdir } from 'node:os' ; 8import { join } from 'node:path' ; 9import { TurnGuard , GUARD_LIMITS , GUARD_NOTES , guardNote } from '../server/agent/turn-guard.mjs' ; 10import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 11import { createAgentBridge } from '../server/agent/agent-bridge.mjs' ; 12import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 13 14const HARNESS = process . env . STRATA_HARNESS_DIR ; 15const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 16 17const search = ( id , state , result = '' ) => ({ id, name :'web_search' , state, result}); 18const LIMITED = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search. Do not retry this search' ; 19 20test ( 'three failed searches in a row stop the turn; a search that worked starts the count again' , () => { 21const g = new TurnGuard ({ plan :true , contextMax :32768 }); 22assert . equal ( g . card ( search ( 'a' , 'running' )), null , 'a running search is not counted yet' ); 23assert . equal ( g . card ( search ( 'a' , 'error' , LIMITED )), null ); 24assert . equal ( g . card ( search ( 'a' , 'error' , LIMITED )), null , 'the same card twice is one search' ); 25assert . equal ( g . card ( search ( 'b' , 'done' , 'three results' )), null ); 26assert . equal ( g . card ( search ( 'c' , 'error' , LIMITED )), null ); 27assert . equal ( g . card ( search ( 'd' , 'done' , LIMITED )), null , 'a refusal that arrives as a normal result still counts' ); 28assert . equal ( g . card ( search ( 'e' , 'error' , LIMITED )), 'searches-failed' ); 29assert . equal ( g . card ( search ( 'f' , 'error' , LIMITED )), 'searches-failed' , 'once stopped it stays stopped' ); 30assert . equal ( g . searches , 5 ); 31}); 32 33test ( 'other tools are not searches; too many searches in one turn stop it even when they work' , () => { 34const g = new TurnGuard ({ plan :true }); 35for ( let i = 0 ; i < 50 ; i ++ ) assert . equal ( g . card ({ id :`r ${ i } ` , name :'read' , state :'done' }), null ); 36for ( let i = 0 ; i < GUARD_LIMITS . searchesPlan - 1 ; i ++ ) assert . equal ( g . card ( search ( `s ${ i } ` , 'done' , 'ok' )), null ); 37assert . equal ( g . card ( search ( 'last' , 'done' , 'ok' )), 'searches' ); 38const t = new TurnGuard ({ plan :false }); 39for ( let i = 0 ; i < GUARD_LIMITS . searchesTurn - 1 ; i ++ ) assert . equal ( t . card ( search ( `s ${ i } ` , 'done' , 'ok' )), null ); 40assert . equal ( t . card ( search ( 'last' , 'done' , 'ok' )), 'searches' ); 41}); 42 43test ( 'a plan turn that writes its numbered plan from 1. again and again is stopped; a single plan is not' , () => { 44const g = new TurnGuard ({ plan :true }); 45const plan = '## Plan\n\n1. First\n2. Second\n3. Third\n\n' ; 46let reason = null ; 47for ( let i = 0 ; i < GUARD_LIMITS . planRewrites - 1 ; i ++ ) reason ??= g . text ( plan ); 48assert . equal ( reason , null , ` ${ GUARD_LIMITS . planRewrites - 1 } versions are fine` ); 49assert . equal ( g . text ( plan ), 'rewrites' ); 50const one = new TurnGuard ({ plan :true }); 51for ( const piece of [ 'Some looking around.\n\n## Plan\n\n' , '1. First\n' , '2. Second\n' , ' 1. a sub point\n' , '3. Third\n' ]) assert . equal ( one . text ( piece ), null , piece ); 52const ordinary = new TurnGuard ({ plan :false }); 53for ( let i = 0 ; i < 10 ; i ++ ) assert . equal ( ordinary . text ( plan ), null , 'only a plan turn counts rewrites' ); 54}); 55 56test ( 'a nearly full context stops the turn; a normal one does not' , () => { 57const g = new TurnGuard ({ contextMax :10000 }); 58assert . equal ( g . context ( 5000 ), null ); 59assert . equal ( g . context ( 9200 ), null ); 60assert . equal ( g . context ( 9300 ), 'context' ); 61assert . equal ( new TurnGuard ({ contextMax :0 }). context ( 1e9 ), null , 'an unknown window is never guessed' ); 62}); 63 64test ( 'a turn that ends with no words always gets a plain message: out of room, or nothing written' , () => { 65const g = new TurnGuard ({ contextMax :10000 }); 66const done = { kind :'completed' }; 67assert . equal ( g . silent ({ ended :done , wrote :false , contextTokens :9700 }), 'context' ); 68assert . equal ( g . silent ({ ended :{ kind :'max-tokens' }, wrote :false , contextTokens :9000 }), 'context' ); 69assert . equal ( g . silent ({ ended :done , wrote :false , contextTokens :3000 }), 'empty' ); 70assert . equal ( g . silent ({ ended :done , wrote :false , acted :true , contextTokens :3000 }), null , 'cards of finished work are an answer of a kind' ); 71assert . equal ( g . silent ({ ended :done , wrote :false , acted :true , contextTokens :9700 }), 'context' , 'but a full context is never silent' ); 72assert . equal ( g . silent ({ ended :done , wrote :true , contextTokens :9700 }), null , 'there are words: nothing to add' ); 73assert . equal ( g . silent ({ ended :{ kind :'error' , error :{ message :'x' } }, wrote :false , contextTokens :9700 }), null , 'an error says why by itself' ); 74assert . equal ( g . silent ({ ended :done , wrote :false , contextTokens :9700 , stoppedByPerson :true }), null , 'Stop is the person\'s own' ); 75}); 76 77test ( 'every message is a plain sentence with a next step, carries its interface key, and is in the catalog in all nine languages' , () => { 78const langs = [ 'en' , 'zh' , 'ja' , 'de' , 'es' , 'ru' , 'pt' , 'ko' , 'fr' ]; 79const catalogs = Object . fromEntries ( langs . map ( l => [ l , JSON . parse ( readFileSync ( new URL ( `../src/locales/ ${ l } .json` , import . meta. url ), 'utf8' ))])); 80const idOf = text => Object . entries ( catalogs . en ). find (([, v ]) => v === text )?.[ 0 ]; 81for ( const [ reason , text ] of Object . entries ( GUARD_NOTES )) { 82const frame = guardNote ( reason ); 83assert . equal ( frame . type , 'delta' ); assert . equal ( frame . key , text ); assert . equal ( frame . own , true ); 84assert . ok ( text . length < 220 , reason ); 85assert . match ( text , / ( Try again | Tell me | Say | Send | approve ) / i , ` ${ reason } gives a next step` ); 86const id = idOf ( text ); 87assert . ok ( id , ` ${ reason } is in the English catalog` ); 88for ( const l of langs ) assert . ok ( catalogs [ l ][ id ]?. trim (), ` ${ reason } in ${ l } ` ); 89} 90assert . match ( GUARD_NOTES . context , / ran out of room / ); 91}); 92 93// ------------------------------------------------------------------------------------------------ with the real Harness 94 95async function rig ( t , options = {}) { 96const worker = await startScriptedWorker ({ chunkDelayMs :5 }); 97const dir = mkdtempSync ( join ( tmpdir (), 'strata-guard-' )); 98const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 99const logs = []; 100const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => [{ id :'i' , label :'S' , baseUrl :worker . url , modelId :'scripted-model' , context :options . context ?? 32768 , slots :2 }], connections :() => [], 101// these chats are in Manual and search without a person at the card: the Settings switch that skips the web question is on 102tools :() => ({ off :new Set (), search :{ provider :'builtin' , key :'' }, servers :{}, webWithoutAsking :true }), 103env :process . env , startTimeoutMs :90_000 , searchMock :'limited' , log :l => logs . push ( l ) }); 104t . after ( async () => { await bridge . close (); await worker . close (); try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }); 105return { worker, bridge, ws, logs, base :( chatId , onFrame ) => ({ chatId, workspacePath :ws , mode :'manual' , onFrame}) }; 106} 107const words = frames => frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ); 108 109test ( 'a search-heavy /plan on a web that keeps refusing stops after 3 failed searches, proposes the plan it has, and says why' , { skip}, async ( t ) => { 110const r = await rig ( t ); 111const out = []; 112await r . bridge . planCommand ({ ...r . base ( 'p1' , f => out . push ( f )), line :'SCRIPT:searchloop' }); 113const cards = out . filter ( f => f . type === 'agent-tool' && f . tool . name === 'web_search' && [ 'done' , 'error' ]. includes ( f . tool . state )); 114assert . ok ( cards . length >= 3 && cards . length <= 4 , `searches stopped at the limit ( ${ cards . length } )` ); 115assert . ok ( cards . some ( f => / Web search is limited right now / . test ( f . tool . result ?? '' )), 'the tool said web search is limited' ); 116assert . equal ( out . filter ( f => f . type === 'error' ). length , 0 , 'not an error: a normal end' ); 117const done = out . find ( f => f . type === 'done' ); 118assert . ok ( done && ! done . cancelled , 'the turn ended normally' ); 119const plan = out . find ( f => f . type === 'plan' ); 120assert . equal ( plan ?. event , 'proposed' , 'the plan it had is offered' ); 121assert . equal ( plan . plan . steps . length , 3 ); 122assert . equal ( plan . plan . caution , GUARD_NOTES [ 'searches-failed' ], 'and the card says why it stopped early' ); 123const requests = r . worker . requests . filter ( q => q . directive === 'searchloop' ); 124assert . ok ( requests . length <= 5 , `the model was not asked again and again ( ${ requests . length } requests)` ); 125assert . ok ( r . logs . some ( l => / turn guard: searches-failed / . test ( l ))); 126}); 127 128test ( 'an ordinary turn whose searches keep failing ends with the plain sentence as its last words' , { skip}, async ( t ) => { 129const r = await rig ( t ); 130const out = []; 131await r . bridge . runTurn ({ ...r . base ( 'c1' , f => out . push ( f )), message :'SCRIPT:searchloop' }); 132assert . equal ( out . filter ( f => f . type === 'error' ). length , 0 ); 133assert . ok ( out . find ( f => f . type === 'done' )); 134const note = out . filter ( f => f . type === 'delta' && f . key ). at ( - 1 ); 135assert . equal ( note ?. key , GUARD_NOTES [ 'searches-failed' ]); 136assert . match ( words ( out ), / Settings → Tools → Web search / ); 137assert . ok ( out . findIndex ( f => f . key ) < out . findIndex ( f => f . type === 'done' ), 'the sentence comes before the end of the turn' ); 138}); 139 140test ( 'a context at 100% with no answer is never silent: the plain message comes, and the older messages are summarised' , { skip}, async ( t ) => { 141const r = await rig ( t , { context :32768 }); 142const out = []; 143await r . bridge . runTurn ({ ...r . base ( 'f1' , f => out . push ( f )), message :'SCRIPT:bloat 32000' }); 144assert . equal ( out . filter ( f => f . type === 'error' ). length , 0 ); 145assert . ok ( out . find ( f => f . type === 'done' )); 146assert . equal ( out . filter ( f => f . type === 'delta' && f . key ). at ( - 1 )?. key , GUARD_NOTES . context ); 147assert . match ( words ( out ), / ran out of room / ); 148await new Promise ( res => setTimeout ( res , 1500 )); 149const compacted = r . logs . find ( l => / compact after a stopped turn / . test ( l )); 150assert . match ( compacted ?? '' , / compact after a stopped turn: \w +/ , `compaction was asked for and the Harness answered ( ${ compacted } )` ); 151const out2 = []; 152await r . bridge . runTurn ({ ...r . base ( 'f2' , f => out2 . push ( f )), message :'SCRIPT:bloat 3000' }); 153assert . equal ( out2 . filter ( f => f . type === 'delta' && f . key ). at ( - 1 )?. key , GUARD_NOTES . empty , 'no words at all, plenty of room: still a message' ); 154});