okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
66331f9bc
main
1/** 2* Time-skip, from the App Host. 3* 4* Strata Control owns the job: checkpointing, isolated candidates, the checks and the decision all 5* live in `strata_control/time_skip.py` and are driven through the `strata timeskip` CLI. This 6* module is only the bridge — it starts that command, streams its output, and reads back the durable 7* `run.json` the job writes. 8* 9* Two rules it must not break: 10* 11* 1. **It never decides anything.** Whether a candidate was kept is the job's answer, read from 12* disk. This module does not compute a status, a score or a progress fraction. 13* 2. **It never reports progress it does not have.** The job's phases are coarse and a check can 14* take minutes with nothing to say, so the stream carries what the command actually printed and 15* the UI shows a phase, not a percentage. 16* 17* A run is a job, not a request: it outlives the HTTP call that started it. The endpoint returns the 18* run id immediately and the client follows it with `/api/timeskip/status`. 19*/ 20import { spawn } from 'node:child_process' ; 21import { endTreeThenKill , ownGroup } from './process-tree.mjs' ; 22import { existsSync , readFileSync , readdirSync , rmSync , statSync } from 'node:fs' ; 23import { isAbsolute , join , relative , resolve } from 'node:path' ; 24import { timeSkipDir } from './platform-paths.mjs' ; 25 26/** Where runs are recorded. Mirrors the CLI's own default resolution. */ 27function stateDir ( env = process . env ) { 28return timeSkipDir ( env ); 29} 30 31function readRun ( root , id ) { 32const file = join ( root , id , 'run.json' ); 33if ( ! existsSync ( file )) return null ; 34try { 35return JSON . parse ( readFileSync ( file , 'utf8' )); 36} catch { 37// A partially written record is not a run: the job writes atomically, so a parse failure means 38// something else touched the file. Report it as missing rather than as an empty run. 39return null ; 40} 41} 42 43function listRuns ( root ) { 44if ( ! existsSync ( root )) return []; 45const out = []; 46for ( const entry of readdirSync ( root , { withFileTypes :true })) { 47if ( ! entry . isDirectory ()) continue ; 48const run = readRun ( root , entry . name ); 49if ( run ) out . push ( summarise ( run )); 50} 51return out . sort (( a , b ) => ( b . startedAt ?? 0 ) - ( a . startedAt ?? 0 )); 52} 53 54/** 55* The projection the UI consumes. 56* 57* Everything here is copied from the job's own record. `decision` and `needsUserReview` are the 58* job's answers; `phase` is its current state. There is deliberately no derived `percent`. 59*/ 60function summarise ( run ) { 61const attempts = run . attempts ?? []; 62const checkpoints = run . checkpoints ?? []; 63return { 64id :run . id , 65phase :run . state , 66workspace :run . workspace , 67prompt :run . prompt , 68startedAt :run . started_at ?? null , 69finishedAt :run . finished_at ?? null , 70attempts :attempts . map (( a ) => ({ 71index :a . index , 72decision :a . decision ?? null , 73reason :a . reason ?? '' , 74checks :( a . checks ?? []). map (( c ) => ({ id :c . id , outcome :c . outcome , kind :c . kind })), 75})), 76checkpoints :checkpoints . map (( c ) => ({ 77id :c . id , 78label :c . label , 79digest :c . digest , 80checks :( c . checks ?? []). map (( x ) => ({ id :x . id , outcome :x . outcome , kind :x . kind })), 81})), 82selectedCheckpoint :run . selected_checkpoint ?? null , 83decision :run . decision ?? null , 84// `unknown` checks must survive to the UI as unknown; a caller that renders this as a failure 85// or as a pass is the bug this field exists to prevent. 86needsUserReview :Boolean ( run . decision ?. needs_user_review ), 87error :run . error ?? null , 88}; 89} 90 91const TERMINAL = new Set ([ 'completed' , 'cancelled' , 'failed' , 'interrupted' ]); 92const SKIP_DIRS = new Set ([ '.git' , '.strata' , '__pycache__' , 'node_modules' ]); 93const MAX_TEXT_BYTES = 200_000 ; 94const MAX_LISTED = 60 ; 95const MAX_WITH_TEXT = 12 ; 96 97/** Every file under a folder, as relative forward-slash paths. */ 98function walkFiles ( root ) { 99const out = []; 100if ( ! root || ! existsSync ( root )) return out ; 101const walk = dir => { 102for ( const entry of readdirSync ( dir , { withFileTypes :true })) { 103if ( out . length > 5000 ) return ; 104const full = join ( dir , entry . name ); 105if ( entry . isDirectory ()) { if ( ! SKIP_DIRS . has ( entry . name )) walk ( full ); } 106else if ( entry . isFile ()) out . push ( relative ( root , full ). split ( '\\' ). join ( '/' )); 107} 108}; 109walk ( root ); 110return out . sort (); 111} 112 113function readText ( path ) { 114try { 115if ( statSync ( path ). size > MAX_TEXT_BYTES ) return { big :true }; 116const buffer = readFileSync ( path ); 117if ( buffer . subarray ( 0 , 4096 ). includes ( 0 )) return { binary :true }; 118return { text :buffer . toString ( 'utf8' ) }; 119} catch { return { missing :true }; } 120} 121 122/** Whether two files hold the same bytes (a big file that did not change must not be listed as changed). Files over 64 MB are treated as changed. */ 123function sameBytes ( a , b ) { 124try { 125const sa = statSync ( a ), sb = statSync ( b ); 126if ( sa . size !== sb . size ) return false ; 127if ( sa . size > 64 * 1024 * 1024 ) return false ; 128return readFileSync ( a ). equals ( readFileSync ( b )); 129} catch { return false ; } 130} 131 132/** What the assistant is told for one revision attempt. It works on a copy, so it is told to stay in it and to say what it did. */ 133export function timeskipRevisionMessage ( request ) { 134return [ 135'You are improving a copy of the user\'s work. The current folder is that copy: the original is safe and you cannot see it.' , 136'Rules:' , 137'1. Work only inside the current folder. Never read or write outside it.' , 138'2. Make the change the user asked for by creating or editing files here. If the folder is empty, create the file(s) the request needs.' , 139'3. Do not delete the user\'s files unless the request says to.' , 140'4. Do not run long programs or start servers.' , 141'5. When you are done, answer in one or two plain sentences: what you changed.' , 142'' , 143'The request:' , 144String ( request ). trim (), 145]. join ( '\n' ); 146} 147 148/** End a process and everything it started (the job, the Python it runs, the revision command and its Node). */ 149function killTree ( child ) { 150endTreeThenKill ( child ); // Windows: taskkill /T. Linux and macOS: the job leads its own process group (startDetached), so the group is ended (#4529 #4570) 151} 152 153/** How big a folder is, stopping early once it is clearly too big to copy for a trial. */ 154export function measureFolder ( root , { maxFiles= 3000 , maxBytes= 300 * 1024 * 1024 } = {}) { 155let files = 0 , bytes = 0 , tooBig = false ; 156const walk = dir => { 157if ( tooBig ) return ; 158let entries ; 159try { entries = readdirSync ( dir , { withFileTypes :true }); } catch { return ; } 160for ( const entry of entries ) { 161const full = join ( dir , entry . name ); 162if ( entry . isDirectory ()) { if ( ! SKIP_DIRS . has ( entry . name )) walk ( full ); } 163else if ( entry . isFile ()) { 164files += 1 ; 165try { bytes += statSync ( full ). size ; } catch { /* ignore */ } 166if ( files > maxFiles || bytes > maxBytes ) { tooBig = true ; return ; } 167} 168if ( tooBig ) return ; 169} 170}; 171walk ( root ); 172return { files, bytes, tooBig}; 173} 174 175/** 176* What a run changed, file by file: the saved original against the revision, for the Compare view. 177* Reads the folders the job itself kept; it decides nothing. 178*/ 179/** Pictures the Compare view shows side by side (read as bytes through /api/timeskip/file, never as text). */ 180export const IMAGE_TYPES = { png :'image/png' , jpg :'image/jpeg' , jpeg :'image/jpeg' , gif :'image/gif' , webp :'image/webp' , svg :'image/svg+xml' , bmp :'image/bmp' }; 181const MAX_IMAGE_BYTES = 12 * 1024 * 1024 ; 182export const imageTypeOf = path => IMAGE_TYPES [ String ( path ). split ( '.' ). pop (). toLowerCase ()] ?? null ; 183 184/** The two folders a run compares: the saved original and the revision (or the last attempt when the checks kept nothing). */ 185export function runRoots ( record ) { 186const baseline = ( record . checkpoints ?? []). find ( c => c . label === 'baseline' ); 187const selected = ( record . checkpoints ?? []). find ( c => c . id === record . selected_checkpoint ); 188const attempts = record . attempts ?? []; 189const last = attempts [ attempts . length - 1 ] ?? null ; 190const useAttempt = ! selected || selected . id === baseline ?. id ; 191return { baseRoot :baseline ?. path ?? null , updatedRoot :( useAttempt ?last ?. path :selected ?. path ) ?? null , useAttempt, last}; 192} 193 194/** The absolute path of one picture of a run, for one side, or null: not a picture, not inside the run's folder, missing or too big. */ 195export function runImagePath ( record , relPath , version ) { 196if ( ! imageTypeOf ( relPath )) return null ; 197const { baseRoot, updatedRoot} = runRoots ( record ); 198const root = version === 'original' ?baseRoot :version === 'updated' ?updatedRoot :null ; 199if ( ! root ) return null ; 200const full = resolve ( root , ...String ( relPath ). split ( '/' )); 201const inside = relative ( resolve ( root ), full ); 202if ( ! inside || inside . startsWith ( '..' ) || isAbsolute ( inside )) return null ; 203try { const st = statSync ( full ); return st . isFile () && st . size <= MAX_IMAGE_BYTES ?full :null ; } catch { return null ; } 204} 205 206/** 207* Files that are the program's own housekeeping, not the person's work: a browser profile, a cache folder, a tool's hidden folder. They are 208* still listed when they changed (never hidden from the person), but last, and without their contents, so the comparison opens on the work 209* that was asked for and not on a cache file. 210*/ 211const NOISE_DIR = / ^ (?: \. [ ^ . ] | __pycache__$ | node_modules$ | cache$ | gpucache$ | code cache$ | crashpad$ | shadercache$ ) / i ; 212export const isNoisePath = path => String ( path ). split ( '/' ). slice ( 0 , - 1 ). some ( seg => NOISE_DIR . test ( seg )); 213const NOISE_LISTED = 5 ; 214 215/** Order in the Compare view: the page or document that was made first, other readable work next, pictures, then everything else, then housekeeping. */ 216function rankOf ( entry ) { 217if ( entry . noise ) return 4 ; 218const ext = String ( entry . path ). split ( '.' ). pop (). toLowerCase (); 219if ( entry . unreadable ) return 3 ; 220if ( ext === 'html' || ext === 'htm' ) return 0 ; 221if ( entry . image ) return 2 ; 222return 1 ; 223} 224 225export function diffRun ( record ) { 226// A kept checkpoint is the revision; when nothing was kept (the checks could not decide) the person looks at the last attempt. 227const { baseRoot, updatedRoot, useAttempt, last} = runRoots ( record ); 228if ( ! baseRoot || ! updatedRoot ) return { files :[], applyAttempt :null , more :0 }; 229const paths = [ ...new Set ([ ...walkFiles ( baseRoot ), ...walkFiles ( updatedRoot )])]. sort (); 230const found = []; 231for ( const path of paths ) { 232const noise = isNoisePath ( path ); 233// Housekeeping is compared as bytes only (never read as text): a browser profile can hold thousands of files. 234if ( noise ) { 235const A = join ( baseRoot , path ), B = join ( updatedRoot , path ); 236const inA = existsSync ( A ), inB = existsSync ( B ); 237let differs = ! inA || ! inB ; 238if ( ! differs ) { try { differs = statSync ( A ). size !== statSync ( B ). size || ! readFileSync ( A ). equals ( readFileSync ( B )); } catch { differs = true ; } } 239if ( differs ) found . push ({ path, status :! inA ?'added' :! inB ?'removed' :'changed' , unreadable :true , noise :true }); 240continue ; 241} 242const a = readText ( join ( baseRoot , path )), b = readText ( join ( updatedRoot , path )); 243const status = a . missing ?'added' :b . missing ?'removed' :null ; 244const same = ! status && a . text !== undefined && a . text === b . text ; 245if ( same ) continue ; 246// A file too big to read as text is the same file when its bytes are the same: it must not show up as a change. 247if ( ! status && ( a . big || b . big ) && sameBytes ( join ( baseRoot , path ), join ( updatedRoot , path ))) continue ; 248if ( imageTypeOf ( path )) { 249// A picture is compared as bytes and shown from the file itself, never read as text. 250let differs = true ; 251try { differs = a . missing || b . missing || ! readFileSync ( join ( baseRoot , path )). equals ( readFileSync ( join ( updatedRoot , path ))); } catch { /* treat as changed */ } 252if ( ! differs ) continue ; 253found . push ({ path, status :status ?? 'changed' , image :true }); 254continue ; 255} 256if ( ! status && ! a . text && ! b . text && ! a . big && ! b . big ) { 257// Both binary: compare sizes only. 258try { if ( statSync ( join ( baseRoot , path )). size === statSync ( join ( updatedRoot , path )). size && readFileSync ( join ( baseRoot , path )). equals ( readFileSync ( join ( updatedRoot , path )))) continue ; } catch { /* treat as changed */ } 259} 260const entry = { path, status :status ?? 'changed' }; 261const textual = ( a . text !== undefined || a . missing ) && ( b . text !== undefined || b . missing ); 262if ( textual ) entry . _text = { original :a . text ?? '' , updated :b . text ?? '' }; 263else entry . unreadable = true ; 264found . push ( entry ); 265} 266// Only housekeeping changed (a cache, a browser profile): the assistant changed nothing the person asked about. 267if ( found . length && found . every ( e => e . noise )) return { files :[], applyAttempt :useAttempt ?( last ?. index ?? null ) :null , more :0 , housekeeping :found . length }; 268found . sort (( x , y ) => rankOf ( x ) - rankOf ( y ) || ( x . path < y . path ?- 1 :x . path > y . path ?1 :0 )); 269const files = []; 270let withText = 0 , more = 0 , noiseListed = 0 ; 271for ( const entry of found ) { 272if ( entry . noise && noiseListed >= NOISE_LISTED ) { more += 1 ; continue ; } 273if ( files . length >= MAX_LISTED ) { more += 1 ; continue ; } 274if ( entry . noise ) noiseListed += 1 ; 275const { _text, ...rest } = entry ; 276if ( _text ) { if ( withText < MAX_WITH_TEXT ) { rest . original = _text . original ; rest . updated = _text . updated ; withText += 1 ; } else rest . unreadable = true ; } 277files . push ( rest ); 278} 279return { files, applyAttempt :useAttempt ?( last ?. index ?? null ) :null , more}; 280} 281 282/** 283* Run one `strata timeskip …` command and collect its result. 284* 285* The command is given a bounded time. A Time-skip run can legitimately take many minutes (each 286* attempt is an agent turn), so the default bound is generous, and exceeding it is reported as a 287* timeout rather than as success. 288*/ 289export function createTimeSkip ({ repoRoot, python, pythonArgs= [], timeoutMs= 30 * 60 * 1000 , env= process . env } = {}) { 290const cli = join ( repoRoot , 'strata.py' ); 291 292/** Runs this host started and is still driving. A run that is not terminal and not in here died with its host. */ 293const live = new Map (); 294/** id -> promise that settles when the job's process has ended. */ 295const endedOf = new Map (); 296/** Runs the person stopped: their folders are deleted, so the answer to "what became of it" is kept here (until the host restarts). */ 297const stopped = new Set (); 298const withLive = summary => ( summary && ! TERMINAL . has ( summary . phase ) && ! live . has ( summary . id ) ?{ ...summary , phase :'interrupted' } :summary ); 299 300function runCli ( args , { signal} = {}) { 301return new Promise (( resolve ) => { 302const root = stateDir ( env ); 303const child = spawn ( python , [ ...pythonArgs , cli , ...args , '--output' , 'json' ], { 304cwd :repoRoot , 305windowsHide :true , 306env :{ ...env , PYTHONUTF8 :'1' , PYTHONIOENCODING :'utf-8' , STRATA_TIMESKIP_DIR :root }, 307stdio :[ 'ignore' , 'pipe' , 'pipe' ], 308}); 309let stdout = '' ; 310let stderr = '' ; 311let timedOut = false ; 312const timer = setTimeout (() => { 313timedOut = true ; 314try { 315child . kill ( 'SIGTERM' ); 316} catch { 317/* already gone */ 318} 319}, timeoutMs ); 320const onAbort = () => { 321try { 322child . kill ( 'SIGTERM' ); 323} catch { 324/* already gone */ 325} 326}; 327signal ?. addEventListener ( 'abort' , onAbort , { once :true }); 328 329child . stdout . on ( 'data' , ( b ) => { 330stdout += b . toString (); 331}); 332child . stderr . on ( 'data' , ( b ) => { 333stderr += b . toString (); 334}); 335child . on ( 'error' , ( e ) => { 336clearTimeout ( timer ); 337signal ?. removeEventListener ( 'abort' , onAbort ); 338resolve ({ ok :false , code :null , error :`could not start the Time-skip command: ${ e . message } ` }); 339}); 340child . on ( 'close' , ( code ) => { 341clearTimeout ( timer ); 342signal ?. removeEventListener ( 'abort' , onAbort ); 343if ( timedOut ) { 344resolve ({ ok :false , code, error :`the Time-skip command did not finish within ${ Math . round ( timeoutMs / 1000 )} s` }); 345return ; 346} 347// The CLI's machine envelope is one JSON object on stdout; anything else is a defect worth 348// surfacing rather than guessing at. 349let parsed = null ; 350try { 351parsed = JSON . parse ( stdout . trim (). split ( '\n' ). filter ( Boolean ). pop () ?? '' ); 352} catch { 353parsed = null ; 354} 355if ( ! parsed ) { 356resolve ({ ok :false , code, error :stderr . trim () || stdout . trim () || `the command exited ${ code } with no JSON` }); 357return ; 358} 359resolve ({ ok :Boolean ( parsed . ok ), code, envelope :parsed , stderr :stderr . trim () }); 360}); 361}); 362} 363 364return { 365stateDir :() => stateDir ( env ), 366 367/** Every recorded run, newest first. */ 368list :() => listRuns ( stateDir ( env )). map ( withLive ), 369 370/** One run's durable record, or null. */ 371status :( id ) => { 372if ( ! /^ [ 0 - 9a - f ]{ 8 , 64 } $ / . test ( String ( id ?? '' ))) return null ; 373if ( stopped . has ( id )) return { id, phase :'cancelled' , workspace :null , prompt :null , startedAt :null , finishedAt :null , attempts :[], checkpoints :[], selectedCheckpoint :null , decision :null , needsUserReview :false , error :null }; 374const run = readRun ( stateDir ( env ), id ); 375return run ?withLive ( summarise ( run )) :null ; 376}, 377 378/** The changed files of a run (saved original against the revision), for the Compare view. */ 379files :id => { 380if ( ! /^ [ 0 - 9a - f ]{ 8 , 64 } $ / . test ( String ( id ?? '' ))) return null ; 381const run = readRun ( stateDir ( env ), id ); 382return run ?diffRun ( run ) :null ; 383}, 384 385/** One picture of a run (original or updated), for the Compare view: { path, type } or null. */ 386image :( id , relPath , version ) => { 387if ( ! /^ [ 0 - 9a - f ]{ 8 , 64 } $ / . test ( String ( id ?? '' ))) return null ; 388const run = readRun ( stateDir ( env ), id ); 389const full = run ?runImagePath ( run , relPath , version ) :null ; 390return full ?{ path :full , type :imageTypeOf ( relPath ) } :null ; 391}, 392 393/** Settles when the job's process has ended (immediately for a run this host is not driving). */ 394whenEnded :id => endedOf . get ( id ) ?? Promise . resolve (), 395 396/** 397* Stop a run and clean up after it: the job and everything it started are ended (the whole process tree), and the run's folder, which 398* holds the copies of the person's files, is deleted. The person's own files were never touched by the run. Afterwards the run reads as 399* cancelled. Returns false for an id that is not a run. 400*/ 401async stop ( id ) { 402if ( ! /^ [ 0 - 9a - f ]{ 8 , 64 } $ / . test ( String ( id ?? '' ))) return false ; 403const folder = join ( stateDir ( env ), id ); 404if ( ! live . has ( id ) && ! existsSync ( folder ) && ! stopped . has ( id )) return false ; 405stopped . add ( id ); 406const child = live . get ( id ); 407if ( child ) killTree ( child ); 408await Promise . race ([ endedOf . get ( id ) ?? Promise . resolve (), new Promise ( r => setTimeout ( r , 8000 ))]); 409for ( let i = 0 ; i < 6 && existsSync ( folder ); i ++ ) { 410try { rmSync ( folder , { recursive :true , force :true , maxRetries :5 , retryDelay :200 }); } catch { await new Promise ( r => setTimeout ( r , 400 )); } 411} 412return true ; 413}, 414 415 416/** 417* Start a run. Returns as soon as the job has been *accepted*; the caller follows the run id. 418* 419* Note the deliberate absence of a `reviseCommand` argument: a revision is performed by the 420* Harness through `integrations/harness/revise_once.py`, and letting an HTTP caller supply an 421* arbitrary shell command would hand a remote caller command execution. The path is configured, 422* not requested. 423*/ 424async start ({ workspace, prompt, attempts= 2 , reviseCommand= null , signal} = {}) { 425if ( ! workspace || typeof workspace !== 'string' ) { 426return { ok :false , code :2 , error :'workspace is required' }; 427} 428if ( ! prompt || typeof prompt !== 'string' ) { 429return { ok :false , code :2 , error :'prompt is required' }; 430} 431const args = [ 'timeskip' , 'run' , '--workspace' , workspace , '--prompt' , prompt , 432'--attempts' , String ( Math . max ( 0 , Math . min ( 10 , Number ( attempts ) || 0 )))]; 433if ( reviseCommand ) args . push ( '--revise-command' , reviseCommand ); 434const result = await runCli ( args , { signal}); 435if ( ! result . ok ) return { ok :false , code :result . code ?? 6 , error :result . error ?? result . stderr }; 436const run = result . envelope ?. run ; 437return run ?{ ok :true , run :summarise ( run ) } :{ ok :false , code :6 , error :'the job reported success but wrote no run record' }; 438}, 439 440/** 441* Start a run and return as soon as its record exists; the job goes on without the caller waiting. 442* The caller follows the run id with `status`. A command that ends before any record appears is an error, in the command's words. 443*/ 444async startDetached ({ workspace, prompt, attempts= 1 , reviseCommand= null , extraEnv= {} } = {}) { 445if ( ! workspace || typeof workspace !== 'string' ) return { ok :false , code :2 , error :'workspace is required' }; 446if ( ! prompt || typeof prompt !== 'string' ) return { ok :false , code :2 , error :'prompt is required' }; 447const root = stateDir ( env ); 448const before = new Set ( existsSync ( root ) ?readdirSync ( root ) :[]); 449const args = [ 'timeskip' , 'run' , '--workspace' , workspace , '--prompt' , prompt , 450'--attempts' , String ( Math . max ( 0 , Math . min ( 10 , Number ( attempts ) || 0 ))), '--output' , 'json' ]; 451if ( reviseCommand ) args . push ( '--revise-command' , reviseCommand ); 452const child = spawn ( python , [ ...pythonArgs , cli , ...args ], { 453cwd :repoRoot , windowsHide :true , detached :ownGroup (), env :{ ...env , PYTHONUTF8 :'1' , PYTHONIOENCODING :'utf-8' , ...extraEnv , STRATA_TIMESKIP_DIR :root }, stdio :[ 'ignore' , 'pipe' , 'pipe' ], 454}); 455let out = '' , err = '' , closed = null ; 456child . stdout . on ( 'data' , b => { out += b . toString (); }); 457child . stderr . on ( 'data' , b => { err += b . toString (); }); 458const ended = new Promise ( resolve => { 459child . on ( 'error' , e => { closed = { code :null , error :`could not start the Time-skip command: ${ e . message } ` }; resolve (); }); 460child . on ( 'close' , code => { closed = { code}; resolve (); }); 461}); 462const deadline = Date . now () + 20_000 ; 463let id = null ; 464while ( ! id && Date . now () < deadline ) { 465if ( existsSync ( root )) { 466for ( const name of readdirSync ( root )) { 467if ( before . has ( name )) continue ; 468const run = readRun ( root , name ); 469if ( run && run . prompt === prompt ) { id = name ; break ; } 470} 471} 472if ( id || closed ) break ; 473await new Promise ( r => setTimeout ( r , 100 )); 474} 475if ( ! id ) { 476if ( ! closed ) { try { child . kill ( 'SIGTERM' ); } catch { /* gone */ } return { ok :false , code :6 , error :'the Time-skip job did not start in time' }; } 477let message = closed . error ?? '' ; 478try { const parsed = JSON . parse ( out . trim (). split ( '\n' ). filter ( Boolean ). pop () ?? '' ); message = message || parsed ?. error ?. message || parsed ?. error || '' ; } catch { /* not JSON */ } 479return { ok :false , code :closed . code ?? 6 , error :String ( message || err . trim () || out . trim () || 'the Time-skip command ended without a run' ). slice ( 0 , 600 ) }; 480} 481live . set ( id , child ); 482endedOf . set ( id , ended ); 483void ended . then (() => live . delete ( id )); 484return { ok :true , run :withLive ( summarise ( readRun ( root , id ))) }; 485}, 486 487/** Apply the retained result, or preview it. Refuses when the destination changed. */ 488async apply ({ id, workspace= null , dryRun= false , restore= false , attempt= null , signal} = {}) { 489if ( ! /^ [ 0 - 9a - f ]{ 8 , 64 } $ / . test ( String ( id ?? '' ))) { 490return { ok :false , code :2 , error :'a run id is required' }; 491} 492const args = [ 'timeskip' , 'apply' , id ]; 493if ( workspace ) args . push ( '--workspace' , workspace ); 494if ( dryRun ) args . push ( '--dry-run' ); 495if ( restore ) args . push ( '--restore' ); 496if ( attempt !== null && attempt !== undefined ) args . push ( '--attempt' , String ( Math . max ( 1 , Math . floor ( Number ( attempt )) || 1 ))); 497const result = await runCli ( args , { signal}); 498if ( ! result . ok ) { 499// Exit 6 is the documented "refused / uncertain" code, which is how a concurrent user edit 500// arrives here. It is a normal outcome, not an internal error. 501return { ok :false , code :result . code ?? 6 , conflict :result . code === 6 , 502error :result . error ?? result . stderr }; 503} 504return { ok :true , apply :result . envelope ?. apply ?? result . envelope ?. restore ?? null }; 505}, 506}; 507}