okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
1/** 2* What a turn made: files (deliverables) and compact activity lines. 3* 4* DeliverableTracker. Takes a quick look at the chat's folder when a turn starts, then reports every file the turn created or changed as a 5* `deliverable` frame: { path (inside the folder), abs, name, type, status, size, lines, added, removed }. A file the agent wrote with its 6* file tools is reported as soon as the tool is done; files made some other way (a script, a build) are found by a sweep when the turn ends. 7* 8* ActivityGroups. Consecutive tool cards between two pieces of assistant text are one group, shown by the page as one compact line the way 9* Claude does ("Ran 2 commands, read a file +225 -0"). The group frame carries the counts per kind, the files and the diff stat, and is 10* sent again as it grows (same id) and closed when text follows. 11*/ 12 13import { readdirSync , readFileSync , statSync } from 'node:fs' ; 14import { basename , dirname , extname , isAbsolute , join , relative , resolve , sep } from 'node:path' ; 15 16const SKIP_DIR = / ^ (?: \. | node_modules$ | __pycache__$ | \$ ) / ; 17const MAX_FILES = 4000 , MAX_TEXT = 200_000 , MAX_TOTAL = 24_000_000 , BUDGET_MS = 1500 ; 18 19const TYPES = { 20html :[ 'html' , 'htm' ], markdown :[ 'md' , 'markdown' ], [ 'pdf' ], csv :[ 'csv' , 'tsv' ], 21image :[ 'png' , 'jpg' , 'jpeg' , 'gif' , 'webp' , 'svg' , 'bmp' , 'ico' ], 22code :[ 'js' , 'mjs' , 'cjs' , 'ts' , 'tsx' , 'jsx' , 'py' , 'rs' , 'go' , 'java' , 'c' , 'h' , 'cpp' , 'cs' , 'sh' , 'ps1' , 'bat' , 'css' , 'json' , 'yaml' , 'yml' , 'toml' , 'xml' , 'sql' , 'rb' , 'php' , 'swift' , 'kt' ], 23text :[ 'txt' , 'log' , 'ini' , 'cfg' ], 24}; 25export function fileType ( path ) { 26const ext = extname ( String ( path )). slice ( 1 ). toLowerCase (); 27for ( const [ type , list ] of Object . entries ( TYPES )) if ( list . includes ( ext )) return type ; 28return 'other' ; 29} 30const isTextual = type => [ 'html' , 'markdown' , 'csv' , 'code' , 'text' ]. includes ( type ); 31 32const linesOf = text => ( text === '' ?[] :text . replace ( / \r\n / g , '\n' ). replace ( / \n$ / , '' ). split ( '\n' )); 33/** Lines added and removed between two versions (a count of lines that are in one and not the other; order is not compared). */ 34export function lineDelta ( before , after ) { 35const bag = new Map (); 36for ( const l of before ) bag . set ( l , ( bag . get ( l ) ?? 0 ) + 1 ); 37let added = 0 ; 38for ( const l of after ) { const n = bag . get ( l ) ?? 0 ; if ( n > 0 ) bag . set ( l , n - 1 ); else added += 1 ; } 39let removed = 0 ; for ( const n of bag . values ()) removed += n ; 40return { added, removed}; 41} 42 43/** A file made or changed this long before the turn started still counts (clock rounding on some file systems). */ 44const START_SLACK_MS = 2000 ; 45const same = process . platform === 'win32' || process . platform === 'darwin' ?p => p . toLowerCase () :p => p ; 46/** True when `child` is `parent` or inside it. */ 47export function isWithin ( parent , child ) { 48const rel = relative ( same ( resolve ( parent )), same ( resolve ( child ))); 49return rel === '' || ( ! rel . startsWith ( '..' ) && ! isAbsolute ( rel )); 50} 51 52/** 53* Who made which file when several chats work in one folder (#5008). A folder chosen for two chats is shared on purpose, but a 54* chat's list of "files this turn made" is private to that turn: a file another chat wrote must not be shown as this chat's work. 55* One registry is shared by the turns of a host. A turn `begin`s on its folder, `claim`s the files its own file tools wrote, and 56* `end`s. Turns that were running at the same time in the same folder are `overlapped`: for them the end-of-turn sweep reports only 57* files nobody else claimed AND that no overlapping turn could have written; since a script's output cannot be told apart, it is 58* left out for an overlapped turn rather than given to the wrong chat. 59*/ 60export class FolderClaims { 61 #active= new Map (); // folder key -> Set(owner) 62 #overlap= new Map (); // folder key + owner -> true 63 #claims= new Map (); // folder key -> Map(rel path -> owner) 64 #key( root ) { return same ( resolve ( String ( root ))); } 65begin ( root , owner ) { 66const k = this . #key( root ); 67const set = this . #active. get ( k ) ?? new Set (); 68const others = [ ...set ]. filter ( o => o !== owner ); 69if ( others . length ) { for ( const o of [ ...others , owner ]) this . #overlap. set ( ` ${ k } | ${ o } ` , true ); } 70set . add ( owner ); this . #active. set ( k , set ); 71} 72end ( root , owner ) { 73const k = this . #key( root ); 74const set = this . #active. get ( k ); 75if ( ! set ) return ; 76set . delete ( owner ); this . #overlap. delete ( ` ${ k } | ${ owner } ` ); 77if ( ! set . size ) { this . #active. delete ( k ); this . #claims. delete ( k ); } 78} 79claim ( root , rel , owner ) { 80const k = this . #key( root ); 81if ( ! this . #active. has ( k )) return ; 82const m = this . #claims. get ( k ) ?? new Map (); 83m . set ( rel , owner ); this . #claims. set ( k , m ); 84} 85ownerOf ( root , rel ) { return this . #claims. get ( this . #key( root ))?. get ( rel ) ?? null ; } 86/** True when another turn was running in this folder at any time during this owner's turn. */ 87overlapped ( root , owner ) { return this . #overlap. get ( ` ${ this . #key ( root )} | ${ owner } ` ) === true ; } 88} 89 90export class DeliverableTracker { 91/** 92* `exclude`: folders that are never searched when they lie inside the chat's folder (the app, the engine and its components, AppData, 93* temp). `forbid`: folders the chat's own folder must not be, or be inside (the app, the engine and its components): then nothing is 94* tracked at all. The turn only reports files the turn itself wrote: an explicit file-tool call, or (for scripts) a file whose modified 95* or creation time is after the turn started. 96*/ 97constructor ( root , { now= Date . now , exclude= [], forbid= [], claims= null , owner= null } = {}) { 98this . root = root ?resolve ( root ) :null ; 99this . claims = claims ; this . owner = owner ; 100this . now = now ; 101if ( this . root && forbid . filter ( Boolean ). some ( p => isWithin ( p , this . root ))) this . root = null ; 102// only the folders that lie inside the chat's folder matter for the search 103this . exclude = this . root ?[ ...exclude , ...forbid ]. filter ( Boolean ). map ( p => resolve ( p )). filter ( p => p !== this . root && isWithin ( this . root , p )) :[]; 104this . startedAt = Date . now (); 105this . before = new Map (); // rel path -> { size, mtimeMs, lines|null } 106this . sent = new Map (); // rel path -> signature of what was last reported 107this . truncated = false ; 108} 109 110 #snapshotting= false ; 111/** A folder inside the chat's folder that is never searched. */ 112 #excluded( full ) { return this . exclude . some ( p => isWithin ( p , full )); } 113 114 #walk( fn ) { 115if ( ! this . root ) return ; 116const t0 = this . now (); let count = 0 ; 117const walk = dir => { 118let entries ; try { entries = readdirSync ( dir , { withFileTypes :true }); } catch { return ; } 119for ( const e of entries ) { 120if ( count >= MAX_FILES || this . now () - t0 > BUDGET_MS ) { this . truncated = true ; if ( this . #snapshotting) this . snapshotTruncated = true ; return ; } 121const full = join ( dir , e . name ); 122if ( e . isDirectory ()) { if ( ! SKIP_DIR . test ( e . name ) && ! this . #excluded( full )) walk ( full ); } 123else if ( e . isFile ()) { count += 1 ; fn ( full ); } 124} 125}; 126walk ( this . root ); 127} 128 129 #read( full , size , type ) { 130if ( ! isTextual ( type ) || size > MAX_TEXT || this . bytes > MAX_TOTAL ) return null ; 131try { const buf = readFileSync ( full ); if ( buf . subarray ( 0 , 2048 ). includes ( 0 )) return null ; this . bytes += buf . length ; return linesOf ( buf . toString ( 'utf8' )); } catch { return null ; } 132} 133 134/** Remember what the folder holds now. */ 135snapshot () { 136this . before . clear (); this . bytes = 0 ; this . startedAt = Date . now (); this . snapshotTruncated = false ; this . #snapshotting= true ; 137this . #walk( full => { 138let st ; try { st = statSync ( full ); } catch { return ; } 139const rel = relative ( this . root , full ). split ( sep ). join ( '/' ); 140this . before . set ( rel , { size :st . size , mtimeMs :st . mtimeMs , lines :this . #read( full , st . size , fileType ( rel )) }); 141}); 142this . #snapshotting= false ; 143} 144 145/** The deliverable for one path now, compared with the snapshot (and the last report), or null when nothing changed. */ 146check ( rawPath , { explicit= false } = {}) { 147if ( ! this . root ) return null ; 148const full = resolve ( this . root , String ( rawPath ?? '' )); 149const rel = relative ( this . root , full ). split ( sep ). join ( '/' ); 150if ( ! rel || rel . startsWith ( '..' ) || isAbsolute ( rel ) || rel . split ( '/' ). some ( seg => SKIP_DIR . test ( seg )) || this . #excluded( dirname ( full ))) return null ; 151let st ; try { st = statSync ( full ); } catch { return null ; } 152if ( ! st . isFile ()) return null ; 153// A file this chat's own file tool wrote is this chat's, whoever else works in the folder (#5008). 154if ( explicit && this . claims && this . owner ) this . claims . claim ( this . root , rel , this . owner ); 155const old = this . before . get ( rel ); 156if ( old && old . size === st . size && old . mtimeMs === st . mtimeMs ) return null ; 157const type = fileType ( rel ); 158this . bytes = this . bytes ?? 0 ; 159const lines = this . #read( full , st . size , type ); 160let added = null , removed = null ; 161if ( lines ) { const d = lineDelta ( old ?. lines ?? [], lines ); added = d . added ; removed = d . removed ; if ( old && ! old . lines ) { added = null ; removed = null ; } } 162const sig = ` ${ st . size } : ${ st . mtimeMs } ` ; 163if ( this . sent . get ( rel ) === sig ) return null ; 164this . sent . set ( rel , sig ); 165// the next change to this file is measured against what was just reported 166this . before . set ( rel , { size :st . size , mtimeMs :st . mtimeMs , lines}); 167return { type :'deliverable' , path :rel , abs :full , name :basename ( rel ), kind :type , status :old ?'changed' :'created' , size :st . size , lines :lines ?lines . length :null , added, removed}; 168} 169 170/** 171* Files the tools did not announce (a script wrote them): what was made or changed since the snapshot and not yet reported. A file only 172* counts when its modified or creation time is after the turn started, so a folder the snapshot could not finish (it stops after 173* MAX_FILES files or BUDGET_MS) never turns the rest of the folder into "new files" (the 308 CUDA headers of the QA report). 174*/ 175sweep () { 176const out = []; 177const since = this . startedAt - START_SLACK_MS ; 178this . #walk( full => { 179let st ; try { st = statSync ( full ); } catch { return ; } 180// modified during the turn; or created during it (a copy that kept its old modified time), which is only certain when the first look saw the whole folder 181const fresh = st . mtimeMs >= since || ( ! this . snapshotTruncated && ( st . birthtimeMs || 0 ) >= since ); 182if ( ! fresh ) return ; 183const rel = relative ( this . root , full ). split ( sep ). join ( '/' ); 184if ( this . claims && this . owner ) { 185// Another chat's file tool wrote it: not ours. Written by a script while another chat was working in the same folder: nobody can say whose it is. 186const by = this . claims . ownerOf ( this . root , rel ); 187if ( by && by !== this . owner ) return ; 188if ( ! by && this . claims . overlapped ( this . root , this . owner )) return ; 189} 190const d = this . check ( rel ); if ( d ) out . push ( d ); 191}); 192return out ; 193} 194} 195 196const KIND_OF = name => { 197if ( name === 'pwsh' || name === 'bash' ) return 'command' ; 198if ( name === 'read' || name === 'read_image' ) return 'read' ; 199if ( name === 'write' || name === 'edit' ) return 'edit' ; 200if ( name === 'glob' || name === 'grep' ) return 'search' ; 201if ( name === 'web_fetch' || name === 'web_search' ) return 'web' ; 202if ( String ( name ). startsWith ( 'mcp__browser__' )) return 'browser' ; 203if ( name === 'subagent' ) return 'helper' ; 204return 'other' ; 205}; 206const NOUN = { command :[ 'command' , 'commands' ], read :[ 'file' , 'files' ], edit :[ 'file' , 'files' ], search :[ 'search' , 'searches' ], web :[ 'web page' , 'web pages' ], browser :[ 'browser step' , 'browser steps' ], helper :[ 'helper' , 'helpers' ], other :[ 'tool' , 'tools' ] }; 207const VERB = { command :[ 'Ran' , 'ran' ], read :[ 'Read' , 'read' ], edit :[ 'Edited' , 'edited' ], search :[ 'Searched' , 'searched' ], web :[ 'Looked up' , 'looked up' ], browser :[ 'Used the browser for' , 'used the browser for' ], helper :[ 'Started' , 'started' ], other :[ 'Used' , 'used' ] }; 208const ORDER = [ 'command' , 'read' , 'edit' , 'search' , 'web' , 'browser' , 'helper' , 'other' ]; 209const count = ( n , [ one , many ]) => ` ${ n === 1 ? 'a' : n } ${ n === 1 ? one : many } ` ; 210 211/** "Ran 2 commands, read a file +225 -0" */ 212export function groupLine ( counts , added , removed ) { 213const parts = ORDER . filter ( k => counts [ k ] > 0 ); 214if ( ! parts . length ) return '' ; 215const text = parts . map (( k , i ) => ` ${ VERB [ k ][ i === 0 ? 0 : 1 ]} ${ count ( counts [ k ], NOUN [ k ])} ` ). join ( ', ' ); 216return ( added || removed ) ?` ${ text } + ${ added ?? 0 } − ${ removed ?? 0 } ` :text ; 217} 218 219export class ActivityGroups { 220constructor ({ emit, tracker= null }) { this . emit = emit ; this . tracker = tracker ; this . seq = 0 ; this . current = null ; this . seen = new Set (); } 221 #open() { if ( ! this . current ) this . current = { id :`g ${ ++ this . seq } ` , counts :{}, files :new Map (), added :0 , removed :0 , tools :0 }; return this . current ; } 222 #send( closed ) { 223const g = this . current ; if ( ! g ) return ; 224const files = [ ...g . files . values ()]; 225this . emit ({ type :'activity-group' , id :g . id , closed, counts :{ ...g . counts }, files, added :g . added , removed :g . removed , tools :g . tools , line :groupLine ( g . counts , g . added , g . removed ) }); 226} 227/** A tool card frame (every state change). Counted once, when it is done or has failed. */ 228card ( tool , deliverable = null ) { 229if ( ! tool || ! [ 'done' , 'error' , 'denied' ]. includes ( tool . state )) return ; 230if ( this . seen . has ( tool . id )) { if ( deliverable ) this . #file( deliverable , true ); return ; } 231this . seen . add ( tool . id ); 232if ( tool . state === 'denied' ) return ; 233const g = this . #open(); const kind = KIND_OF ( tool . name ); 234g . counts [ kind ] = ( g . counts [ kind ] ?? 0 ) + 1 ; g . tools += 1 ; 235if ( deliverable ) this . #file( deliverable , false ); 236this . #send( false ); 237} 238 #file( d , resend ) { 239const g = this . #open(); const prev = g . files . get ( d . path ); 240if ( prev ) { g . added += ( d . added ?? 0 ) - ( prev . added ?? 0 ); g . removed += ( d . removed ?? 0 ) - ( prev . removed ?? 0 ); } else { g . added += d . added ?? 0 ; g . removed += d . removed ?? 0 ; } 241g . files . set ( d . path , { path :d . path , name :d . name , kind :d . kind , status :d . status , added :d . added , removed :d . removed }); 242if ( resend ) this . #send( false ); 243} 244/** A file a script made: part of the group it was made in, without counting a tool. */ 245addFile ( d ) { this . #file( d , true ); } 246/** Assistant text ends the group. */ 247text () { if ( this . current ) { this . #send( true ); this . current = null ; } } 248end () { this . text (); } 249}