okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f9bfe8bc1
main
1/** 2* Time-skip in the app, for real: the host starts the job without waiting for it, follows its record, lists the changed files and 3* applies a revision the person chose. The revision step here is a small script (the assistant's turn is covered by the box runs). 4*/ 5import test from 'node:test' ; 6import assert from 'node:assert/strict' ; 7import { spawnSync } from 'node:child_process' ; 8import { existsSync , mkdtempSync , mkdirSync , readFileSync , writeFileSync , rmSync } from 'node:fs' ; 9import { tmpdir } from 'node:os' ; 10import { join , resolve } from 'node:path' ; 11import { fileURLToPath } from 'node:url' ; 12import { createTimeSkip , diffRun , measureFolder , timeskipRevisionMessage } from '../server/timeskip.mjs' ; 13 14const REPO = resolve ( fileURLToPath ( new URL ( '.' , import . meta. url )), '..' , '..' , '..' ); 15const PYTHON = process . env . STRATA_TEST_PYTHON ?? ( process . platform === 'win32' ?'python' :'python3' ); 16const hasPython = spawnSync ( PYTHON , [ '--version' ], { windowsHide :true }). status === 0 ; 17 18function sleep ( ms ) { return new Promise ( r => setTimeout ( r , ms )); } 19 20test ( 'the revision request tells the assistant to stay in the copy and to say what it did' , () => { 21const text = timeskipRevisionMessage ( 'make a launch plan' ); 22assert . match ( text , / current folder is that copy / ); 23assert . match ( text , / Never read or write outside it / ); 24assert . match ( text , / make a launch plan$ / ); 25}); 26 27test ( 'measureFolder stops early on a folder that is too big to copy' , () => { 28const dir = mkdtempSync ( join ( tmpdir (), 'ts-measure-' )); 29try { 30for ( let i = 0 ; i < 30 ; i ++ ) writeFileSync ( join ( dir , `f ${ i } .txt` ), 'x' ); 31assert . equal ( measureFolder ( dir ). tooBig , false ); 32assert . equal ( measureFolder ( dir , { maxFiles :10 }). tooBig , true ); 33mkdirSync ( join ( dir , 'node_modules' )); 34writeFileSync ( join ( dir , 'node_modules' , 'big.txt' ), 'y' . repeat ( 1000 )); 35assert . equal ( measureFolder ( dir , { maxBytes :100 }). tooBig , false , 'node_modules is not copied for a trial, so it does not count' ); 36} finally { rmSync ( dir , { recursive :true , force :true }); } 37}); 38 39test ( 'diffRun lists added, changed and removed files and says which revision to apply' , () => { 40const dir = mkdtempSync ( join ( tmpdir (), 'ts-diff-' )); 41try { 42const base = join ( dir , 'base' ), cand = join ( dir , 'cand' ); 43mkdirSync ( base ); mkdirSync ( cand ); 44writeFileSync ( join ( base , 'same.txt' ), 'same' ); writeFileSync ( join ( cand , 'same.txt' ), 'same' ); 45writeFileSync ( join ( base , 'edit.txt' ), 'one' ); writeFileSync ( join ( cand , 'edit.txt' ), 'one two' ); 46writeFileSync ( join ( base , 'gone.txt' ), 'bye' ); 47writeFileSync ( join ( cand , 'new.md' ), '# new' ); 48const found = diffRun ({ checkpoints :[{ id :'cp1-baseline' , label :'baseline' , path :base }], selected_checkpoint :'cp1-baseline' , attempts :[{ index :1 , path :cand }] }); 49assert . deepEqual ( found . files . map ( f => [ f . path , f . status ]), [[ 'edit.txt' , 'changed' ], [ 'gone.txt' , 'removed' ], [ 'new.md' , 'added' ]]); 50assert . equal ( found . files [ 0 ]. original , 'one' ); assert . equal ( found . files [ 0 ]. updated , 'one two' ); 51assert . equal ( found . applyAttempt , 1 , 'nothing was kept by the checks, so the person applies the last revision' ); 52} finally { rmSync ( dir , { recursive :true , force :true }); } 53}); 54 55test ( 'a run starts without the caller waiting, shows its changed files, and applies the chosen revision with a rollback copy' , { skip :! hasPython && 'no python on this machine' , timeout :120000 }, async () => { 56const dir = mkdtempSync ( join ( tmpdir (), 'ts-run-' )); 57try { 58const workspace = join ( dir , 'work' ); mkdirSync ( workspace ); 59writeFileSync ( join ( workspace , 'plan.md' ), 'first draft\n' ); 60const script = join ( dir , 'revise.mjs' ); 61writeFileSync ( script , "import { writeFileSync, appendFileSync } from 'node:fs'; await new Promise(r => setTimeout(r, 1500)); appendFileSync('plan.md', 'second line\\n'); writeFileSync('extra.md', process.env.STRATA_TIMESKIP_PROMPT);" ); 62const state = join ( dir , 'state' ); 63const ts = createTimeSkip ({ repoRoot :REPO , python :PYTHON , env :{ ...process . env , STRATA_TIMESKIP_DIR :state } }); 64const started = Date . now (); 65const result = await ts . startDetached ({ workspace, prompt :'extend the plan' , attempts :1 , reviseCommand :`" ${ process . execPath } " " ${ script } "` }); 66assert . ok ( result . ok , JSON . stringify ( result )); 67assert . ok ( Date . now () - started < 1400 , 'the call returned while the revision was still running' ); 68const id = result . run . id ; 69let run ; 70for ( let i = 0 ; i < 100 ; i ++ ) { run = ts . status ( id ); if ([ 'completed' , 'failed' ]. includes ( run . phase )) break ; await sleep ( 300 ); } 71assert . equal ( run . phase , 'completed' , JSON . stringify ( run )); 72assert . equal ( run . needsUserReview , true , 'no checks were declared, so the person decides' ); 73const files = ts . files ( id ); 74assert . deepEqual ( files . files . map ( f => [ f . path , f . status ]), [[ 'extra.md' , 'added' ], [ 'plan.md' , 'changed' ]]); 75assert . equal ( files . applyAttempt , 1 ); 76assert . equal ( readFileSync ( join ( workspace , 'plan.md' ), 'utf8' ), 'first draft\n' , 'the person\'s files are untouched until they choose' ); 77const applied = await ts . apply ({ id, attempt :files . applyAttempt }); 78assert . ok ( applied . ok , JSON . stringify ( applied )); 79assert . match ( readFileSync ( join ( workspace , 'plan.md' ), 'utf8' ), / second line / ); 80assert . equal ( readFileSync ( join ( workspace , 'extra.md' ), 'utf8' ), 'extend the plan' ); 81const restored = await ts . apply ({ id, restore :true }); 82assert . ok ( restored . ok , JSON . stringify ( restored )); 83assert . equal ( readFileSync ( join ( workspace , 'plan.md' ), 'utf8' ), 'first draft\n' ); 84} finally { rmSync ( dir , { recursive :true , force :true }); } 85}); 86 87test ( 'a run whose host is gone reads as interrupted, not as still working' , { skip :! hasPython && 'no python on this machine' , timeout :60000 }, async () => { 88const dir = mkdtempSync ( join ( tmpdir (), 'ts-gone-' )); 89try { 90const state = join ( dir , 'state' ), id = 'a' . repeat ( 32 ); 91mkdirSync ( join ( state , id ), { recursive :true }); 92writeFileSync ( join ( state , id , 'run.json' ), JSON . stringify ({ id, state :'generating' , workspace :dir , prompt :'x' , checkpoints :[], attempts :[] })); 93const ts = createTimeSkip ({ repoRoot :REPO , python :PYTHON , env :{ ...process . env , STRATA_TIMESKIP_DIR :state } }); 94assert . equal ( ts . status ( id ). phase , 'interrupted' ); 95} finally { rmSync ( dir , { recursive :true , force :true }); } 96}); 97 98test ( 'Stop ends the job and everything it started, deletes the copies, leaves the person\'s files alone, and the run then reads as cancelled' , { skip :! hasPython && 'no python on this machine' , timeout :120000 }, async () => { 99const dir = mkdtempSync ( join ( tmpdir (), 'ts-stop-' )); 100try { 101const workspace = join ( dir , 'work' ); mkdirSync ( workspace ); 102writeFileSync ( join ( workspace , 'plan.md' ), 'first draft\n' ); 103const pidFile = join ( dir , 'revise.pid' ); 104const script = join ( dir , 'slow.mjs' ); 105writeFileSync ( script , `import { writeFileSync } from 'node:fs'; writeFileSync( ${ JSON . stringify ( pidFile )} , String(process.pid)); writeFileSync('half-done.md', 'x'); await new Promise(r => setTimeout(r, 120000));` ); 106const state = join ( dir , 'state' ); 107const ts = createTimeSkip ({ repoRoot :REPO , python :PYTHON , env :{ ...process . env , STRATA_TIMESKIP_DIR :state } }); 108const started = await ts . startDetached ({ workspace, prompt :'slow one' , attempts :1 , reviseCommand :`" ${ process . execPath } " " ${ script } "` }); 109assert . ok ( started . ok , JSON . stringify ( started )); 110const id = started . run . id ; 111for ( let i = 0 ; i < 100 && ! existsSync ( pidFile ); i ++ ) await sleep ( 200 ); 112assert . ok ( existsSync ( pidFile ), 'the revision step is running' ); 113const pid = Number ( readFileSync ( pidFile , 'utf8' )); 114assert . equal ( ts . status ( id ). phase , 'generating' ); 115assert . equal ( await ts . stop ( id ), true ); 116assert . equal ( existsSync ( join ( state , id )), false , 'the copies are deleted' ); 117assert . equal ( ts . status ( id ). phase , 'cancelled' ); 118let alive = true ; for ( let i = 0 ; i < 40 && alive ; i ++ ) { try { process . kill ( pid , 0 ); await sleep ( 150 ); } catch { alive = false ; } } 119assert . equal ( alive , false , 'the revision command (a grandchild of the job) was ended too' ); 120assert . equal ( readFileSync ( join ( workspace , 'plan.md' ), 'utf8' ), 'first draft\n' ); 121assert . equal ( existsSync ( join ( workspace , 'half-done.md' )), false , 'nothing reached the person\'s folder' ); 122assert . equal ( await ts . stop ( 'b' . repeat ( 32 )), false , 'an id that is not a run is not "stopped"' ); 123} finally { rmSync ( dir , { recursive :true , force :true }); } 124}); 125 126test ( 'the revision step reads the host\'s stream: a long silent turn is fine, a failure is told in the host\'s words, a vanished host is "could not be reached"' , { timeout :60000 }, async () => { 127const http = await import ( 'node:http' ); 128const { spawn} = await import ( 'node:child_process' ); 129const script = join ( REPO , 'apps' , 'host' , 'server' , 'timeskip-revise.mjs' ); 130const mode = { current :'ok' }; 131const server = http . createServer (( req , res ) => { 132if ( req . headers [ 'x-strata-internal' ] !== 's3cret' ) { res . writeHead ( 403 , { 'content-type' :'application/json' }); res . end ( '{"error":"Not allowed."}' ); return ; } 133if ( mode . current === 'refuse' ) { res . writeHead ( 503 , { 'content-type' :'application/json' }); res . end ( '{"error":"Load a model first, then try Time-skip again."}' ); return ; } 134res . writeHead ( 200 , { 'content-type' :'application/x-ndjson' }); 135res . write ( '{"type":"beat"}\n' ); 136setTimeout (() => res . write ( '{"type":"beat"}\n' ), 300 ); 137setTimeout (() => { 138if ( mode . current === 'ok' ) res . end ( '{"type":"result","text":"I added a second line."}\n' ); 139else if ( mode . current === 'error' ) res . end ( '{"type":"error","message":"The model stopped answering."}\n' ); 140else res . end (); // the stream ends with no result 141}, 900 ); 142}); 143await new Promise ( r => server . listen ( 0 , '127.0.0.1' , r )); 144const run = ( env = {}) => new Promise ( resolve => { 145const child = spawn ( process . execPath , [ script ], { env :{ ...process . env , STRATA_HOST_URL :`http://127.0.0.1: ${ server . address (). port } ` , STRATA_INTERNAL_SECRET :'s3cret' , STRATA_TIMESKIP_PROMPT :'x' , ...env } }); 146let out = '' , err = '' ; child . stdout . on ( 'data' , d => { out += d ; }); child . stderr . on ( 'data' , d => { err += d ; }); 147child . on ( 'close' , code => resolve ({ code, out :out . trim (), err :err . trim () })); 148}); 149try { 150mode . current = 'ok' ; assert . deepEqual ( await run (), { code :0 , out :'I added a second line.' , err :'' }); 151mode . current = 'error' ; const bad = await run (); assert . equal ( bad . code , 1 ); assert . equal ( bad . err , 'The model stopped answering.' ); 152mode . current = 'cut' ; const cut = await run (); assert . equal ( cut . code , 1 ); assert . match ( cut . err , / stopped before it finished / ); 153mode . current = 'refuse' ; assert . match (( await run ()). err , / Load a model first / ); 154assert . match (( await run ({ STRATA_INTERNAL_SECRET :'wrong' })). err , / Not allowed / ); 155assert . match (( await run ({ STRATA_INTERNAL_SECRET :'' })). err , / needs the Strata app / ); 156} finally { server . close (); } 157const gone = await new Promise ( resolve => { const child = spawn ( process . execPath , [ script ], { env :{ ...process . env , STRATA_HOST_URL :'http://127.0.0.1:9' , STRATA_INTERNAL_SECRET :'s' , STRATA_TIMESKIP_PROMPT :'x' } }); let err = '' ; child . stderr . on ( 'data' , d => { err += d ; }); child . on ( 'close' , code => resolve ({ code, err})); }); 158assert . equal ( gone . code , 1 ); assert . match ( gone . err , / could not be reached / ); 159});