okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
dca9770ef
main
1// The task board: what lands in which column, which button a card gets, what a dismissal hides, and what the host keeps so that it 2// stays true (a new run clears the last problem; the loop and chat records the board reads). 3import test from 'node:test' ; 4import assert from 'node:assert/strict' ; 5import { build } from 'esbuild' ; 6import { createTaskService } from '../server/tasks.mjs' ; 7import { lastLine } from '../server/task-report.mjs' ; 8 9const compiled = await build ({ stdin :{ contents :"export * from './src/lib/board'; export * from './src/lib/loop-runner'; export * from './src/lib/task-handover'; export * from './src/lib/i18n';" , resolveDir :process . cwd (), loader :'ts' }, bundle :true , write :false , format :'esm' , platform :'node' , loader :{ '.json' :'json' } }); 10const { boardCards, isInside, canApproveOnBoard, plainLine, folderName, LoopScheduler, chatHandoverMessage} = await import ( `data:text/javascript;base64, ${ Buffer . from ( compiled . outputFiles [ 0 ]. text ). toString ( 'base64' )} ` ); 11 12const NOW = Date . parse ( '2026-10-19T12:00:00Z' ); 13const ago = ms => new Date ( NOW - ms ). toISOString (); 14const MIN = 60_000 , HOUR = 3_600_000 , DAY = 86_400_000 ; 15const task = ( over = {}) => ({ id :'t1' , title :'Backup check' , prompt :'p' , frequency :'daily' , at :'02:00' , weekday :1 , timeZone :'UTC' , enabled :true , nextRunAt :new Date ( NOW + HOUR ). toISOString (), status :'done' , lastRunAt :ago ( 2 * HOUR ), finishedAt :ago ( 2 * HOUR - MIN ), ...over }); 16const msg = ( role , content , over = {}) => ({ id :`m ${ Math . random ()} ` , role, content, at :ago ( HOUR ), ...over }); 17const chat = ( over = {}) => ({ id :'c1' , title :'Fix rounding' , workspace :'C:\\work\\billing-api' , createdAt :ago ( DAY ), updatedAt :ago ( HOUR ), messages :[ msg ( 'user' , 'fix it' ), msg ( 'assistant' , 'Fixed. Totals now round to the cent.' )], tokensIn :0 , tokensOut :0 , ...over }); 18const input = ( over = {}) => ({ tasks :[], sessions :[], liveChats :[], loopChats :[], pending :null , activeSession :null , now :NOW , ...over }); 19const ask = ( over = {}) => ({ id :'tool1' , name :'write_file' , args :{}, preview :'logs/a.txt' , effect :'Change a file' , scope :'write' , target :'C:\\work\\billing-api\\logs\\a.txt' , state :'proposed' , live :true , ...over }); 20const waitingChat = ( tool , over = {}) => chat ({ messages :[ msg ( 'user' , 'go' ), msg ( 'assistant' , '' , { tools :[ tool ] })], ...over }); 21const ids = list => list . map ( c => c . id ); 22 23test ( 'a scheduled task lands where its state puts it' , () => { 24const b = boardCards ( input ({ tasks :[ 25task ({ id :'run' , status :'running' , lastRunAt :ago ( 2 * MIN ), finishedAt :null }), 26task ({ id :'err' , status :'error' , error :'no model loaded' }), 27task ({ id :'stop' , status :'cancelled' , error :'Run stopped.' }), 28task ({ id :'gone' , status :'interrupted' }), 29task ({ id :'yes' , status :'done' , attention :'It wanted a yes.' , lastLine :'All 4 folders read.' }), 30task ({ id :'ok' , status :'done' , lastLine :'Twelve changes this week.' }), 31task ({ id :'new' , status :'idle' , lastRunAt :undefined , finishedAt :undefined }), 32task ({ id :'old' , status :'done' , finishedAt :ago ( 8 * DAY ), lastRunAt :ago ( 8 * DAY ) }), 33task ({ id :'arch' , status :'error' , archived :true , error :'x' }), 34] })); 35assert . deepEqual ( ids ( b . columns . running ), [ 'run' ]); 36assert . deepEqual ( ids ( b . columns . attention ). sort (), [ 'err' , 'gone' , 'stop' , 'yes' ]); 37assert . deepEqual ( ids ( b . columns . done ), [ 'ok' ], 'older than 7 days, archived and never-run tasks are not on the board' ); 38assert . deepEqual ( b . columns . waiting , []); 39assert . equal ( b . need , 4 ); 40assert . deepEqual ( b . problemTasks . sort (), [ 'err' , 'gone' , 'stop' , 'yes' ]); 41}); 42 43test ( 'a task card has one next step and a menu, by what happened' , () => { 44const b = boardCards ( input ({ tasks :[ task ({ id :'run' , status :'running' , finishedAt :null }), task ({ id :'err' , status :'error' , error :'boom' }), task ({ id :'yes' , attention :'a' }), task ({ id :'ok' })] })); 45const by = id => Object . values ( b . columns ). flat (). find ( c => c . id === id ); 46assert . deepEqual ([ by ( 'run' ). primary , by ( 'run' ). menu ], [ 'stop-task' , [ 'open-task' ]]); 47assert . deepEqual ([ by ( 'err' ). primary , by ( 'err' ). menu ], [ 'run-again' , [ 'open-task' , 'continue' , 'dismiss' ]]); 48assert . deepEqual ([ by ( 'yes' ). primary , by ( 'yes' ). menu ], [ 'continue' , [ 'open-task' , 'dismiss' ]], 'a run that needed a yes continues in a new chat' ); 49assert . deepEqual ([ by ( 'ok' ). primary , by ( 'ok' ). menu ], [ 'view-result' , [ 'dismiss' ]], 'a Done card can be dismissed too' ); 50assert . equal ( by ( 'err' ). reason . tone , 'bad' ); 51assert . equal ( by ( 'yes' ). reason . tone , 'warn' ); 52}); 53 54test ( 'dismissing a task hides that run only; a newer run brings its problem back' , () => { 55const failed = task ({ status :'error' , error :'boom' , finishedAt :ago ( 3 * HOUR ) }); 56assert . equal ( boardCards ( input ({ tasks :[{ ...failed , ackedAt :ago ( HOUR ) }] })). need , 0 ); 57assert . equal ( boardCards ( input ({ tasks :[{ ...failed , ackedAt :ago ( 4 * HOUR ) }] })). need , 1 , 'dismissed before this run ended' ); 58const done = task ({ ackedAt :ago ( MIN ) }); 59assert . equal ( boardCards ( input ({ tasks :[ done ] })). columns . done . length , 0 ); 60}); 61 62test ( 'the next scheduled runs are listed soonest first, paused tasks left out' , () => { 63const b = boardCards ( input ({ tasks :[ task ({ id :'b' , title :'B' , nextRunAt :new Date ( NOW + 2 * HOUR ). toISOString () }), task ({ id :'a' , title :'A' , nextRunAt :new Date ( NOW + HOUR ). toISOString () }), task ({ id :'p' , enabled :false })] })); 64assert . deepEqual ( b . upcoming . map ( u => u . id ), [ 'a' , 'b' ]); 65}); 66 67test ( 'a chat waits only while the host still holds the approval' , () => { 68const s = waitingChat ( ask ()); 69assert . deepEqual ( ids ( boardCards ( input ({ sessions :[ s ], liveChats :[ 'c1' ], pending :[{ chatId :'c1' , callIds :[ 'tool1' ], at :NOW - 4 * MIN }] })). columns . waiting ), [ 'c1' ]); 70const gone = boardCards ( input ({ sessions :[ s ], pending :[] })); 71assert . equal ( gone . columns . waiting . length , 0 , 'the host no longer holds it: a stale card is not a question' ); 72assert . equal ( boardCards ( input ({ sessions :[ s ], pending :null })). columns . waiting . length , 1 , 'unknown: trust the card' ); 73const card = boardCards ( input ({ sessions :[ s ], liveChats :[ 'c1' ], pending :[{ chatId :'c1' , callIds :[ 'tool1' ], at :NOW - 4 * MIN }] })). columns . waiting [ 0 ]; 74assert . equal ( card . at , NOW - 4 * MIN ); 75assert . equal ( boardCards ( input ({ sessions :[ s ], liveChats :[ 'c1' ], pending :[{ chatId :'c1' , callIds :[ 'tool1' ] }] })). columns . running . length , 0 , 'a waiting chat is not also running' ); 76}); 77 78test ( 'Approve on the card is for file read and write inside the chat folder; the rest opens the chat' , () => { 79const card = tool => boardCards ( input ({ sessions :[ waitingChat ( tool )] })). columns . waiting [ 0 ]; 80const ok = card ( ask ()); 81assert . equal ( ok . primary , 'approve' ); 82assert . deepEqual ( ok . menu , [ 'deny' , 'open-chat' ]); 83assert . deepEqual ( ok . approve . toolId , 'tool1' ); 84for ( const tool of [ ask ({ scope :'shell' , target :'rm -rf logs' }), ask ({ scope :'connected' , target :'github' }), ask ({ target :'C:\\work\\other\\a.txt' }), ask ({ target :'C:\\work\\billing-api\\..\\secret.txt' }), ask ({ target :undefined })]) { 85const c = card ( tool ); 86assert . equal ( c . primary , 'open-chat' , JSON . stringify ( tool )); 87assert . equal ( c . approve , undefined ); 88} 89assert . equal ( canApproveOnBoard ({ scope :'read' , target :'src/a.ts' }, 'C:\\work\\billing-api' ), true , 'a relative path is in the folder' ); 90assert . equal ( canApproveOnBoard ({ scope :'read' , target :'c:\\WORK\\Billing-API\\a.ts' }, 'C:\\work\\billing-api' ), true , 'Windows paths ignore case' ); 91assert . equal ( isInside ( '/home/me/proj/a.ts' , '/home/me/proj' ), true ); 92assert . equal ( isInside ( '/home/me/project2/a.ts' , '/home/me/proj' ), false , 'a sibling with the same start is outside' ); 93assert . equal ( isInside ( '/home/me/Proj/a.ts' , '/home/me/proj' ), false , 'Linux paths do not ignore case' ); 94}); 95 96test ( 'a running chat and a running loop are one card each, never two for the same chat' , () => { 97const loop = { prompt :'check the build' , everyMs :10 * MIN , startedAt :NOW - 20 * MIN , state :'running' , answers :2 , maxRuns :6 , nextAt :NOW + 4 * MIN , lastText :'Build is still red.' }; 98const b = boardCards ( input ({ sessions :[ chat ({ loop}), chat ({ id :'c2' , title :'Refactor' , agents :[{ id :'a' , name :'h' , description :'' , status :'working' , durationMs :0 , tokens :0 }] })], liveChats :[ 'c2' ], loopChats :[ 'c1' ] })); 99assert . deepEqual ( b . columns . running . map ( c => [ c . key , c . primary , c . menu ]), [[ 'chat:c2' , 'open-chat' , [ 'stop-chat' ]], [ 'loop:c1' , 'stop-loop' , [ 'open-chat' ]]]. sort (( x , y ) => b . columns . running . findIndex ( c => c . key === x [ 0 ]) - b . columns . running . findIndex ( c => c . key === y [ 0 ]))); 100const l = b . columns . running . find ( c => c . source === 'loop' ); 101assert . deepEqual ( l . meta , { text :'answer {0} of {1}' , params :[ 3 , 6 ] }); 102assert . equal ( l . nextAt , NOW + 4 * MIN ); 103assert . equal ( b . columns . running . find ( c => c . id === 'c2' ). meta . params [ 0 ], 1 ); 104}); 105 106test ( 'a loop that ended is Done, unless 3 runs in a row failed; then it needs attention' , () => { 107const ended = why => chat ({ loop :{ prompt :'watch' , everyMs :5 * MIN , startedAt :NOW - HOUR , state :'ended' , endedWhy :why , endedAt :NOW - 10 * MIN , answers :3 } }); 108for ( const why of [ 'count' , 'said-done' , 'time' , 'cap' , 'stopped' , 'closed' ]) { 109const b = boardCards ( input ({ sessions :[ ended ( why )] })); 110assert . equal ( b . columns . done . length , 1 , why ); 111assert . equal ( b . columns . attention . length , 0 , why ); 112} 113const bad = boardCards ( input ({ sessions :[ ended ( 'failures' )] })). columns . attention [ 0 ]; 114assert . equal ( bad . reason . kind , 'loop-failed' ); 115assert . deepEqual ([ bad . primary , bad . menu ], [ 'open-chat' , [ 'continue' , 'dismiss' ]]); 116const running = chat ({ loop :{ prompt :'x' , everyMs :MIN , startedAt :NOW - HOUR , state :'running' , answers :1 } }); 117assert . equal ( boardCards ( input ({ sessions :[ running ] })). columns . done [ 0 ]. chip . text , 'Stopped when Strata closed' , 'a record that says running with no loop behind it is a loop the window closed on' ); 118}); 119 120test ( 'chats show up only with something to do, from the last 7 days' , () => { 121const b = boardCards ( input ({ sessions :[ 122chat ({ id :'unread' , lastReadAt :ago ( 2 * HOUR ) }), 123chat ({ id :'seen' , lastReadAt :ago ( 30 * MIN ) }), 124chat ({ id :'open' }), 125chat ({ id :'old' , updatedAt :ago ( 8 * DAY ), lastReadAt :ago ( 9 * DAY ) }), 126chat ({ id :'bad' , messages :[ msg ( 'user' , 'go' ), msg ( 'assistant' , '' , { error :'The model stopped while starting.' })] }), 127chat ({ id :'typing' , messages :[ msg ( 'user' , 'hello' )] }), 128chat ({ id :'stream' , lastReadAt :ago ( DAY ), messages :[ msg ( 'user' , 'go' ), msg ( 'assistant' , 'part' , { streaming :true })] }), 129chat ({ id :'arch' , archived :true , lastReadAt :ago ( DAY ) }), 130], activeSession :'open' })); 131assert . deepEqual ( ids ( b . columns . done ), [ 'unread' ]); 132assert . deepEqual ( ids ( b . columns . attention ), [ 'bad' ]); 133assert . deepEqual ([ b . columns . attention [ 0 ]. primary , b . columns . attention [ 0 ]. menu ], [ 'open-chat' , [ 'continue' , 'dismiss' ]]); 134assert . equal ( b . columns . done [ 0 ]. folder , 'billing-api' ); 135}); 136 137test ( 'dismissing a chat card hides it until something newer happens in that chat' , () => { 138const bad = chat ({ messages :[ msg ( 'user' , 'go' ), msg ( 'assistant' , '' , { error :'boom' })], updatedAt :ago ( HOUR ) }); 139assert . equal ( boardCards ( input ({ sessions :[{ ...bad , ackedAt :ago ( 30 * MIN ) }] })). need , 0 ); 140assert . equal ( boardCards ( input ({ sessions :[{ ...bad , ackedAt :ago ( 2 * HOUR ) }] })). need , 1 ); 141const endedLoop = chat ({ loop :{ prompt :'x' , everyMs :MIN , startedAt :NOW - HOUR , state :'ended' , endedWhy :'failures' , endedAt :NOW - 20 * MIN , answers :0 } }); 142assert . equal ( boardCards ( input ({ sessions :[{ ...endedLoop , ackedAt :ago ( 10 * MIN ) }] })). need , 0 ); 143}); 144 145test ( 'every column is newest first' , () => { 146const b = boardCards ( input ({ tasks :[ task ({ id :'a' , finishedAt :ago ( 3 * HOUR ) }), task ({ id :'b' , finishedAt :ago ( HOUR ) })] })); 147assert . deepEqual ( ids ( b . columns . done ), [ 'b' , 'a' ]); 148}); 149 150test ( 'small helpers: one plain line, a folder name' , () => { 151assert . equal ( plainLine ( '**Fixed.** Totals now round to the cent and the tests pass. More text.' ), 'Fixed. Totals now round to the cent and the tests pass.' ); 152assert . equal ( plainLine ( '# Report\n\n- first thing\n- second' ), 'Report first thing second' ); 153assert . equal ( folderName ( 'C:\\work\\billing-api\\' ), 'billing-api' ); 154assert . equal ( folderName ( '' ), undefined ); 155}); 156 157/* ---- what the host and the loop keep for the board ---- */ 158 159test ( 'the host line for a card is the first plain sentence, without the list of steps or the note' , () => { 160assert . equal ( lastLine ( 'Two things need your attention. Disk space is low.\n\n---\n\n**What it did**\n\n- Read the log\n\n> needed a yes' ), 'Two things need your attention.' ); 161assert . equal ( lastLine ( '**All 4** backup folders were found and read.\n\n> note' ), 'All 4 backup folders were found and read.' ); 162assert . equal ( lastLine ( '' ), '' ); 163assert . ok ( lastLine ( 'x' . repeat ( 500 )). length <= 160 ); 164}); 165 166function service ( run , seed = []) { 167let db = seed , t = Date . parse ( '2026-10-19T12:00:00Z' ); 168const svc = createTaskService ({ read :() => db , write :r => { db = JSON . parse ( JSON . stringify ( r )); }, run, now :() => t }); 169return { svc, advance :ms => { t += ms ; }, db :() => db }; 170} 171const draft = { title :'T' , prompt :'p' , frequency :'daily' , at :'08:00' , weekday :1 , timeZone :'UTC' , mode :'plan' }; 172 173test ( 'a run records when it ended and its one plain line; a failure keeps only the newest problem' , async () => { 174let n = 0 ; 175const { svc, advance} = service ( async () => { 176n += 1 ; 177if ( n === 1 ) return { text :'All 4 folders read.\n\n> It wanted a yes.' , attention :'It wanted a yes.' }; 178if ( n === 2 ) throw new Error ( 'first problem' ); 179if ( n === 3 ) throw new Error ( 'second problem' ); 180return { text :'Fine now.' }; 181}); 182const id = svc . put ( draft ). id ; 183await svc . execute ( id ); 184let t = svc . list ()[ 0 ]; 185assert . equal ( t . status , 'done' ); assert . equal ( t . attention , 'It wanted a yes.' ); assert . equal ( t . lastLine , 'All 4 folders read.' ); assert . ok ( t . finishedAt ); 186advance ( MIN ); 187await svc . execute ( id ); 188t = svc . list ()[ 0 ]; 189assert . equal ( t . status , 'error' ); assert . equal ( t . error , 'first problem' ); assert . equal ( t . attention , null , 'a stale "needed a yes" does not survive a later run' ); 190advance ( MIN ); 191await svc . execute ( id ); 192assert . equal ( svc . list ()[ 0 ]. error , 'second problem' , 'only the newest problem is kept' ); 193await svc . execute ( id ); 194t = svc . list ()[ 0 ]; 195assert . equal ( t . error , null ); assert . equal ( t . status , 'done' ); 196}); 197 198test ( 'Dismiss is a mark on the task (ackedAt) that a new run clears' , async () => { 199const { svc} = service ( async () => { throw new Error ( 'boom' ); }); 200const id = svc . put ( draft ). id ; 201await svc . execute ( id ); 202const mark = new Date (). toISOString (); 203svc . put ({ ackedAt :mark }, id ); 204assert . equal ( svc . list ()[ 0 ]. ackedAt , mark ); 205assert . equal ( svc . list ()[ 0 ]. error , 'boom' , 'dismissing keeps the result' ); 206await svc . execute ( id ); 207assert . equal ( svc . list ()[ 0 ]. ackedAt , null ); 208svc . put ({ title :'Renamed' }, id ); 209assert . equal ( svc . list ()[ 0 ]. ackedAt , null , 'an edit that does not mention it leaves it alone' ); 210}); 211 212test ( 'a loop leaves a record on its chat: running with the next time, then how it ended' , async () => { 213const records = []; 214let clock = 1_000 , timer = null ; 215const sched = new LoopScheduler ({ 216send :async () => ({ answered :true , text :'Build is still red: 2 tests fail.' , failed :false }), 217note :() => {}, exists :() => true , ready :() => true , now :() => clock , 218setTimer :( fn , ms ) => { timer = { fn, ms}; return timer ; }, clearTimer :() => { timer = null ; }, 219track :( id , record ) => records . push ({ id, ...record }), 220}); 221await sched . start ( 'c1' , { everyMs :10 * MIN , prompt :'check the build' , maxRuns :2 }); 222assert . deepEqual ( sched . ids (), [ 'c1' ]); 223const waiting = records . at ( - 1 ); 224assert . equal ( waiting . state , 'running' ); assert . equal ( waiting . answers , 1 ); assert . equal ( waiting . nextAt , 1_000 + 10 * MIN ); assert . equal ( waiting . lastText , 'Build is still red: 2 tests fail.' ); assert . equal ( waiting . maxRuns , 2 ); 225clock += 10 * MIN ; 226await timer . fn (); 227await new Promise ( r => setImmediate ( r )); 228const ended = records . at ( - 1 ); 229assert . equal ( ended . state , 'ended' ); assert . equal ( ended . endedWhy , 'count' ); assert . equal ( ended . answers , 2 ); 230assert . deepEqual ( sched . ids (), []); 231 232await sched . start ( 'c2' , { everyMs :MIN , prompt :'x' }); 233assert . equal ( sched . stop ( 'c2' ), true ); 234assert . equal ( records . at ( - 1 ). endedWhy , 'stopped' ); 235}); 236 237test ( '"Continue in a new chat" on a chat starts from what was asked, what went wrong and the last answer' , () => { 238const s = chat ({ messages :[ msg ( 'user' , 'Update the dependencies' ), msg ( 'assistant' , 'Working on it.' , { error :'The model stopped while starting.' }), msg ( 'assistant' , 'note' , { local :true })] }); 239const text = chatHandoverMessage ( s ); 240assert . match ( text , / Continuing from the chat “Fix rounding” / ); 241assert . match ( text , / Update the dependencies / ); 242assert . match ( text , / The model stopped while starting\. / ); 243assert . match ( text , / Working on it\. / ); 244assert . doesNotMatch ( text , / note / ); 245assert . match ( text , / Please help me take it from here\.$ / ); 246const loopText = chatHandoverMessage ( chat ({ loop :{ prompt :'watch the deploy' , everyMs :MIN , startedAt :0 , state :'ended' , endedWhy :'failures' , endedAt :1 , answers :0 } })); 247assert . match ( loopText , / watch the deploy / ); 248assert . match ( loopText , / 3 runs in a row did not work / ); 249});