🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
perf(console): incremental transcript parsing, kit-seq runner, tsc clean for specs (ADR-473)
ruvb531aa927974
diff --git a/plugins/ruflo-console/hooks/data/wf-activity.ts b/plugins/ruflo-console/hooks/data/wf-activity.tsindex 41764346b6..f998839d9e 100644--- a/plugins/ruflo-console/hooks/data/wf-activity.ts+++ b/plugins/ruflo-console/hooks/data/wf-activity.ts@@ -70,11 +70,11 @@ export type Parsed = {const asRecord = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)const SUMMARY_KEYS = ['command', 'file_path', 'notebook_path', 'path', 'pattern', 'url', 'query', 'description', 'prompt', 'skill', 'subject'] as const-const READ_TOOLS = new Set(['Read'])-const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'NotebookEdit'])-const WRITE_TOOLS = new Set(['Write'])+export const READ_TOOLS = new Set(['Read'])+export const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'NotebookEdit'])+export const WRITE_TOOLS = new Set(['Write'])-function summaryOf(input: unknown): string {+export function summaryOf(input: unknown): string {const record = asRecord(input)if (record === null) return typeof input === 'string' ? cleanLine(input) : ''@@ -84,7 +84,7 @@ function summaryOf(input: unknown): string {return ''}-function pathOf(input: unknown): string | undefined {+export function pathOf(input: unknown): string | undefined {const record = asRecord(input)const value = record?.file_path ?? record?.notebook_path@@ -92,7 +92,7 @@ function pathOf(input: unknown): string | undefined {}/** A tool result's text: a string, or the text blocks of an array (an image is named, not drawn). */-function resultText(content: unknown): string {+export function resultText(content: unknown): string {if (typeof content === 'string') return contentif (!Array.isArray(content)) return ''@@ -106,7 +106,7 @@ function resultText(content: unknown): string {.join('\n')}-const stamp = (line: Record<string, unknown>): number | undefined => {+export const stamp = (line: Record<string, unknown>): number | undefined => {const at = typeof line.timestamp === 'string' ? Date.parse(line.timestamp) : Number.NaNreturn Number.isFinite(at) ? at : undefineddiff --git a/plugins/ruflo-console/hooks/data/wf-drill-io.ts b/plugins/ruflo-console/hooks/data/wf-drill-io.tsindex f6709cd6df..9b4d8de804 100644--- a/plugins/ruflo-console/hooks/data/wf-drill-io.ts+++ b/plugins/ruflo-console/hooks/data/wf-drill-io.ts@@ -11,7 +11,8 @@* A refusal, a missing file or a file too large is a stated reason, never an empty success.*/import { readBounded, type ReadCache } from './files'-import { cleanLine, cleanPath, journalResult, parseActivity, type Capped, type Parsed } from './wf-activity'+import { cleanLine, cleanPath, journalResult, type Capped, type Parsed } from './wf-activity'+import { activityOf, parsedStats, PARSED_BUDGET_CHARS, resetStore } from './wf-incr-store'import { TAIL_BYTES, TRANSCRIPT_CAP, type WorkflowFs } from './workflows-read'import type { WfAgent, WfRun } from './workflows'@@ -36,9 +37,7 @@ export const isBound = (): boolean => bound !== null/** For tests: forgets the binding and everything held. */export function resetDrillIo(): void {bound = null- parsedMemo.clear()- parsedChars = 0- parseCount = 0+ resetStore()tails.clear()notes.clear()results.clear()@@ -74,40 +73,16 @@ const hold = <V>(map: Map<string, V>, key: string, value: V, max = MAX_HELD): voexport const noteOf = (key: string): Note | undefined => notes.get(key)-const parsedMemo = new Map<string, { src: string; isTail: boolean; parsed: Parsed }>()/**- * The parse memo is bounded by the text it holds, not by a count of files: a live project has 6 runs x 60 agents, and a memo of 24 entries was- * walked past by every frame that asked for all of them (the search panel does), so each draw parsed ~340 transcripts again (bench-workflows.mjs:- * 66 ms a frame). A parsed transcript is no bigger than its text, so this budget caps what the memo can keep; the oldest go first.+ * The parse memo is bounded by the text it holds, not by a count of files (data/wf-incr-store.ts): a live project has 6 runs x 60 agents, and a memo+ * of 24 entries was walked past by every frame that asked for all of them (the search panel does), so each draw parsed ~340 transcripts again+ * (bench-workflows.mjs: 66 ms a frame). A transcript that grew is parsed from where its last parse ended, not from its first line (ADR-473).*/-export const PARSED_BUDGET_CHARS = 24_000_000-const PARSED_MAX_ENTRIES = 1024-let parsedChars = 0-let parseCount = 0+export { parsedStats, PARSED_BUDGET_CHARS }-/** What the parse memo holds and how many parses it has done: what a test or a bench reads to prove a frame parsed nothing. */-export const parsedStats = (): { entries: number; chars: number; parses: number } => ({ entries: parsedMemo.size, chars: parsedChars, parses: parseCount })+const tails = new Map<string, { text: string; size: number; tag: string }>()-function holdParsed(path: string, entry: { src: string; isTail: boolean; parsed: Parsed }): void {- const old = parsedMemo.get(path)-- if (old !== undefined) parsedChars -= old.src.length-- parsedMemo.delete(path)- parsedMemo.set(path, entry)- parsedChars += entry.src.length-- for (const [key, held] of parsedMemo) {- if (key === path || (parsedChars <= PARSED_BUDGET_CHARS && parsedMemo.size <= PARSED_MAX_ENTRIES)) break-- parsedMemo.delete(key)- parsedChars -= held.src.length- }-}--const tails = new Map<string, { text: string; size: number }>()--export type Text = { text: string; isTail: boolean }+export type Text = { text: string; isTail: boolean; /** Which version of the file a tail is (size and mtime): two windows can read the same at different places. */ tag: string }/** The transcript text in memory for an agent: the console's read cache (whole files, handed in by the caller), else a tail this module read; null where neither has it. */export function textOf(cache: ReadCache, agent: WfAgent): Text | null {@@ -117,31 +92,21 @@ export function textOf(cache: ReadCache, agent: WfAgent): Text | null {const held = cache.get(path)- if (held !== undefined && 'text' in held) return { text: held.text, isTail: false }+ if (held !== undefined && 'text' in held) return { text: held.text, isTail: false, tag: '' }const tail = tails.get(path)- return tail === undefined ? null : { text: tail.text, isTail: true }+ return tail === undefined ? null : { text: tail.text, isTail: true, tag: tail.tag }}-/** The agent's transcript parsed, memoised by the text itself so an unchanged file is parsed once however often the page draws. */+/** The agent's transcript parsed, memoised by the text itself so an unchanged file is parsed once however often the page draws, and a grown one only from its new lines. */export function parsedOf(cache: ReadCache, agent: WfAgent): Parsed | null {const text = textOf(cache, agent)const path = agent.transcriptPathif (text === null || path === undefined) return null- const held = parsedMemo.get(path)-- if (held !== undefined && held.isTail === text.isTail && held.src === text.text) return held.parsed-- const parsed = parseActivity(text.text, text.isTail)-- parseCount += 1-- holdParsed(path, { src: text.text, isTail: text.isTail, parsed })-- return parsed+ return activityOf(path, text.text, text.isTail, text.tag)}/** Reads one agent's transcript into memory. Resolves when done; never rejects. */@@ -168,7 +133,7 @@ export async function loadTranscript(agent: WfAgent): Promise<void> {else if (read.reason === 'too-large' && b.host.fs.readTail !== undefined) {const tail = await b.host.fs.readTail(path, TAIL_BYTES)- hold(tails, path, { text: tail, size: read.size ?? 0 })+ hold(tails, path, { text: tail, size: read.size ?? 0, tag: `${read.size ?? 0}` })notes.set(path, { phase: 'ok', why: `${(read.size ?? 0) / 1_000_000 >= 0.1 ? `${((read.size ?? 0) / 1_000_000).toFixed(1)} MB` : 'a large file'}: only the last ${Math.round(TAIL_BYTES / 1000)} KB is read` })} else notes.set(path, { phase: 'failed', why: read.reason === 'too-large' ? `${((read.size ?? 0) / 1_000_000).toFixed(1)} MB is over the ${(TRANSCRIPT_CAP / 1_000_000).toFixed(1)} MB read cap and this host cannot read a tail` : read.reason === 'missing' ? 'the file is gone' : 'the host refused the read' })} catch (error) {@@ -211,7 +176,10 @@ export async function reloadTails(): Promise<void> {if (!isRunFile(path, b.configDir)) continuetry {- hold(tails, path, { text: await b.host.fs.readTail(path, TAIL_BYTES), size: held.size })+ const stat = await b.host.fs.stat(path).catch(() => undefined)+ const size = stat?.size ?? held.size++ hold(tails, path, { text: await b.host.fs.readTail(path, TAIL_BYTES), size, tag: `${size}:${stat?.mtimeMs ?? 0}` })} catch {// The held tail stays; the next tick tries again.}diff --git a/plugins/ruflo-console/hooks/data/wf-incr-activity.ts b/plugins/ruflo-console/hooks/data/wf-incr-activity.tsnew file mode 100644index 0000000000..1f0a7e02c1--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-incr-activity.ts@@ -0,0 +1,198 @@+/**+ * `parseActivity`'s answer, folded line by line (ADR-473; the machinery is data/wf-incr.ts). The state is bounded: the newest+ * ENTRY_CAP entries are kept, with the count of the ones before them; ids of calls that left the ring are remembered (up to ID_CAP,+ * oldest first) so a late result for one is still absorbed, as the whole-text parse absorbs it, instead of turning into a message.+ */+import { cleanBlock, cleanLine, ENTRY_CAP, EDIT_TOOLS, FILE_CAP, pathOf, READ_TOOLS, resultText, stamp, summaryOf, WRITE_TOOLS, type CallEntry, type Entry, type MessageRole, type Parsed, type TouchedFile } from './wf-activity'+import { Incremental, type Rec, type Tentative } from './wf-incr'++/** Call ids kept after their entry left the ring. Past this a result for a call this old reads as one whose call is before the part read. */+export const ID_CAP = 50_000++const asRecord = (value: unknown): Rec | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Rec) : null)++export class ActivityIncr extends Incremental<Parsed> {+ /** The newest entries; `index` and `callIndex` hold the position since the start of the text and are made relative when the answer is built. */+ private ring: Entry[] = []+ /** Entries and calls that left the ring from its front. */+ private base = 0+ private callsBase = 0+ private calls = 0+ private byId = new Map<string, number>()+ private files = new Map<string, TouchedFile>()+ private skipped = 0+ /** While a line is applied tentatively: how to take each change back. */+ private log: (() => void)[] | null = null++ protected restart(): void {+ this.ring = []+ this.base = this.callsBase = this.calls = this.skipped = 0+ this.byId = new Map()+ this.files = new Map()+ }++ weight(): number {+ let chars = 0++ for (const entry of this.ring) chars += entry.kind === 'call' ? entry.input.text.length + (entry.output?.text.length ?? 0) : entry.body.text.length++ return chars + this.byId.size * 48+ }++ private message(role: MessageRole, atMs: number | undefined, raw: string): void {+ if (raw.trim() === '') return++ this.ring.push({ kind: 'message', index: this.base + this.ring.length, role, body: cleanBlock(raw), ...(atMs !== undefined && { atMs }) })+ this.log?.push(() => void this.ring.pop())+ }++ protected fold(line: Rec): void {+ const body = asRecord(line.message)++ if ((line.type !== 'user' && line.type !== 'assistant') || body === null || line.isMeta === true) {+ this.skipped += 1+ this.log?.push(() => void (this.skipped -= 1))++ return+ }++ const at = stamp(line)+ const content = body.content++ if (typeof content === 'string') {+ this.message(line.type, at, content)++ return+ }++ if (!Array.isArray(content)) return++ for (const raw of content) {+ const block = asRecord(raw)++ if (block === null) continue++ if (block.type === 'text' && typeof block.text === 'string') this.message(line.type, at, block.text)+ else if (block.type === 'thinking' && typeof block.thinking === 'string') this.message('thinking', at, block.thinking)+ else if (block.type === 'tool_use' && typeof block.id === 'string') this.call(block, block.id, at)+ else if (block.type === 'tool_result') this.result(block, at)+ }+ }++ private call(block: Rec, id: string, at: number | undefined): void {+ // A streamed message repeats its blocks over several lines: a call is counted once, by its id.+ if (this.byId.has(id)) return++ const tool = cleanLine(typeof block.name === 'string' ? block.name : 'tool', 40)+ const seq = this.base + this.ring.length+ const entry: CallEntry = { kind: 'call', index: seq, callIndex: this.calls, id, tool, status: 'pending', summary: summaryOf(block.input), input: cleanBlock(JSON.stringify(block.input ?? {}, null, 2) ?? '{}'), output: null, ...(at !== undefined && { atMs: at }) }+ const path = pathOf(block.input)++ this.calls += 1+ this.byId.set(id, seq)+ this.ring.push(entry)+ this.log?.push(() => {+ this.ring.pop()+ this.byId.delete(id)+ this.calls -= 1+ })++ if (path !== undefined && (READ_TOOLS.has(tool) || EDIT_TOOLS.has(tool) || WRITE_TOOLS.has(tool))) {+ const held = this.files.get(path)+ const next: TouchedFile = { path, read: held?.read ?? 0, edit: held?.edit ?? 0, write: held?.write ?? 0 }++ if (READ_TOOLS.has(tool)) next.read += 1+ else if (EDIT_TOOLS.has(tool)) next.edit += 1+ else next.write += 1++ this.files.set(path, next)+ this.log?.push(() => (held === undefined ? this.files.delete(path) : this.files.set(path, held)))+ }+ }++ private result(block: Rec, at: number | undefined): void {+ const seq = typeof block.tool_use_id === 'string' ? this.byId.get(block.tool_use_id) : undefined+ const out = resultText(block.content)++ if (seq === undefined) {+ this.message('result', at, out === '' ? '(a result whose call is before the part read)' : out)++ return+ }++ const held = seq >= this.base ? this.ring[seq - this.base] : undefined++ // A call that left the ring still takes its result (it is no longer shown): nothing to set, and no message either.+ if (held === undefined || held.kind !== 'call') return++ const before = { output: held.output, status: held.status, endMs: held.endMs }++ held.output = cleanBlock(out === '' ? '(empty)' : out)+ held.status = block.is_error === true ? 'error' : 'ok'+ if (at !== undefined) held.endMs = at++ this.log?.push(() => {+ held.output = before.output+ held.status = before.status++ if (before.endMs === undefined) delete held.endMs+ else held.endMs = before.endMs+ })+ }++ protected tentative(rec: Rec): Tentative {+ const log: (() => void)[] = []++ this.log = log+ this.fold(rec)+ this.log = null++ return () => {+ for (let i = log.length - 1; i >= 0; i--) (log[i] as () => void)()+ }+ }++ /** Keeps the newest ENTRY_CAP entries and the newest ID_CAP ids; what leaves is counted. */+ protected override settle(): void {+ const over = this.ring.length - ENTRY_CAP++ if (over > 0) {+ for (let i = 0; i < over; i++) if ((this.ring[i] as Entry).kind === 'call') this.callsBase += 1++ this.ring.splice(0, over)+ this.base += over+ }++ for (const id of this.byId.keys()) {+ if (this.byId.size <= ID_CAP) break++ this.byId.delete(id)+ }+ }++ protected build(isTail: boolean): Parsed {+ const extra = Math.max(0, this.ring.length - ENTRY_CAP)+ let callsBefore = this.callsBase++ for (let i = 0; i < extra; i++) if ((this.ring[i] as Entry).kind === 'call') callsBefore += 1++ const entries: Entry[] = []+ const calls: CallEntry[] = []++ for (let i = extra; i < this.ring.length; i++) {+ const entry = this.ring[i] as Entry++ if (entry.kind === 'call') {+ const copy: CallEntry = { ...entry, index: i - extra, callIndex: entry.callIndex - callsBefore }++ entries.push(copy)+ calls.push(copy)+ } else entries.push({ ...entry, index: i - extra })+ }++ const files = [...this.files.values()].sort((a, b) => b.edit + b.write - (a.edit + a.write) || a.path.localeCompare(b.path)).slice(0, FILE_CAP)++ return { entries, calls, files, isTail, dropped: this.base + extra, skipped: this.skipped }+ }+}+diff --git a/plugins/ruflo-console/hooks/data/wf-incr-store.ts b/plugins/ruflo-console/hooks/data/wf-incr-store.tsnew file mode 100644index 0000000000..3e794558ff--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-incr-store.ts@@ -0,0 +1,106 @@+/**+ * The parsed transcripts the console holds, by path (ADR-473): one `ActivityIncr` state per transcript, so a transcript that grew is+ * parsed from where it left off, not from its first line. The drill's `parsedOf` and the folder reader's background warm-up both go through+ * here, which is what lets a search over every agent find its transcripts already parsed.+ *+ * Bounded by the text held, not by a count of files: a live project has 6 runs x 60 agents. The state of a transcript no frame has asked for+ * (a path not seen again) is the oldest in the map and goes first.+ */+import type { Parsed } from './wf-activity'+import { ActivityIncr } from './wf-incr-activity'++/** What the memo may keep, in characters of transcript text (a parsed transcript is no bigger than its text). */+export const PARSED_BUDGET_CHARS = 24_000_000+const PARSED_MAX_ENTRIES = 1024+/**+ * What the background warm-up may parse in one refresh: about 10 ms, inside one frame. It fills the memo up to its budget and no further, so it never+ * evicts what it parsed a minute before (the search stops at 8 million characters of entries, which is most of the 24 million of transcript text the memo+ * keeps: the lines carry ids, usage and streamed repeats).+ */+export const WARM_CHARS_PER_REFRESH = 400_000++type Held = { src: string; tag: string; isTail: boolean; parsed: Parsed; state: ActivityIncr }++const memo = new Map<string, Held>()+let chars = 0+let parses = 0+let resumed = 0+let fed = 0+let warmed = 0+let warmLeft = WARM_CHARS_PER_REFRESH++/** What the memo holds and how much parsing it has done: what a test or a bench reads to prove a frame parsed nothing, or only what was new. */+export const parsedStats = (): { entries: number; chars: number; parses: number; /** Of those, the ones that carried on from a held state. */ resumed: number; /** Characters parsed in all (a fresh parse counts the whole text). */ fed: number; /** Parses done ahead of time by a refresh; not in `parses`. */ warmed: number } => ({ entries: memo.size, chars, parses, resumed, fed, warmed })++export function resetStore(): void {+ memo.clear()+ chars = parses = resumed = fed = warmed = 0+ warmLeft = WARM_CHARS_PER_REFRESH+}++function hold(path: string, entry: Held): void {+ const old = memo.get(path)++ if (old !== undefined) chars -= old.src.length++ memo.delete(path)+ memo.set(path, entry)+ chars += entry.src.length++ for (const [key, held] of memo) {+ if (key === path || (chars <= PARSED_BUDGET_CHARS && memo.size <= PARSED_MAX_ENTRIES)) break++ memo.delete(key)+ chars -= held.src.length+ }+}++function parse(path: string, text: string, isTail: boolean, tag: string): Held {+ const held = memo.get(path)++ if (held !== undefined && held.isTail === isTail && held.tag === tag && held.src === text) return held++ const state = held?.state ?? new ActivityIncr()+ const done = state.update(text, isTail, tag)+ const entry: Held = { src: text, tag, isTail, parsed: done.value, state }++ fed += done.fed+ if (done.how === 'resumed') resumed += 1++ hold(path, entry)++ return entry+}++/** A transcript's activity, parsed from where the last parse of this path ended; the held answer where the text is the one it was made from. */+export function activityOf(path: string, text: string, isTail: boolean, tag = ''): Parsed {+ const held = memo.get(path)++ if (held !== undefined && held.isTail === isTail && held.tag === tag && held.src === text) return held.parsed++ parses += 1++ return parse(path, text, isTail, tag).parsed+}++/** Called once at the start of a refresh: gives the warm-up its allowance for this pass. */+export function beginWarm(): void {+ warmLeft = WARM_CHARS_PER_REFRESH+}++/**+ * Parses a whole transcript a refresh has just read, ahead of any frame that would ask for it, while this pass's allowance and the held-text+ * ceiling last. A transcript already current costs nothing; one that grew costs the new lines. Never parses a tail.+ */+export function warmActivity(path: string, text: string): void {+ const held = memo.get(path)++ if (held !== undefined && !held.isTail && held.tag === '' && held.src === text) return+ if (warmLeft <= 0 || (held === undefined && chars + text.length > PARSED_BUDGET_CHARS)) return++ const before = fed++ warmed += 1+ parse(path, text, false, '')+ warmLeft -= Math.max(1, fed - before)+}diff --git a/plugins/ruflo-console/hooks/data/wf-incr.ts b/plugins/ruflo-console/hooks/data/wf-incr.tsnew file mode 100644index 0000000000..eb25219ef1--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-incr.ts@@ -0,0 +1,220 @@+/**+ * Incremental transcript parsing (ADR-473). A live workflow agent's transcript only ever grows by appending lines, yet every+ * refresh used to parse the whole text again. Here a transcript keeps a parse state: how far the text was consumed (always just+ * after a newline, so no line straddles a chunk), a short anchor of the text before that point, and the running figures. A changed+ * text is checked against the anchor and, if it continues the old one, only the part after the consumed point is parsed. Anything+ * that does not check out (truncation, a rewrite, a window that slid past the anchor, an ambiguous match) is parsed whole: the+ * fallback is always a full parse, never a guess. A last line with no newline yet is parsed for the answer but not committed, so+ * the next call sees it again, finished.+ *+ * The folds below are written beside, not on top of, `parseTranscript` (data/workflows.ts) and `parseActivity` (data/wf-activity.ts):+ * those stay the reference the property test (tests/wf-incr.spec.ts) compares every append sequence against.+ *+ * This module parses text. It does not read: the host's `$.fs` has no range read, so on a whole-file read the saving is the parse (the+ * costly part), and the bytes saved are only where a host offers `readTail`.+ */+import { LINE_CAP, num, str, type TranscriptFacts } from './workflows'++export type Rec = Record<string, unknown>++/** One line as a record, by the rules of `jsonLines`: an object that parses, on a line of 2 to LINE_CAP characters starting with `{`. */+export function recordOf(line: string): Rec | null {+ if (line.length < 2 || line.length > LINE_CAP || line.charCodeAt(0) !== 123) return null++ try {+ const value: unknown = JSON.parse(line)++ return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Rec) : null+ } catch {+ return null+ }+}++/** Feeds every complete line of `text` from `from` to `fold`; returns the offset just after the last newline (never before `from`). */+export function scanLines(text: string, from: number, fold: (rec: Rec) => void): number {+ const end = text.lastIndexOf('\n') + 1+ let pos = from++ while (pos < end) {+ const nl = text.indexOf('\n', pos)+ const rec = nl - pos < 2 ? null : recordOf(text.slice(pos, nl))++ if (rec !== null) fold(rec)++ pos = nl + 1+ }++ return Math.max(from, end)+}++const ANCHOR_CHARS = 4096+const HEAD_CHARS = 512+/** A tail window slides, so its anchor is searched for: a short one could match some other place by chance, a long one cannot. Below this the window is parsed whole (it is small by definition). */+const MIN_TAIL_ANCHOR = 1024++type Cursor = { src: string; tag: string; consumed: number; head: string; anchor: string; isTail: boolean }++/** Where the old parse can carry on in `text`, or null where it cannot be shown to continue (then the caller parses whole). */+function resumeAt(c: Cursor, text: string, isTail: boolean): number | null {+ if (c.isTail !== isTail || c.anchor === '') return null++ if (!isTail) {+ // A whole file only grows at its end: same first characters, same text just before the consumed point (a text cut shorter than that point cannot hold it).+ return text.startsWith(c.head) && text.startsWith(c.anchor, c.consumed - c.anchor.length) ? c.consumed : null+ }++ // A tail window slides: the anchor must be found, once, in the new window.+ if (c.anchor.length < MIN_TAIL_ANCHOR) return null++ const at = text.indexOf(c.anchor)++ return at < 0 || text.indexOf(c.anchor, at + 1) >= 0 ? null : at + c.anchor.length+}++export type Outcome = 'fresh' | 'resumed' | 'same'+export type Update<R> = { value: R; how: Outcome; /** Characters this call parsed (the whole text for a fresh parse). */ fed: number }++/** What a fold does to its state for a line that may still change: apply it, and the returned function takes it back. */+export type Tentative = () => void++/** The shared machinery: resume or restart, scan the new lines, build the answer with an unfinished last line counted. */+export abstract class Incremental<R> {+ private cursor: Cursor | null = null+ private last: R | null = null+ protected abstract restart(): void+ protected abstract fold(rec: Rec): void+ protected abstract tentative(rec: Rec): Tentative+ /** Called after each committed batch (the activity fold trims its ring here). */+ protected settle(): void {}+ protected abstract build(isTail: boolean): R++ /** Characters held that belong to this state beyond the text (for the LRU's weight): the text itself is held by the caller. */+ abstract weight(): number++ /** `tag` says which version of the file `text` is (its size and mtime): a tail window can read the same at two places, and only a differing tag then tells them apart. */+ update(text: string, isTail: boolean, tag = ''): Update<R> {+ const c = this.cursor++ if (c !== null && this.last !== null && c.src === text && c.tag === tag && c.isTail === isTail) return { value: this.last, how: 'same', fed: 0 }++ const resume = c === null ? null : resumeAt(c, text, isTail)+ let from = resume++ if (from === null) {+ this.restart()+ // A tail window starts mid-line: its first line is dropped (the whole text where it holds no newline, as `parseTranscript` does).+ from = isTail ? text.indexOf('\n') + 1 : 0+ }++ const lower = resume === null ? from : 0+ const consumed = scanLines(text, from, rec => this.fold(rec))++ this.settle()++ const pending = consumed < text.length ? recordOf(text.slice(consumed)) : null+ const undo = pending === null ? null : this.tentative(pending)+ const value = this.build(isTail)++ undo?.()+ this.last = value+ this.cursor = { src: text, tag, consumed, isTail, head: text.slice(0, Math.min(HEAD_CHARS, consumed)), anchor: text.slice(Math.max(lower, consumed - ANCHOR_CHARS), consumed) }++ return { value, how: resume === null ? 'fresh' : 'resumed', fed: text.length - from }+ }+}++/**+ * `parseTranscript`'s answer, folded line by line. Messages are keyed by id (a streamed message repeats its lines), the line number+ * stands in for a missing id, and the tokens are those of the last keyed message that carried usage.+ */+export class FactsIncr extends Incremental<TranscriptFacts> {+ private usage = new Map<string, number>()+ private model: string | undefined+ private firstMs: number | undefined+ private lastMs: number | undefined+ private lastKey: string | undefined+ private toolCalls = 0+ private lastTool: string | undefined+ private lineNo = 0+ /** Set while a line is applied tentatively: the key it wrote and what was there. */+ private wrote: { key: string; prev: number | undefined } | null = null++ protected restart(): void {+ this.usage = new Map()+ this.model = this.firstMs = this.lastMs = this.lastKey = this.lastTool = undefined+ this.toolCalls = 0+ this.lineNo = 0+ }++ weight(): number {+ return this.usage.size * 48+ }++ protected fold(line: Rec): void {+ const index = this.lineNo+++ const at = typeof line.timestamp === 'string' ? Date.parse(line.timestamp) : Number.NaN++ if (Number.isFinite(at)) {+ this.firstMs ??= at+ this.lastMs = at+ }++ const message = typeof line.message === 'object' && line.message !== null && !Array.isArray(line.message) ? (line.message as Rec) : null++ if (line.type !== 'assistant' || message === null) return++ const u = typeof message.usage === 'object' && message.usage !== null && !Array.isArray(message.usage) ? (message.usage as Rec) : null+ const key = str(message.id, 80) ?? `line-${index}`++ if (u !== null) {+ this.wrote = { key, prev: this.usage.get(key) }+ this.usage.set(key, (num(u.input_tokens) ?? 0) + (num(u.cache_creation_input_tokens) ?? 0) + (num(u.cache_read_input_tokens) ?? 0) + (num(u.output_tokens) ?? 0))+ this.lastKey = key+ }++ this.model = str(message.model, 60) ?? this.model++ if (Array.isArray(message.content)) {+ for (const block of message.content) {+ const b = typeof block === 'object' && block !== null && !Array.isArray(block) ? (block as Rec) : null++ if (b?.type === 'tool_use') {+ this.toolCalls += 1+ this.lastTool = str(b.name, 40) ?? this.lastTool+ }+ }+ }+ }++ protected tentative(rec: Rec): Tentative {+ const saved = { model: this.model, firstMs: this.firstMs, lastMs: this.lastMs, lastKey: this.lastKey, toolCalls: this.toolCalls, lastTool: this.lastTool, lineNo: this.lineNo }++ this.wrote = null+ this.fold(rec)++ const wrote = this.wrote as { key: string; prev: number | undefined } | null++ return () => {+ Object.assign(this, saved)++ if (wrote !== null) {+ if (wrote.prev === undefined) this.usage.delete(wrote.key)+ else this.usage.set(wrote.key, wrote.prev)+ }+ }+ }++ protected build(): TranscriptFacts {+ const tokens = this.lastKey === undefined ? undefined : this.usage.get(this.lastKey)++ return {+ toolCalls: this.toolCalls,+ messages: this.usage.size,+ ...(this.model !== undefined && { model: this.model }),+ ...(tokens !== undefined && { tokens }),+ ...(this.firstMs !== undefined && { firstMs: this.firstMs }),+ ...(this.lastMs !== undefined && { lastMs: this.lastMs }),+ ...(this.lastTool !== undefined && { lastTool: this.lastTool }),+ }+ }+}diff --git a/plugins/ruflo-console/hooks/data/workflows-read.ts b/plugins/ruflo-console/hooks/data/workflows-read.tsindex 921bd9f6e4..f2875f8c67 100644--- a/plugins/ruflo-console/hooks/data/workflows-read.ts+++ b/plugins/ruflo-console/hooks/data/workflows-read.ts@@ -6,7 +6,9 @@* its transcripts are not read.*/import { readBounded, under, type ReadCache, type ReaderFs } from './files'-import { buildRun, parseTranscript, type RunInput, type TranscriptFacts, type WfRun } from './workflows'+import { FactsIncr } from './wf-incr'+import { beginWarm, warmActivity } from './wf-incr-store'+import { buildRun, type RunInput, type TranscriptFacts, type WfRun } from './workflows'/** The engine refuses files over 4 MiB; below this a transcript is read whole. */export const TRANSCRIPT_CAP = 3_000_000@@ -24,26 +26,23 @@ export type WorkflowRuns = { runs: WfRun[]; /** The project's folder under the cexport const slugOf = (cwd: string): string => cwd.replace(/[^A-Za-z0-9]/g, '-')/**- * What each transcript parsed to, by path. A refresh re-reads every run on a timer; JSON.parse of the same unchanged- * transcripts was the whole cost of it (bench-swarmui.mjs: ~170 ms of ~170 ms at 6 runs x 60 agents). The read cache hands back- * the same string while a file is unchanged, so the text itself is the key's check. Bounded, oldest out.+ * What each transcript parsed to, by path. A refresh re-reads every run on a timer; JSON.parse of the same unchanged transcripts was the whole+ * cost of it (bench-swarmui.mjs: ~170 ms of ~170 ms at 6 runs x 60 agents), and of a transcript that grew, the parse of the lines it already had.+ * Each path keeps its parse state (data/wf-incr.ts): an unchanged text is the held answer, an appended one is parsed from the end of the old+ * one (ADR-473), anything else is parsed whole. Bounded, oldest out.*/const PARSED_MAX = MAX_RUNS * MAX_AGENTS * 2-const parsed = new Map<string, { text: string; isTail: boolean; facts: TranscriptFacts }>()+const parsed = new Map<string, FactsIncr>()-function factsOf(path: string, text: string, isTail: boolean): TranscriptFacts {- const held = parsed.get(path)-- if (held !== undefined && held.isTail === isTail && held.text === text) return held.facts-- const facts = parseTranscript(text, isTail)+function factsOf(path: string, text: string, isTail: boolean, tag = ''): TranscriptFacts {+ const state = parsed.get(path) ?? new FactsIncr()parsed.delete(path)- parsed.set(path, { text, isTail, facts })+ parsed.set(path, state)if (parsed.size > PARSED_MAX) parsed.delete(parsed.keys().next().value as string)- return facts+ return state.update(text, isTail, tag).value}/**@@ -119,7 +118,7 @@ export async function readWorkflowRuns(fs: WorkflowFs, cache: ReadCache, optionsif (transcript === null) skipped.push(path)}- const facts = kept ?? (transcript === null ? undefined : factsOf(path, transcript, isTail))+ const facts = kept ?? (transcript === null ? undefined : factsOf(path, transcript, isTail, isTail ? `${size}:${listed?.mtimeMs ?? 0}` : ``))if (kept === undefined && isTail && facts !== undefined) rememberTail(path, size, listed?.mtimeMs, facts)@@ -142,5 +141,23 @@ export async function readWorkflowRuns(fs: WorkflowFs, cache: ReadCache, options}),)+ warmAhead(runs, cache)+return { runs, root, capBytes: TRANSCRIPT_CAP, skipped, more: Math.max(0, found.length - chosen.length) }}++/**+ * Parses the transcripts this refresh read for the drill and its search before any frame asks (ADR-473), in the order the search walks them (live runs+ * first, then each run's phases and agents), so the search finds them parsed. A small allowance a refresh; a transcript already current costs nothing.+ */+function warmAhead(runs: readonly WfRun[], cache: ReadCache): void {+ beginWarm()++ for (const run of [...runs.filter(candidate => candidate.running > 0), ...runs.filter(candidate => candidate.running === 0)]) {+ for (const agent of run.phases.flatMap(phase => phase.agents)) {+ const held = agent.ruflo !== undefined || agent.transcriptPath === undefined ? undefined : cache.get(agent.transcriptPath)++ if (held !== undefined && 'text' in held && held.text !== '') warmActivity(agent.transcriptPath as string, held.text)+ }+ }+}diff --git a/plugins/ruflo-console/hooks/data/workflows.ts b/plugins/ruflo-console/hooks/data/workflows.tsindex a7ed352c44..088fdee105 100644--- a/plugins/ruflo-console/hooks/data/workflows.ts+++ b/plugins/ruflo-console/hooks/data/workflows.ts@@ -66,7 +66,7 @@ export type WfRun = {const asRecord = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)/** Escape sequences go whole (an OSC title or a hyperlink would otherwise leave its text behind), then control, zero-width and bidi-override characters (they reorder or hide text) become spaces: every string a file supplies passes here. */const CONTROL = HIDDEN-const str = (value: unknown, max = 200): string | undefined => {+export const str = (value: unknown, max = 200): string | undefined => {const clean = typeof value === 'string' ? value.replace(ESCAPES, '').replace(INVISIBLE, '').replace(CONTROL, ' ').slice(0, max) : ''return clean === '' ? undefined : clean@@ -94,7 +94,10 @@ const SECRETISH = new RegExp('gi',)export const maskSecrets = (text: string): string => text.replace(SECRETISH, '‹masked›')-const num = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)+export const num = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)++/** A line longer than this is not read (ADR-473): the engine refuses files over 4 MiB and the console reads 3 MB whole, so no real line is this long, and the cap bounds what a half-written line can hold. */+export const LINE_CAP = 3_000_000/** JSONL as records: a line that does not parse (a half-written tail) is dropped, never thrown on. */export function jsonLines(text: string | null): Record<string, unknown>[] {@@ -103,7 +106,7 @@ export function jsonLines(text: string | null): Record<string, unknown>[] {const out: Record<string, unknown>[] = []for (const line of text.split('\n')) {- if (line.length < 2 || line[0] !== '{') continue+ if (line.length < 2 || line.length > LINE_CAP || line[0] !== '{') continuetry {const record = asRecord(JSON.parse(line))diff --git a/plugins/ruflo-console/scripts/bench-workflows.mjs b/plugins/ruflo-console/scripts/bench-workflows.mjsindex 726d8f50c6..775c6c43bf 100644--- a/plugins/ruflo-console/scripts/bench-workflows.mjs+++ b/plugins/ruflo-console/scripts/bench-workflows.mjs@@ -10,6 +10,9 @@* Cases: transcript parse at 1 / 3 / 5 / 50 MB; the folder reader at 1 / 20 / 200 runs on disk (cold, refreshed unchanged, one agent grown)* and with 5 MB / 50 MB transcripts (tail reads); a whole refresh with the page open and closed; the page frame (what one draw costs)* at 1 / 20 / 200 runs and with the drill open; search across every parsed transcript; a replay step; a conversation thread fed 1000 messages.+ * ADR-473 adds: 50 lines appended to a 3 MB / 5 MB / 50 MB transcript (the whole parse against the incremental one, with the answers compared), a 200-run+ * refresh in which one 2.4 MB transcript grew, and the first draw of a typed search with a cold and with a warmed parse memo. The incremental cases+ * need hooks/data/wf-incr*.ts and are skipped (printed as absent) where those do not exist, so the same script can be run on the code before.*/import { newState } from '../hooks/state.ts'import { parseActivity } from '../hooks/data/wf-activity.ts'@@ -29,6 +32,10 @@ import { resetSlots, slotsFor } from '../hooks/views/wf-slots.ts'import { registerDrill, setQuery } from '../hooks/views/wf-detail.ts'import { registerSearch } from '../hooks/views/wf-search.ts'import { sha256 } from '../hooks/data/ap-envelope.ts'+import { parsedStats } from '../hooks/data/wf-drill-io.ts'++/** The incremental parsers, where this tree has them. */+const incr = await Promise.all([import('../hooks/data/wf-incr.ts'), import('../hooks/data/wf-incr-activity.ts')]).then(([a, b]) => ({ FactsIncr: a.FactsIncr, ActivityIncr: b.ActivityIncr })).catch(() => null)const QUICK = process.argv.includes('--quick')const CHECK = process.argv.includes('--check')@@ -55,6 +62,14 @@ const BUDGET_MS = /** @type {Record<string, number>} */ ({'search: miss over 360 transcripts': 120,'search: hit': 120,'replay: boardAt, 2000 agents': 12,+ // ADR-473: what one refresh may spend on a transcript that grew by 50 lines, whole file or tail window (one frame is ~16 ms).+ 'append 50 lines onto 3 MB, activity: incremental': 8,+ 'append 50 lines onto 3 MB, facts: incremental': 5,+ 'append 50 lines onto 5 MB (400 KB tail), activity: incremental': 8,+ 'append 50 lines onto 50 MB (400 KB tail), activity: incremental': 8,+ 'reader 200 runs, 2.4 MB transcripts: refresh, 50 lines appended to one': 40,+ 'search typed: first draw, project that fits (memo warmed)': 16,+ 'refresh: warm-up tick (cold memo), slowest of 100': 60,})const BUDGET_P99_MS = 16@@ -210,7 +225,7 @@ function disk(/** @type {{ runs: number; heavy: number; agents: number; bytes: nreadTail: async (/** @type {string} */ _path, /** @type {number} */ _bytes) => (fs.reads.tail++, tail),}- return { fs, files, grow: (/** @type {string} */ path) => { const held = files.get(path); if (held !== undefined) files.set(path, { text: `${held.text}${JSON.stringify({ type: 'user', message: { content: 'more' } })}\n`, mtimeMs: held.mtimeMs + 1000, size: held.size + 50 }) } }+ return { fs, files, append: (/** @type {string} */ path, /** @type {string} */ more) => { const held = files.get(path); if (held !== undefined) files.set(path, { text: `${held.text}${more}`, mtimeMs: held.mtimeMs + 1000, size: held.size + more.length }) }, grow: (/** @type {string} */ path) => { const held = files.get(path); if (held !== undefined) files.set(path, { text: `${held.text}${JSON.stringify({ type: 'user', message: { content: 'more' } })}\n`, mtimeMs: held.mtimeMs + 1000, size: held.size + 50 }) } }}const summary = (/** @type {import('../hooks/data/workflows.ts').WfRun[]} */ runs) => runs.map(run => [run.id, run.state, run.total, run.done, run.running, run.totalTokens, run.phases.map(p => p.agents.map(a => [a.id, a.state, a.tokens, a.toolCalls, a.lastTool]))])@@ -273,6 +288,114 @@ for (const mb of want('parse') ? (QUICK ? [1, 3, 5] : [1, 3, 5, 50]) : []) {bench(`parseActivity ${mb} MB`, () => { const p = parseActivity(text); return [p.entries.length, p.calls.length, p.dropped, p.files.length] }, runs)}+// 1b. Append: 50 lines onto a transcript that already has megabytes (ADR-473). The reference (whole parse) and the incremental parse see the same texts in the same order.+console.log('\n# append: 50 lines onto an existing transcript')++/** @type {(name: string, times: number[], note: string) => void} */+function seriesReport(name, times, note) {+ times.sort((a, b) => a - b)++ const median = times[Math.floor(times.length / 2)] ?? 0+ const p99 = times[Math.min(times.length - 1, Math.floor(times.length * 0.99))] ?? 0+ const budget = BUDGET_MS[name]+ const over = budget !== undefined && (median > budget || p99 > Math.max(BUDGET_P99_MS, budget * 3))++ if (over) failed.push(name + ': median ' + median.toFixed(3) + ' ms (budget ' + budget + '), p99 ' + p99.toFixed(3) + ' ms')++ console.log(name.padEnd(64) + ' median ' + median.toFixed(3).padStart(9) + ' ms · p99 ' + p99.toFixed(3).padStart(9) + ' ms · ' + note + (over ? ' · OVER BUDGET' : ''))+}++/** 50 more lines in the shapes Claude Code writes, with ids no earlier batch used. */+const batchOf = (/** @type {number} */ k) => transcriptOfBytes(30_000, 7000 + k).split('\n').slice(0, 50).join('\n') + '\n'+const ROUNDS = 14++for (const mb of want('append') ? (QUICK ? [3, 5] : [3, 5, 50]) : []) {+ const base = transcriptOfBytes(mb * 1_000_000, 1)+ const isTail = mb > 3+ const batches = Array.from({ length: ROUNDS }, (_, k) => batchOf(k))+ /** Each step's text: the whole file (3 MB, read whole) or its last 400 KB (read past the cap), flattened before timing. */+ const whole = /** @type {string[]} */ ([])+ let file = base++ for (const batch of batches) {+ file += batch+ whole.push(isTail ? file.slice(file.length - TAIL_BYTES) : file.slice(0))+ whole[whole.length - 1]?.charCodeAt(0)+ }++ const first = isTail ? base.slice(base.length - TAIL_BYTES) : base+ const where = isTail ? mb + ' MB (400 KB tail)' : mb + ' MB'+ const refA = whole.map((text, i) => ({ text, i }))++ // The reference: what a refresh used to do for every changed transcript, the whole text (the window, for a tail).+ const refAct = /** @type {unknown[]} */ ([])+ const refFacts = /** @type {unknown[]} */ ([])+ const tA = /** @type {number[]} */ ([])+ const tF = /** @type {number[]} */ ([])++ for (const { text } of refA) {+ let t = process.hrtime.bigint()++ refAct.push(parseActivity(text, isTail))+ tA.push(ms(t))+ t = process.hrtime.bigint()+ refFacts.push(parseTranscript(text, isTail))+ tF.push(ms(t))+ }++ seriesReport('append 50 lines onto ' + where + ', activity: whole parse', tA, 'parsed ' + (whole[0]?.length ?? 0) + ' chars each')+ seriesReport('append 50 lines onto ' + where + ', facts: whole parse', tF, 'parsed ' + (whole[0]?.length ?? 0) + ' chars each')++ if (incr === null) {+ console.log('(incremental parsers not in this tree)')+ continue+ }++ const act = new incr.ActivityIncr()+ const facts = new incr.FactsIncr()+ const iA = /** @type {number[]} */ ([])+ const iF = /** @type {number[]} */ ([])+ const fed = /** @type {number[]} */ ([])+ const outA = /** @type {unknown[]} */ ([])+ const outF = /** @type {unknown[]} */ ([])++ act.update(first, isTail, '0')+ facts.update(first, isTail, '0')++ for (const [i, text] of whole.entries()) {+ let t = process.hrtime.bigint()+ const a = act.update(text, isTail, String(i + 1))++ iA.push(ms(t))+ fed.push(a.fed)+ outA.push(a.value)+ t = process.hrtime.bigint()+ outF.push(facts.update(text, isTail, String(i + 1)).value)+ iF.push(ms(t))+ }++ const fedMedian = [...fed].sort((a, b) => a - b)[Math.floor(fed.length / 2)] ?? 0+ const sameA = isTail ? 'n/a (tail: compared once below)' : outA.every((v, i) => digest(v) === digest(refAct[i])) ? 'answers identical' : 'ANSWERS DIFFER'+ const sameF = isTail ? 'n/a (tail: compared once below)' : outF.every((v, i) => digest(v) === digest(refFacts[i])) ? 'answers identical' : 'ANSWERS DIFFER'++ if (sameA === 'ANSWERS DIFFER' || sameF === 'ANSWERS DIFFER') failed.push('append ' + where + ': incremental answer differs from the whole parse')++ seriesReport('append 50 lines onto ' + where + ', activity: incremental', iA, 'parsed ' + fedMedian + ' chars · ' + sameA)+ seriesReport('append 50 lines onto ' + where + ', facts: incremental', iF, sameF)++ if (isTail) {+ // A tail state carries the history of every window since it began, so it is compared with the whole parse of the file from its first complete line.+ const from = base.indexOf('\n', base.length - TAIL_BYTES) + 1+ const reference = parseActivity(file.slice(from), false)+ const got = /** @type {import('../hooks/data/wf-activity.ts').Parsed} */ (outA.at(-1))+ const same = digest({ ...reference, isTail: true }) === digest(got)++ console.log(''.padEnd(64) + ' tail state vs whole parse of the file from its anchor: ' + (same ? 'identical' : 'DIFFER'))++ if (!same) failed.push('append ' + where + ': the tail state differs from the whole parse from its anchor')+ }+}+// 2. The folder reader.console.log('\n# folder reader (6 runs read, however many are on disk)')@@ -292,6 +415,28 @@ for (const runs of want('reader') ? [1, 20, 200] : []) {await benchAsync(`reader ${runs} runs: refresh, one agent grew`, async () => { d.grow(victim); return summary((await read()).runs) }, 12, () => 'n/a (grows)')}+if (want('reader') && !QUICK) {+ // 200 runs on disk, the newest 6 with 8 transcripts of 2.4 MB (read whole): a refresh in which one of them grew by 50 lines.+ const d = disk({ runs: 200, heavy: 6, agents: 8, bytes: 2_400_000 })+ const cache = new Map()+ const opts = { configDir: CONFIG, cwd: CWD, nowMs: NOW }+ const read = () => readWorkflowRuns(/** @type {never} */ (d.fs), cache, opts)+ const victim = ROOT + '/' + SESSION + '/subagents/workflows/wf_r000/agent-a0.jsonl'+ let k = 0++ const start = process.hrtime.bigint()++ await read()+ console.log('reader 200 runs, 2.4 MB transcripts: first read (cold)'.padEnd(46) + ' ' + ms(start).toFixed(1).padStart(10) + ' ms')+ // The first refreshes after a page opens also parse ahead for the drill and its search (a small allowance each); measure once that has settled.+ const settle = process.hrtime.bigint()++ for (let i = 0; i < 70; i++) await read()+ console.log('reader 200 runs, 2.4 MB transcripts: 70 refreshes to settle'.padEnd(46) + ' ' + ms(settle).toFixed(1).padStart(10) + ' ms in all')+ await benchAsync('reader 200 runs, 2.4 MB transcripts: refresh, unchanged', async () => summary((await read()).runs), 12)+ await benchAsync('reader 200 runs, 2.4 MB transcripts: refresh, 50 lines appended to one', async () => { d.append(victim, batchOf(100 + k++)); return summary((await read()).runs) }, 12, () => 'n/a (grows)')+}+console.log('\n# folder reader, transcripts over the read cap (tail reads)')for (const mb of want('tail') ? (QUICK ? [5] : [5, 50]) : []) {@@ -319,6 +464,8 @@ if (want('refresh')) {const { state, host } = worldlet t = NOW+ for (let i = 0; i < 40; i++) await refreshWorkflows(state, host, true, (t += 1000))+await benchAsync('refresh: page open, nothing changed', async () => { await refreshWorkflows(state, host, true, (t += 1000)); return summary(state.wf.read?.runs ?? []) }, 12)state.view = 'overview'@@ -389,13 +536,92 @@ if (want('drill')) {console.log(`${' '.repeat(46)} agent transcript: ${parsed?.entries.length ?? 0} entries kept (${parsed?.dropped ?? 0} older dropped)`)bench('frame: page, drill open on an agent', () => countOf(frame.tree()), ITERS || 40, out => String(out))- // A query typed in the search box: every frame asks for the search of all 360 transcripts. The first draw parses them; after it, a frame must not.+ // A query typed in the search box: every frame asks for the search of all 360 transcripts. The first draw parses them (the memo is empty: a person typed+ // before any refresh parsed ahead); after it, a frame must not. Then the same with the memo warmed by 100 refresh ticks (5 minutes of a page left open at the 3 s refresh).+ const rebind = () => {+ resetDrillIo()+ bindDrill(world.state, /** @type {never} */ ({ fs: world.host.fs, run: world.host.run, invalidate: noop }))+ }++ rebind()+const typed = process.hrtime.bigint()setQuery(envNow(), 'module_7')countOf(frame.tree())- console.log(`${'search typed: first draw (parses all)'.padEnd(46)} ${ms(typed).toFixed(1).padStart(10)} ms`)+ console.log(String('search typed: first draw (cold memo)').padEnd(46) + ' ' + ms(typed).toFixed(1).padStart(10) + ' ms · parses ' + parsedStats().parses + ' · chars held ' + parsedStats().chars)bench('frame: page, search query active', () => countOf(frame.tree()), ITERS || 40, out => String(out))+ rebind()++ const ticks = /** @type {number[]} */ ([])++ for (let i = 0; i < 100; i++) {+ const t = process.hrtime.bigint()++ await refreshWorkflows(world.state, world.host, true, NOW)+ ticks.push(ms(t))+ }++ ticks.sort((x, y) => x - y)+ seriesReport('refresh: warm-up tick (cold memo), slowest of 100', [ticks.at(-1) ?? 0], 'median tick ' + (ticks[50] ?? 0).toFixed(1) + ' ms · parsed ahead: ' + JSON.stringify({ warmed: parsedStats().warmed, held: parsedStats().chars }))++ const warm = process.hrtime.bigint()+ const before = parsedStats().parses++ setQuery(envNow(), 'module_8')+ countOf(frame.tree())+ console.log(String('search typed: first draw (memo warmed by 100 refreshes)').padEnd(64) + ' ' + ms(warm).toFixed(1).padStart(9) + ' ms · parses on the frame: ' + (parsedStats().parses - before) + ' (the search scans more than the 24 M memo holds)')+}++// 4b. A project whose search fits the parse memo (6 runs x 20 agents x 100 KB = 12 M characters, under its 24 M): the first draw after typing, cold and warmed (ADR-473).+console.log('\n# typed search on a project that fits the memo')++if (want('typed')) {+ resetSlots()+ resetDrillIo()+ registerDrill()+ registerSearch()++ const world = await worldOf(disk({ runs: 6, heavy: 6, agents: 20, bytes: 100_000 }))+ const frame = frameOf(world)+ const envNow = () => {+ const m = workflowsModelOf(world.state, NOW)+ const h = pick(world.state.wf.ui, m?.runs ?? [])++ return /** @type {never} */ ({ ctx: frame.ctx, runs: m?.runs ?? [], run: h.run, phase: h.phase, agent: h.agent, ui: h.ui, nowMs: NOW })+ }+ const typeOnce = (/** @type {string} */ query) => {+ const t = process.hrtime.bigint()+ const before = parsedStats().parses++ setQuery(envNow(), query)+ countOf(frame.tree())++ return { ms: ms(t), parses: parsedStats().parses - before }+ }++ resetDrillIo()++ const cold = typeOnce('module_7')++ console.log('search typed: first draw, project that fits (cold memo)'.padEnd(64) + ' ' + cold.ms.toFixed(1).padStart(9) + ' ms · parses ' + cold.parses)+ resetDrillIo()++ const ticks = /** @type {number[]} */ ([])++ for (let i = 0; i < 40; i++) {+ const t = process.hrtime.bigint()++ await refreshWorkflows(world.state, world.host, true, NOW)+ ticks.push(ms(t))+ }++ ticks.sort((x, y) => x - y)+ console.log(''.padEnd(64) + ' warm-up: 40 refresh ticks, median ' + (ticks[20] ?? 0).toFixed(1) + ' ms, slowest ' + (ticks.at(-1) ?? 0).toFixed(1) + ' ms · held ' + parsedStats().chars + ' chars')++ const warm = typeOnce('module_8')++ seriesReport('search typed: first draw, project that fits (memo warmed)', [warm.ms], 'parses on the frame: ' + warm.parses)}// 5. Search over every parsed transcript.diff --git a/plugins/ruflo-console/scripts/kit-seq.sh b/plugins/ruflo-console/scripts/kit-seq.shnew file mode 100755index 0000000000..4d86374679--- /dev/null+++ b/plugins/ruflo-console/scripts/kit-seq.sh@@ -0,0 +1,75 @@+#!/usr/bin/env bash+# Runs the console's kit tests (tests/*.test.ts) one file at a time with `claude plugin test` (ADR-473).+#+# Why: `claude plugin test` runs every file in its own child at once. On a loaded machine (load average 30+) 3-8 of the+# view tests then exceed their own 5 s limits, which says nothing about the code. One file at a time they do not.+# `claude plugin test` refuses a symlinked tree as path traversal, so the plugin is COPIED into a temp dir (hooks, catalog,+# types, tsconfig, plugin.json, the test fixtures and helpers) and the test files are swapped in one by one.+#+# scripts/kit-seq.sh every tests/*.test.ts+# scripts/kit-seq.sh nav actions only tests/nav.test.ts and tests/actions.test.ts (names, with or without .test.ts)+#+# Prints one line per file, the failing file's output, and a total; exits 1 on any failure. The temp dir is removed on exit.+set -euo pipefail++PLUGIN="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"+TMP="$(mktemp -d "${TMPDIR:-/tmp}/kit-seq.XXXXXX")"+readonly PLUGIN TMP++# Removes exactly the directory made above, and only if it is still a directory under the temp root with the expected name.+cleanup() {+ case "$TMP" in+ "${TMPDIR:-/tmp}"/kit-seq.??????) [ -d "$TMP" ] && rm -rf -- "$TMP" ;;+ esac+}+trap cleanup EXIT++command -v claude >/dev/null 2>&1 || { echo "kit-seq: the claude CLI is not on PATH" >&2; exit 2; }++cd "$PLUGIN"+mkdir -p "$TMP/.claude-plugin" "$TMP/tests"+cp -rL hooks catalog types tsconfig.json "$TMP/"+cp -L .claude-plugin/plugin.json "$TMP/.claude-plugin/"+[ -f package.json ] && cp -L package.json "$TMP/"+[ -d tests/fixtures ] && cp -rL tests/fixtures "$TMP/tests/"+# Helpers that sit beside the tests (anything that is not itself a test or a spec).+while IFS= read -r helper; do cp -L "$helper" "$TMP/tests/"; done < <(/usr/bin/find tests -maxdepth 1 -type f ! -name '*.test.ts' ! -name '*.spec.ts' | sort)++declare -a files=()+if [ "$#" -gt 0 ]; then+ for name in "$@"; do+ name="${name##*/}"; name="${name%.test.ts}"+ [ -f "tests/$name.test.ts" ] || { echo "kit-seq: no tests/$name.test.ts" >&2; exit 2; }+ files+=("tests/$name.test.ts")+ done+else+ while IFS= read -r f; do files+=("$f"); done < <(/usr/bin/find tests -maxdepth 1 -type f -name '*.test.ts' | sort)+fi++[ "${#files[@]}" -gt 0 ] || { echo "kit-seq: no kit tests found" >&2; exit 2; }++pass=0 fail=0 failed_files=0 out="$TMP/out.txt"+for f in "${files[@]}"; do+ base="$(basename "$f")"+ cp -L "$f" "$TMP/tests/$base"+ code=0+ timeout 600 claude plugin test "$TMP" >"$out" 2>&1 || code=$?+ rm -f -- "$TMP/tests/$base"++ # The runner ends with "N pass", "N fail" lines; a run that printed neither (a crash, a timeout) is a failure.+ p="$(grep -E '^ *[0-9]+ pass$' "$out" | tail -1 | grep -oE '[0-9]+' || true)"+ x="$(grep -E '^ *[0-9]+ fail$' "$out" | tail -1 | grep -oE '[0-9]+' || true)"+ p="${p:-0}"; x="${x:-0}"+ pass=$((pass + p)); fail=$((fail + x))++ if [ "$code" -eq 0 ] && [ "$x" -eq 0 ] && [ "$p" -gt 0 ]; then+ printf 'PASS %-34s %s pass\n' "$base" "$p"+ else+ failed_files=$((failed_files + 1))+ printf 'FAIL %-34s %s pass, %s fail, exit %s\n' "$base" "$p" "$x" "$code"+ tail -40 "$out" | sed 's/^/ /'+ fi+done++printf '\n%s files, %s pass, %s fail, %s file(s) failed\n' "${#files[@]}" "$pass" "$fail" "$failed_files"+[ "$failed_files" -eq 0 ]diff --git a/plugins/ruflo-console/scripts/typecheck.sh b/plugins/ruflo-console/scripts/typecheck.shnew file mode 100644index 0000000000..77e5e52b01--- /dev/null+++ b/plugins/ruflo-console/scripts/typecheck.sh@@ -0,0 +1,43 @@+#!/usr/bin/env bash+# Type-checks the console: `tsc --noEmit -p plugins/ruflo-console` (ADR-473).+#+# tsconfig.json reads the ambient declarations (claude-code, claude-code-tools, claude-code-mcp) from .claude-plugin/types/.+# Claude Code writes that folder when it LOADS the plugin and it is gitignored, so a fresh clone or a git worktree has none and tsc stops+# at TS2688 "Cannot find type definition file for 'claude-code'" before it checks anything. This copies the folder from where it exists+# (first hit wins): $CLAUDE_CONSOLE_TYPES, the main checkout of this repository, the newest installed copy of the plugin. It never+# overwrites a folder that is already there.+#+# scripts/typecheck.sh tsc over hooks, types and tests+# scripts/typecheck.sh --pretty extra arguments go to tsc+set -euo pipefail++PLUGIN="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"+DEST="$PLUGIN/.claude-plugin/types"+NEED=(claude-code claude-code-tools claude-code-mcp)++complete() { local d="$1" n; for n in "${NEED[@]}"; do [ -f "$d/$n/index.d.ts" ] || return 1; done; }++if ! complete "$DEST"; then+ candidates=()+ [ -n "${CLAUDE_CONSOLE_TYPES:-}" ] && candidates+=("$CLAUDE_CONSOLE_TYPES")+ common="$(git -C "$PLUGIN" rev-parse --path-format=absolute --git-common-dir 2>/dev/null || true)"+ [ -n "$common" ] && candidates+=("$(dirname "$common")/plugins/ruflo-console/.claude-plugin/types")+ while IFS= read -r installed; do candidates+=("$installed"); done < <(ls -dt "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"/plugins/cache/*/ruflo-console/*/.claude-plugin/types 2>/dev/null || true)++ found=""+ for c in "${candidates[@]}"; do+ if [ -d "$c" ] && [ "$(cd "$c" && pwd -P)" != "$DEST" ] && complete "$c"; then found="$c"; break; fi+ done++ if [ -z "$found" ]; then+ echo "typecheck: no .claude-plugin/types here and none to copy: load the plugin once in Claude Code, or set CLAUDE_CONSOLE_TYPES" >&2+ exit 2+ fi++ mkdir -p "$DEST"+ cp -rL "$found"/. "$DEST"/+ echo "typecheck: copied the ambient types from $found" >&2+fi++cd "$PLUGIN"+exec npx tsc --noEmit -p . "$@"diff --git a/plugins/ruflo-console/tests/anatole.spec.ts b/plugins/ruflo-console/tests/anatole.spec.tsindex 250ded2432..37592af31b 100644--- a/plugins/ruflo-console/tests/anatole.spec.ts+++ b/plugins/ruflo-console/tests/anatole.spec.ts@@ -154,7 +154,7 @@ describe('the section', () => {it('computes a rule row from the shipped table, its override and the alert tail', async () => {const { state } = await draw({ 'rules.json': JSON.stringify({ schemaVersion: 1, rules: { 'PR-001': { mode: 'notify' } } }), 'alerts.jsonl': alert({ rule: 'PR-001' }) })- const rows = ruleRows(state.snapshot!.anatole)+ const rows = ruleRows(state.snapshot!.anatole!)expect(rows).toHaveLength(13)expect(rows[0]).toMatchObject({ mode: 'notify', changed: true, hits: 1, ackedShare: 0 })diff --git a/plugins/ruflo-console/tests/ap-review.spec.ts b/plugins/ruflo-console/tests/ap-review.spec.tsindex 603ac6f5e7..7a110d0e84 100644--- a/plugins/ruflo-console/tests/ap-review.spec.ts+++ b/plugins/ruflo-console/tests/ap-review.spec.ts@@ -117,7 +117,7 @@ describe('stop is never undone', () => {const run = r.host.run- r.host.run = (async () => ({ exitCode: 1, stdout: '', stderr: 'no space left on device' })) as typeof r.host.run+ r.host.run = (async () => ({ exitCode: 1, stdout: '', stderr: 'no space left on device' })) as unknown as typeof r.host.runawait stopNow(state, r.host, 'disk is full')expect(r.toasts.join()).toContain('this session only')diff --git a/plugins/ruflo-console/tests/band.spec.ts b/plugins/ruflo-console/tests/band.spec.tsindex d08ed2baa4..4fc86d0aaf 100644--- a/plugins/ruflo-console/tests/band.spec.ts+++ b/plugins/ruflo-console/tests/band.spec.ts@@ -135,7 +135,7 @@ describe('band: a panel of two rows, standing facts that stay, and links', () =>state.events.push({ atMs: Date.now() - 300_000, kind: 'claims', text: 'claude: Bash' })// Narrow: the standing row uses its compact forms; nothing is cut in the middle of a word.- const panel = barView(kit, state, 70, null, () => undefined, () => undefined) as El+ const panel = barView(kit, state, 70, null, () => undefined, () => undefined) as unknown as Elconst [top, bottom] = panel.props.children as El[]const narrow = readable(bottom)@@ -156,7 +156,7 @@ describe('band: a panel of two rows, standing facts that stay, and links', () =>})it('is a bordered panel with a ground, in two rows', () => {- const panel = barView(kit, newState({}), 100, null, () => undefined, () => undefined) as El+ const panel = barView(kit, newState({}), 100, null, () => undefined, () => undefined) as unknown as Elexpect(panel.props).toMatchObject({ borderStyle: 'round', borderColor: PANEL.border, backgroundColor: PANEL.ground, flexDirection: 'column' })expect((panel.props.children as unknown[]).length).toBe(2)diff --git a/plugins/ruflo-console/tests/bench-guards.spec.ts b/plugins/ruflo-console/tests/bench-guards.spec.tsindex 1fa0271234..3cc63f39c1 100644--- a/plugins/ruflo-console/tests/bench-guards.spec.ts+++ b/plugins/ruflo-console/tests/bench-guards.spec.ts@@ -271,6 +271,9 @@ describe('the search panel on the page', () => {it('parses nothing for a frame with no query, and once for a query however often it is drawn again', async () => {const world = await worldOf(liveFiles())+ // The refresh has parsed the transcripts ahead of any frame (ADR-473): this guard is about a memo that has not, so it is emptied.+ expect(parsedStats().warmed).toBeGreaterThan(0)+ resetDrillIo()frame(world)frame(world)@@ -297,6 +300,25 @@ describe('the search panel on the page', () => {expect(resultOf(again.env, 'ls -la')).toBe(resultOf(again.env, 'ls -la'))click(again.tree, 'wf-hit-tool-0')})++ it('finds the transcripts a refresh parsed ahead already parsed: typing a query parses nothing new, and a redraw nothing either', async () => {+ const world = await worldOf(liveFiles())+ const warm = parsedStats()++ expect(warm.warmed).toBeGreaterThan(0)++ const idle = warm.parses++ frame(world)+ ;(inputOf(frame(world).tree)?.props.onInput as (v: string) => void)('ls -la')++ const drawn = frame(world)++ expect(parsedStats().parses).toBe(idle)+ expect(resultOf(drawn.env, 'ls -la').counts.tool).toBeGreaterThan(0)+ frame(world)+ expect(parsedStats().parses).toBe(idle)+ })})describe('search stops parsing where its cap stops scanning', () => {diff --git a/plugins/ruflo-console/tests/memmap.spec.ts b/plugins/ruflo-console/tests/memmap.spec.tsindex 0226ec30f5..494572d1c0 100644--- a/plugins/ruflo-console/tests/memmap.spec.ts+++ b/plugins/ruflo-console/tests/memmap.spec.ts@@ -223,7 +223,8 @@ describe('bounds', () => {describe('registration', () => {it('runs the memmap probe from the controller, so the read counts are not permanently n/a', async () => {const { readFileSync } = await import('node:fs')+ const { fileURLToPath } = await import('node:url')- expect(readFileSync(new URL('../hooks/controller.ts', import.meta.url), 'utf8')).toMatch(/ALL_PROBES = \[[^\]]*memmapProbe/)+ expect(readFileSync(fileURLToPath(new URL('../hooks/controller.ts', import.meta.url) as never), 'utf8')).toMatch(/ALL_PROBES = \[[^\]]*memmapProbe/)})})diff --git a/plugins/ruflo-console/tests/mission-cost.spec.ts b/plugins/ruflo-console/tests/mission-cost.spec.tsindex 886db6d27a..6716cfd28f 100644--- a/plugins/ruflo-console/tests/mission-cost.spec.ts+++ b/plugins/ruflo-console/tests/mission-cost.spec.ts@@ -112,7 +112,7 @@ const shown = (cost: ReturnType<typeof parseMissionCost>, cap: number | null, nodescribe('missionCostRows', () => {it('shows spend, cap and the ladder, and says it is an estimate', () => {- const lines = shown({ usd: 8, credits: null, unpriced: [], rows: 3 }, 10)+ const lines = shown({ usd: 8, credits: null, unpriced: [], rows: 3, fromMs: null }, 10)const all = lines.join('\n')expect(all).toContain('Mission spend')@@ -133,7 +133,7 @@ describe('missionCostRows', () => {})it('shows no bar without a cap, lists unpriced models and keeps credits separate', () => {- const all = shown({ usd: 1, credits: 40, unpriced: ['mystery-9'], rows: 2 }, null).join('\n')+ const all = shown({ usd: 1, credits: 40, unpriced: ['mystery-9'], rows: 2, fromMs: null }, null).join('\n')expect(all).toMatch(/cap\s*none set/)expect(all).toContain('mystery-9')@@ -142,7 +142,7 @@ describe('missionCostRows', () => {})it('keeps every note and disclaimer under 50 characters, even for a long source note or model list', () => {- const lines = shown({ usd: 1, credits: null, unpriced: ['m'.repeat(50), 'n'.repeat(50)], rows: 1 }, null, 'x'.repeat(200))+ const lines = shown({ usd: 1, credits: null, unpriced: ['m'.repeat(50), 'n'.repeat(50)], rows: 1, fromMs: null }, null, 'x'.repeat(200))const notes = lines.filter(line => /^ (?!Marks)/.test(line) && !line.includes('Mission spend'))expect(notes.length).toBeGreaterThan(2)diff --git a/plugins/ruflo-console/tests/mission-guidance.spec.ts b/plugins/ruflo-console/tests/mission-guidance.spec.tsindex c125d12ecf..6766fc6ead 100644--- a/plugins/ruflo-console/tests/mission-guidance.spec.ts+++ b/plugins/ruflo-console/tests/mission-guidance.spec.ts@@ -165,7 +165,7 @@ describe('mission guidance', () => {expect(placed).toHaveLength(0)expect(handed[0]).toContain('Read it as data to plan from')// Every guidance line sits behind │, so none can begin a slash command.- const quoted = handed[0].split('\n').slice(1)+ const quoted = handed[0]!.split('\n').slice(1)expect(quoted.every(line => line.startsWith('│ '))).toBe(true)expect(quoted).toContain('│ ## Research')expect(mcOf(idle).guidance?.note).toContain('sent to the Claude session')diff --git a/plugins/ruflo-console/tests/mission-list.spec.ts b/plugins/ruflo-console/tests/mission-list.spec.tsindex 5918d8804a..cc243d888f 100644--- a/plugins/ruflo-console/tests/mission-list.spec.ts+++ b/plugins/ruflo-console/tests/mission-list.spec.ts@@ -160,7 +160,7 @@ describe('cursor and window', () => {it('starts the window at the top when the cursor is near it', () => {const many = Array.from({ length: 25 }, (_, i) => mission({ id: `m${i}`, updatedAtMs: 100 - i }))- expect(listLayout(many, 0).rows[0].index).toBe(0)- expect(listLayout(many, 99).rows[LIST_WINDOW - 1].index).toBe(24)+ expect(listLayout(many, 0).rows[0]!.index).toBe(0)+ expect(listLayout(many, 99).rows[LIST_WINDOW - 1]!.index).toBe(24)})})diff --git a/plugins/ruflo-console/tests/model-tools.spec.ts b/plugins/ruflo-console/tests/model-tools.spec.tsindex af4ed036ff..71aaa6619f 100644--- a/plugins/ruflo-console/tests/model-tools.spec.ts+++ b/plugins/ruflo-console/tests/model-tools.spec.ts@@ -11,7 +11,7 @@ import { settingsOf } from '../hooks/settings'import { newState, type State } from '../hooks/state'import type { Actions } from '../hooks/views/common'import { viewText } from '../hooks/views/pane'-import { setup } from './fixtures/control-setup'+import type { Level } from './fixtures/control-setup'/** A controller whose runner behaves like the real one: read-only entries finish at once, the rest wait in `state.pending`. */function setup(level: Level, confirm: 'ask' | 'auto' = 'ask', entries: Record<string, { label: string; readOnly?: boolean; note?: string }> = {}, followUp?: { label: string; note?: string }) {diff --git a/plugins/ruflo-console/tests/result-display.test.ts b/plugins/ruflo-console/tests/result-display.test.tsindex 701a5851ec..889d6383a9 100644--- a/plugins/ruflo-console/tests/result-display.test.ts+++ b/plugins/ruflo-console/tests/result-display.test.ts@@ -43,9 +43,9 @@ describe('result display in the real engine', () => {expect(text).toContain('2 patterns shown, see neural train')expect(text).not.toContain('**2 patterns**')// And the result sits in one rounded frame, green because the run passed (the text surface does not draw borders, so the tree is checked).- const frames = elementsOf(tree, 'Box').filter(box => (box.props as { key?: string }).key === 'result-frame')+ const frames = elementsOf(tree, 'Box').filter(box => (box as unknown as { props: { key?: string } }).props.key === 'result-frame')expect(frames).toHaveLength(1)- expect(frames[0]?.props).toMatchObject({ borderStyle: 'round', borderColor: expect.stringMatching(/.+/) })+ expect((frames[0] as unknown as { props: object } | undefined)?.props).toMatchObject({ borderStyle: 'round', borderColor: expect.stringMatching(/.+/) })})})diff --git a/plugins/ruflo-console/tests/self-check.spec.ts b/plugins/ruflo-console/tests/self-check.spec.tsindex fc8f348dc9..23b6ad1bba 100644--- a/plugins/ruflo-console/tests/self-check.spec.ts+++ b/plugins/ruflo-console/tests/self-check.spec.ts@@ -72,25 +72,25 @@ describe('self-check: it fails on what is broken', () => {const broken = (change: (registries: Registries) => Registries) => selfCheck(change(REGISTRIES))it('a text verb that builds a command from an empty field', () => {- const results = broken(r => ({ ...r, secureText: [{ ...r.secureText[0], id: 'aid-bad', argv: () => ['security', 'defend'] }, ...r.secureText.slice(1)] }))+ const results = broken(r => ({ ...r, secureText: [{ ...r.secureText[0], id: 'aid-bad', argv: () => ['security', 'defend'] } as never, ...r.secureText.slice(1)] }))expect(area(results, 'Security')?.problems.join(' ')).toContain('aid-bad: an empty field must be refused')})it('a text verb that lets text starting with - through, where it could be read as a flag', () => {- const results = broken(r => ({ ...r, secureText: [{ ...r.secureText[0], id: 'aid-flag', argv: text => ['security', text] }, ...r.secureText.slice(1)] }))+ const results = broken(r => ({ ...r, secureText: [{ ...r.secureText[0], id: 'aid-flag', argv: (text: string) => ['security', text] } as never, ...r.secureText.slice(1)] }))expect(area(results, 'Security')?.problems.join(' ')).toContain('aid-flag: text starting with - must be refused')})it('a text verb that refuses every input, so its button could never run', () => {- const results = broken(r => ({ ...r, secureText: [{ ...r.secureText[0], id: 'aid-never', argv: () => null }, ...r.secureText.slice(1)] }))+ const results = broken(r => ({ ...r, secureText: [{ ...r.secureText[0], id: 'aid-never', argv: () => null } as never, ...r.secureText.slice(1)] }))expect(area(results, 'Security')?.problems.join(' ')).toContain('aid-never: no sample input')})it('a command with an empty part, and one with no reader', () => {- const results = broken(r => ({ ...r, perf: [{ ...r.perf[0], id: 'perf-empty', args: ['performance', ''] }, { ...r.perf[1], id: 'perf-noread', read: undefined as never }, ...r.perf.slice(2)] }))+ const results = broken(r => ({ ...r, perf: [{ ...r.perf[0], id: 'perf-empty', args: ['performance', ''] } as never, { ...r.perf[1], id: 'perf-noread', read: undefined as never } as never, ...r.perf.slice(2)] }))const problems = area(results, 'Performance')?.problems.join(' ') ?? ''expect(problems).toContain('perf-empty: its command is empty or has an empty')@@ -101,7 +101,7 @@ describe('self-check: it fails on what is broken', () => {const dev = REGISTRIES.dev.find(entry => entry.args !== undefined) as (typeof REGISTRIES.dev)[number]const results = broken(r => ({...r,- dev: [{ ...dev, id: 'dt-never', args: () => null }, { ...dev, id: 'dt-silent', input: undefined, args: fields => (fields.task === '' ? null : ['git', 'status']) }, { ...dev, id: 'dt-na', na: ' ', args: undefined }, ...r.dev],+ dev: [{ ...dev, id: 'dt-never', args: () => null } as never, { ...dev, id: 'dt-silent', input: undefined, args: (fields: Record<string, string>) => (fields.task === '' ? null : ['git', 'status']) } as never, { ...dev, id: 'dt-na', na: ' ', args: undefined } as never, ...r.dev],}))const problems = area(results, 'Dev Tools')?.problems.join(' ') ?? ''@@ -112,7 +112,7 @@ describe('self-check: it fails on what is broken', () => {it('a lab verb that cannot run and gives no reason, and one with nothing to run or type', () => {const lab = REGISTRIES.lab[0]- const results = broken(r => ({ ...r, lab: [{ ...lab, id: 'mh-mute', args: () => null, why: undefined }, { ...lab, id: 'mh-empty', args: undefined, types: undefined }, ...r.lab] }))+ const results = broken(r => ({ ...r, lab: [{ ...lab, id: 'mh-mute', args: () => null, why: undefined } as never, { ...lab, id: 'mh-empty', args: undefined, types: undefined } as never, ...r.lab] }))const problems = area(results, 'MetaHarness')?.problems.join(' ') ?? ''expect(problems).toContain('mh-mute: it cannot run now and says nothing about why')@@ -120,9 +120,9 @@ describe('self-check: it fails on what is broken', () => {})it('two entries sharing an id (a palette keyword), which fails each registry-owning area', () => {- const results = broken(r => ({ ...r, perf: [{ ...r.perf[0], id: r.secure[0].id }, ...r.perf.slice(1)] }))+ const results = broken(r => ({ ...r, perf: [{ ...r.perf[0], id: r.secure[0]?.id } as never, ...r.perf.slice(1)] }))- expect(area(results, 'Security')?.problems.join(' ')).toContain(`${REGISTRIES.secure[0].id}: used by two entries`)+ expect(area(results, 'Security')?.problems.join(' ')).toContain(`${REGISTRIES.secure[0]?.id}: used by two entries`)expect(area(results, 'Performance')?.ok).toBe(false)expect(area(results, 'Missions')?.ok).toBe(true)})diff --git a/plugins/ruflo-console/tests/version.spec.ts b/plugins/ruflo-console/tests/version.spec.tsindex 55388e7ad5..beda8be6ad 100644--- a/plugins/ruflo-console/tests/version.spec.ts+++ b/plugins/ruflo-console/tests/version.spec.ts@@ -22,7 +22,7 @@ const header = (): string => {describe('console version', () => {it('matches the plugin manifest, so the header shows the build that is running', () => {- const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../.claude-plugin/plugin.json', import.meta.url)), 'utf8')) as { version: string }+ const manifest = JSON.parse(readFileSync(fileURLToPath(new URL('../.claude-plugin/plugin.json', import.meta.url) as never), 'utf8')) as { version: string }expect(CONSOLE_VERSION).toBe(manifest.version)})diff --git a/plugins/ruflo-console/tests/wf-convo.spec.ts b/plugins/ruflo-console/tests/wf-convo.spec.tsindex 16a67a7d2b..418d06c2c1 100644--- a/plugins/ruflo-console/tests/wf-convo.spec.ts+++ b/plugins/ruflo-console/tests/wf-convo.spec.ts@@ -24,13 +24,13 @@ function deps(over: Partial<SendDeps> & { env?: string | null; httpReply?: { ok:cwd: '/work/proj',hive,config: parseConfig('endpoint:metallm=https://gw.example.com/v1|COG_KEY|cognitum-auto; bbs:ops; x:pub:team'),- run: async (argv, timeoutMs, stdin) => {+ run: (async (argv: readonly string[], timeoutMs: number, stdin?: string) => {rec.run.push({ argv, timeoutMs, ...(stdin !== undefined && { stdin }) })if (argv[0] === 'printenv') return over.env === null ? { exitCode: 1, stdout: '', stderr: '' } : { exitCode: 0, stdout: `${over.env ?? KEY}\n`, stderr: '' }return over.runReply?.(argv) ?? { exitCode: 0, stdout: 'Result:\n{"success":true}', stderr: '' }- },+ }) as unknown as SendDeps['run'],httpSend: async (url, init) => { rec.http.push({ url, init }); return over.httpReply ?? { ok: true, status: 200, text: JSON.stringify({ model: 'm', choices: [{ message: { content: 'an answer' } }], usage: { prompt_tokens: 12, completion_tokens: 5 } }) } },submitPrompt: async text => { rec.prompts.push(text) },toolCall: async input => { rec.tool.push(input); return { text: '{"success":true,"message":"Message queued for delivery to sleeper at its next tool round."}' } },diff --git a/plugins/ruflo-console/tests/wf-guide.spec.ts b/plugins/ruflo-console/tests/wf-guide.spec.tsindex ac70015990..e6f03ff38d 100644--- a/plugins/ruflo-console/tests/wf-guide.spec.ts+++ b/plugins/ruflo-console/tests/wf-guide.spec.ts@@ -208,7 +208,7 @@ describe('the slots', () => {return { state, ctx: { kit, state, nowMs: 1_000, columns: 120, pictures: new Map(), act }, asked }}const envOf = (ctx: Ctx, run: WfRun): SlotEnv => ({ ctx, runs: [run], run, phase: run.phases[0] ?? null, agent: run.phases[0]?.agents[0] ?? null, ui: { run: 0, phase: 0, agent: 0, column: 'agents', isInspecting: true }, nowMs: 1_000 })- const slot = <K extends 'board' | 'tab'>(kind: K, id: string) => slotsFor(kind).find(candidate => candidate.id === id) as never as { render: (env: SlotEnv) => unknown[]; when?: (env: SlotEnv) => boolean }+ const slot = <K extends 'board' | 'tab'>(kind: K, id: string) => slotsFor(kind).find(candidate => (candidate as unknown as { id: string }).id === id) as never as { render: (env: SlotEnv) => unknown[]; when?: (env: SlotEnv) => boolean }const ledger = (state: State): MissionRecord => {const mission = { id: 'm1', objective: 'Ship it', profile: 'feature', rigor: 'standard', tasks: [{ id: 'implement', title: 'Implement', phase: 'R', stage: 'Build', agent: 'coder', requirement: 'it works', dependsOn: [] }], acceptance: [], events: [], paused: false, cancelled: false, auto: false, createdAtMs: 0 } as MissionRecorddiff --git a/plugins/ruflo-console/tests/wf-incr.spec.ts b/plugins/ruflo-console/tests/wf-incr.spec.tsnew file mode 100644index 0000000000..db3b9621df--- /dev/null+++ b/plugins/ruflo-console/tests/wf-incr.spec.ts@@ -0,0 +1,454 @@+/**+ * The incremental transcript parsers against the reference ones (ADR-473). Seeded random transcripts are cut at random points (mid line,+ * mid escape, mid surrogate pair), fed in growing steps, truncated, rewritten and slid as a tail window; at every step the incremental answer+ * must equal what `parseTranscript` / `parseActivity` make of the same text. The reference parsers are not touched by this change and do not+ * share the state machine, so a wrong anchor, a lost carry or a miscounted ring shows as a different answer, not as a passing echo.+ */+import { describe, expect, it } from 'vitest'++import { ENTRY_CAP, parseActivity, type Parsed } from '../hooks/data/wf-activity'+import { ActivityIncr } from '../hooks/data/wf-incr-activity'+import { FactsIncr } from '../hooks/data/wf-incr'+import { LINE_CAP, parseTranscript } from '../hooks/data/workflows'++/** mulberry32: small, seeded, the same on every run. */+function rng(seed: number): () => number {+ let a = seed >>> 0++ return () => {+ a = (a + 0x6d2b79f5) >>> 0++ let t = a++ t = Math.imul(t ^ (t >>> 15), t | 1)+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)++ return ((t ^ (t >>> 14)) >>> 0) / 4294967296+ }+}++const TOOLS = ['Bash', 'Read', 'Edit', 'Write', 'MultiEdit', 'Grep', 'NotebookEdit']+const WORDS = ['alpha', 'beta', 'ls -la', 'cargo test', 'sk-ant-abcdefghijklmnopqrstu', '\u001b[31mred\u001b[0m', 'café', '\u{1F600} grin', 'tab\there', '‮evil', 'line one\nline two', 'x'.repeat(40)]++/** The lines of one random transcript, as the strings that go between newlines. `calls` are the ids a later result may name. */+function linesOf(seed: number, count: number): string[] {+ const rand = rng(seed)+ const pick = <T>(list: readonly T[]): T => list[Math.floor(rand() * list.length)] as T+ const out: string[] = []+ const ids: string[] = []+ let t = Date.parse('2026-10-06T00:00:00.000Z')+ let msg = 0++ for (let i = 0; i < count; i++) {+ t += Math.floor(rand() * 2000)++ const at = rand() < 0.9 ? { timestamp: new Date(t).toISOString() } : {}+ const roll = rand()++ if (roll < 0.3) {+ // An assistant line: usage, text or thinking, tool calls; a streamed message repeats its id (and its calls) on several lines.+ const id = rand() < 0.4 && msg > 0 ? `m${msg}` : `m${++msg}`+ const content: unknown[] = []++ if (rand() < 0.6) content.push({ type: 'text', text: pick(WORDS) })+ if (rand() < 0.15) content.push({ type: 'thinking', thinking: pick(WORDS) })++ for (let k = Math.floor(rand() * 3); k > 0; k--) {+ const callId = rand() < 0.25 && ids.length > 0 ? pick(ids) : `t${ids.length}-${i}`+ const tool = pick(TOOLS)++ if (!ids.includes(callId)) ids.push(callId)++ content.push({ type: 'tool_use', id: callId, name: tool, input: tool === 'Bash' ? { command: pick(WORDS), description: 'run' } : { file_path: `/w/src/f${Math.floor(rand() * 12)}.ts` } })+ }++ const usage = rand() < 0.85 ? { input_tokens: Math.floor(rand() * 9), cache_creation_input_tokens: Math.floor(rand() * 500), cache_read_input_tokens: Math.floor(rand() * 90_000), output_tokens: Math.floor(rand() * 400) } : undefined++ out.push(JSON.stringify({ type: 'assistant', ...at, message: { ...(rand() < 0.9 && { id }), model: pick(['claude-sonnet-5-5', 'claude-opus-5-5', 'claude-haiku-5']), role: 'assistant', content, ...(usage !== undefined && { usage }) } }))+ } else if (roll < 0.55) {+ // A user line carrying results: of a known call (early ones too), of an unknown id, an error, an empty one, an array of blocks.+ const target = rand() < 0.12 ? 'ghost-id' : ids.length > 0 ? pick(ids) : 'none'+ const content = rand() < 0.2 ? [{ type: 'text', text: pick(WORDS) }, { type: 'image' }] : rand() < 0.1 ? '' : pick(WORDS)++ out.push(JSON.stringify({ type: 'user', ...at, message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: target, content, ...(rand() < 0.2 && { is_error: true }) }] } }))+ } else if (roll < 0.68) out.push(JSON.stringify({ type: 'user', ...at, message: { role: 'user', content: pick(WORDS) } }))+ else if (roll < 0.74) out.push(JSON.stringify({ type: 'user', isMeta: true, ...at, message: { role: 'user', content: 'meta' } }))+ else if (roll < 0.8) out.push(JSON.stringify({ type: 'attachment', ...at }))+ else if (roll < 0.84) out.push('not json at all')+ else if (roll < 0.87) out.push('{"type":"user","message":{"content":"half')+ else if (roll < 0.9) out.push('[1,2,3]')+ else if (roll < 0.93) out.push('')+ else if (roll < 0.96) out.push(JSON.stringify({ type: 'summary', n: i }))+ else out.push(JSON.stringify({ type: 'user', ...at, message: { role: 'user', content: 'y'.repeat(7000) } }))+ }++ return out+}++/** The file text: lines joined by LF or CRLF, with or without a final newline. */+function textOf(lines: readonly string[], rand: () => number): string {+ const eol = rand() < 0.35 ? '\r\n' : '\n'+ const body = lines.join(eol)++ return rand() < 0.7 ? `${body}${eol}` : body+}++/** Increasing cut points, mostly small steps (a poll) and some big ones, at any character. */+function cuts(length: number, rand: () => number, step = 700): number[] {+ const out: number[] = []+ let at = 0++ while (at < length) {+ at = Math.min(length, at + 1 + Math.floor(rand() * (rand() < 0.2 ? step * 9 : step)))+ out.push(at)+ }++ return out+}++const factsOf = (text: string, isTail = false) => parseTranscript(text, isTail)++describe('incremental parsing equals the whole parse', () => {+ it.each(Array.from({ length: 24 }, (_, i) => i + 1))('seed %i: a whole text grown at random cut points, facts and activity at every step', seed => {+ const rand = rng(seed * 7919)+ const lines = linesOf(seed, 30 + Math.floor(rand() * 200))+ const text = textOf(lines, rand)+ const facts = new FactsIncr()+ const act = new ActivityIncr()+ let resumed = 0+ let fedTotal = 0+ let steps = 0++ for (const at of cuts(text.length, rand)) {+ const part = text.slice(0, at)+ const f = facts.update(part, false)+ const a = act.update(part, false)++ expect(f.value).toEqual(factsOf(part))+ expect(a.value).toEqual(parseActivity(part))++ steps += 1+ fedTotal += a.fed+ if (a.how === 'resumed') resumed += 1+ }++ // The point of it: most steps carried on from the last one, and the characters parsed in all stayed near the text's own length.+ expect(resumed).toBeGreaterThanOrEqual(Math.floor(steps / 2))+ // (a line cut mid-way is looked at again when it finishes: at most one line, about 7 KB here, per step)+ expect(fedTotal).toBeLessThan(text.length * 1.6 + steps * 7500)+ })++ it('beyond the entry ring: calls and their results that left it, dropped counts, re-indexed positions', () => {+ const rand = rng(99)+ const lines = linesOf(5, ENTRY_CAP * 2 + 400)+ const text = textOf(lines, rand)+ const act = new ActivityIncr()+ const facts = new FactsIncr()+ let last: Parsed | null = null++ for (const at of cuts(text.length, rand, text.length / 14)) {+ const part = text.slice(0, at)++ last = act.update(part, false).value+ expect(last).toEqual(parseActivity(part))+ expect(facts.update(part, false).value).toEqual(factsOf(part))+ }++ expect((last as Parsed).dropped).toBeGreaterThan(0)+ expect((last as Parsed).entries.length).toBe(ENTRY_CAP)+ })++ it('a result for a call that already left the ring is absorbed, not turned into a message', () => {+ const call = (id: string): string => JSON.stringify({ type: 'assistant', message: { id, content: [{ type: 'tool_use', id, name: 'Bash', input: { command: 'ls' } }] } })+ const filler = Array.from({ length: ENTRY_CAP + 50 }, (_, i) => JSON.stringify({ type: 'user', message: { content: `note ${i}` } }))+ const result = JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'early', content: 'done' }] } })+ const head = `${[call('early'), ...filler].join('\n')}\n`+ const whole = `${head}${result}\n`+ const act = new ActivityIncr()++ act.update(head, false)++ const grown = act.update(whole, false)++ expect(grown.how).toBe('resumed')+ expect(grown.value).toEqual(parseActivity(whole))+ expect(grown.value.entries.some(entry => entry.kind === 'message' && entry.role === 'result')).toBe(false)+ })++ it('a text cut shorter, rewritten or replaced is parsed whole, and still equals the whole parse', () => {+ const rand = rng(31)+ const a = textOf(linesOf(1, 120), rand)+ const b = textOf(linesOf(2, 140), rand)+ const act = new ActivityIncr()+ const facts = new FactsIncr()+ const steps = [a, a.slice(0, Math.floor(a.length / 2)), a, `${a}${b}`, b, b.slice(0, 10), b, `${b.slice(0, 600)}X${b.slice(601)}`, '', a]+ const how: string[] = []++ for (const text of steps) {+ const r = act.update(text, false)++ how.push(r.how)+ expect(r.value).toEqual(parseActivity(text))+ expect(facts.update(text, false).value).toEqual(factsOf(text))+ }++ expect(how).toContain('fresh')+ expect(how).toContain('resumed')+ })++ it('an edit before the point already parsed is not carried over: in the first characters, or in the text just before it', () => {+ const line = (content: string): string => JSON.stringify({ type: 'user', message: { content } })+ const body = Array.from({ length: 70 }, (_, i) => line(`note ${i} ${'q'.repeat(80)}`))+ const a = `${[line('HEADHEAD'), ...body, line('TAILTAIL')].join('\n')}\n`+ const more = `${line('later')}\n`++ expect(a.length).toBeGreaterThan(6000)++ for (const edited of [a.replace('HEADHEAD', 'headhead'), a.replace('TAILTAIL', 'tailtail')]) {+ const act = new ActivityIncr()+ const facts = new FactsIncr()++ act.update(a, false)+ facts.update(a, false)++ const next = act.update(`${edited}${more}`, false)++ expect(next.how).toBe('fresh')+ expect(next.value).toEqual(parseActivity(`${edited}${more}`))+ expect(facts.update(`${edited}${more}`, false).value).toEqual(factsOf(`${edited}${more}`))+ }+ })++ it('an unfinished last line that is taken back leaves no trace: a result, a file, a skipped line, a message', () => {+ const call = JSON.stringify({ type: 'assistant', message: { id: 'm1', model: 'claude-sonnet-5-5', usage: { output_tokens: 3 }, content: [{ type: 'tool_use', id: 't1', name: 'Read', input: { file_path: '/w/a.ts' } }] } })+ const pending = [+ JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok', is_error: true }] } }),+ JSON.stringify({ type: 'assistant', message: { id: 'm2', usage: { output_tokens: 9 }, content: [{ type: 'tool_use', id: 't2', name: 'Edit', input: { file_path: '/w/b.ts' } }, { type: 'text', text: 'hi' }] } }),+ JSON.stringify({ type: 'attachment' }),+ JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't2', content: 'late' }] } }),+ ]++ for (const last of pending) {+ const act = new ActivityIncr()+ const facts = new FactsIncr()+ const head = `${call}\n`+ const replaced = `${head}${JSON.stringify({ type: 'user', message: { content: 'something else' } })}\n`++ for (const text of [`${head}${last}`, replaced, `${head}${last}`, `${head}${last}\n`]) {+ expect(act.update(text, false).value).toEqual(parseActivity(text))+ expect(facts.update(text, false).value).toEqual(factsOf(text))+ }+ }+ })++ it('an unfinished last line that would push the ring over its cap still counts what it pushes out', () => {+ const line = (i: number): string => JSON.stringify({ type: 'user', message: { content: `note ${i}` } })+ const full = Array.from({ length: ENTRY_CAP + 5 }, (_, i) => line(i)).join('\n')+ const text = `${full}\n${line(9999)}`+ const act = new ActivityIncr()++ act.update(`${full}\n`, false)++ const grown = act.update(text, false)++ expect(grown.value).toEqual(parseActivity(text))+ expect(grown.value.dropped).toBe(6)+ })++ it('a text cut shorter than what was parsed is parsed whole', () => {+ const line = JSON.stringify({ type: 'user', message: { content: 'x'.repeat(200) } })+ const a = `${Array.from({ length: 40 }, () => line).join('\n')}\n`+ const act = new ActivityIncr()++ act.update(a, false)++ const cut = act.update(a.slice(0, 3000), false)++ expect(cut.how).toBe('fresh')+ expect(cut.value).toEqual(parseActivity(a.slice(0, 3000)))+ })++ it('an unfinished last line is counted when it parses, and counted once when its newline arrives', () => {+ const a = JSON.stringify({ type: 'assistant', message: { id: 'm1', model: 'claude-sonnet-5-5', usage: { input_tokens: 1, output_tokens: 2 }, content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: { command: 'ls' } }] } })+ const r = JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] } })+ const act = new ActivityIncr()+ const facts = new FactsIncr()++ for (const text of [`${a}\n${r.slice(0, 20)}`, `${a}\n${r}`, `${a}\n${r}\n`, `${a}\n${r}\n${a}`, `${a}\n${r}\n${a}\n`]) {+ expect(act.update(text, false).value).toEqual(parseActivity(text))+ expect(facts.update(text, false).value).toEqual(factsOf(text))+ }+ })++ it('a line over the line cap is not read, by the reference and the incremental alike', () => {+ const big = JSON.stringify({ type: 'user', message: { content: 'z'.repeat(LINE_CAP + 10) } })+ const small = JSON.stringify({ type: 'user', message: { content: 'after' } })+ const text = `${small}\n${big}\n${small}\n`+ const act = new ActivityIncr()++ expect(act.update(text.slice(0, text.length - 5), false).value).toEqual(parseActivity(text.slice(0, text.length - 5)))+ expect(act.update(text, false).value).toEqual(parseActivity(text))+ expect(act.update(text, false).value.entries.length).toBe(2)+ })+})++describe('a tail window that slides over a growing file', () => {+ /** The reference for a state started in one window: the whole parse of the file from the first line that window held complete. */+ const refFrom = (file: string, windowStart: number): { text: string } => {+ const first = file.indexOf('\n', windowStart)++ return { text: first < 0 ? file.slice(windowStart) : file.slice(first + 1) }+ }++ it.each(Array.from({ length: 16 }, (_, i) => i + 1))('seed %i: windows of a growing file equal the whole parse from the first line of the first window', seed => {+ const rand = rng(seed * 104729)+ const file = textOf(linesOf(seed + 500, 150 + Math.floor(rand() * 250)), rand)+ const win = 1500 + Math.floor(rand() * 9000)+ const act = new ActivityIncr()+ const facts = new FactsIncr()+ let start = 0+ let resumed = 0+ let steps = 0++ for (const at of cuts(file.length, rand)) {+ const from = Math.max(0, at - win)+ const part = file.slice(from, at)+ const a = act.update(part, true, String(at))+ const f = facts.update(part, true, String(at))+ void f++ // A fresh start anchors the reference at this window; a resumed one keeps the anchor of the window it began in.+ if (a.how === 'fresh') start = from++ const ref = refFrom(file.slice(0, at), start).text+ const whole = file.slice(0, at).indexOf('\n', start) < 0++ if (!whole) {+ expect(a.value).toEqual({ ...parseActivity(ref, false), isTail: true })+ }++ steps += 1+ if (a.how === 'resumed') resumed += 1+ }++ expect(resumed).toBeGreaterThan(0)+ expect(steps).toBeGreaterThan(1)+ })++ it('facts: a tail state agrees with the whole parse of the file from its anchor', () => {+ const rand = rng(8)+ const file = textOf(linesOf(77, 300), rand)+ const facts = new FactsIncr()+ let start = 0++ for (const at of cuts(file.length, rand)) {+ const from = Math.max(0, at - 6000)+ const part = file.slice(from, at)+ const f = facts.update(part, true, String(at))++ if (f.how === 'fresh') start = from++ const first = file.slice(0, at).indexOf('\n', start)++ if (first >= 0) expect(f.value).toEqual(parseTranscript(file.slice(first + 1, at), false))+ }+ })++ it('a window that slid past the anchor is parsed whole, never guessed', () => {+ const file = textOf(linesOf(3, 300), rng(3))+ const act = new ActivityIncr()++ act.update(file.slice(0, 5000), true)++ const far = act.update(file.slice(file.length - 5000), true)++ expect(far.how).toBe('fresh')+ })++ it('an ambiguous anchor (the same text twice in the window) is parsed whole', () => {+ const line = `${JSON.stringify({ type: 'user', message: { content: 'same'.repeat(300) } })}\n`+ const text = `torn start\n${line.repeat(8)}`+ const act = new ActivityIncr()++ act.update(text, true)++ expect(act.update(`${text}${line}`, true).how).toBe('fresh')+ })+})++describe('through the readers', () => {+ const T = Date.parse('2026-10-06T01:30:00.000Z')+ const assistant = (n: number): string => JSON.stringify({ type: 'assistant', timestamp: new Date(T + n * 1000).toISOString(), message: { id: `g${n}`, model: 'claude-sonnet-5-5', role: 'assistant', content: [{ type: 'text', text: `step ${n}` }, { type: 'tool_use', id: `u${n}`, name: 'Bash', input: { command: `echo ${n}` } }], usage: { input_tokens: 1, cache_creation_input_tokens: 10, cache_read_input_tokens: 1000 + n, output_tokens: 5 } } })++ it('a transcript that grew between two refreshes: the agent figures and the parsed activity equal a whole parse, and the second parse read only the new lines', async () => {+ const { readWorkflowRuns } = await import('../hooks/data/workflows-read')+ const { parsedOf, resetDrillIo } = await import('../hooks/data/wf-drill-io')+ const { parsedStats } = await import('../hooks/data/wf-incr-store')+ const world = await import('./fixtures/wf-drill-world')++ resetDrillIo()++ const path = `${world.RUN}/agent-a1.jsonl`+ const files = world.liveFiles({ [path]: `${Array.from({ length: 400 }, (_, i) => assistant(i)).join('\n')}\n` })+ const cache = new Map()+ const read = () => readWorkflowRuns(world.memoryFs(files), cache, { configDir: world.CONFIG, cwd: '/work/proj', nowMs: world.NOW })+ const first = await read()+ const agent = () => first.runs[0]?.phases.flatMap(p => p.agents).find(a => a.id === 'a1') as NonNullable<(typeof first.runs)[0]>['phases'][0]['agents'][0]++ expect(parsedOf(cache, agent())).toEqual(parseActivity(files[path] as string))++ const before = parsedStats()++ files[path] = `${files[path]}${assistant(400)}\n${assistant(401)}\n`++ const grown = await read()+ const grownAgent = grown.runs[0]?.phases.flatMap(p => p.agents).find(a => a.id === 'a1')++ expect(grownAgent).toMatchObject({ tokens: 1 + 10 + 1401 + 5, toolCalls: 402 })+ expect(parseTranscript(files[path] as string)).toMatchObject({ tokens: grownAgent?.tokens, toolCalls: grownAgent?.toolCalls })+ expect(parsedOf(cache, agent())).toEqual(parseActivity(files[path] as string))++ const after = parsedStats()++ // Two refreshes' worth of new lines were parsed for the activity (by the warm-up), not the 400 before them.+ expect(after.resumed).toBeGreaterThan(before.resumed)+ expect(after.fed - before.fed).toBeLessThan((files[path] as string).length / 10)+ })+ it('a tail-read transcript that grew: the facts are those of the whole text from the first complete line of the first window', async () => {+ const { readWorkflowRuns, TRANSCRIPT_CAP } = await import('../hooks/data/workflows-read')+ const { resetDrillIo } = await import('../hooks/data/wf-drill-io')+ const world = await import('./fixtures/wf-drill-world')++ resetDrillIo()++ const path = `${world.RUN}/agent-a1.jsonl`+ const lines = Array.from({ length: 500 }, (_, i) => assistant(i))+ const files = world.liveFiles()+ const textTo = (n: number): string => `${lines.slice(0, n).join('\n')}\n`+ const window = (text: string): string => text.slice(Math.max(0, text.length - 9000))+ const cache = new Map()+ const seen: { tokens?: number; toolCalls?: number }[] = []+ let first = ''++ for (let n = 200; n <= 424; n += 8) {+ files[path] = textTo(n)++ const size = TRANSCRIPT_CAP + files[path].length+ const mem = world.memoryFs(files, { size: { [path]: size } })+ const fs = { ...mem, list: async (dir: string) => (await mem.list(dir)).map(e => (`${dir}/${e.name}` === path ? { ...e, size } : e)), readTail: async () => window(files[path] as string) }+ const found = await readWorkflowRuns(fs, cache, { configDir: world.CONFIG, cwd: '/work/proj', nowMs: world.NOW })+ const agent = found.runs[0]?.phases.flatMap(p => p.agents).find(a => a.id === 'a1')++ if (first === '') first = window(files[path] as string)++ seen.push({ ...(agent?.tokens !== undefined && { tokens: agent.tokens }), ...(agent?.toolCalls !== undefined && { toolCalls: agent.toolCalls }) })+ }++ // Every window slid forward by less than itself, so the state carried on from the first: it knows every call since that window's first line.+ const startOfFirst = textTo(200).length - first.length+ const from = textTo(424).indexOf('\n', startOfFirst) + 1+ const reference = parseTranscript(textTo(424).slice(from))++ expect(seen.at(-1)).toMatchObject({ tokens: reference.tokens, toolCalls: reference.toolCalls })+ })+})diff --git a/plugins/ruflo-console/tests/wf-saved.spec.ts b/plugins/ruflo-console/tests/wf-saved.spec.tsindex 9ea6e6d7f1..49b47e753b 100644--- a/plugins/ruflo-console/tests/wf-saved.spec.ts+++ b/plugins/ruflo-console/tests/wf-saved.spec.ts@@ -151,7 +151,7 @@ describe('live: load, restore, write', () => {list: async () => [],}const host = { fs, run: async (argv: readonly string[], _t: number, stdin?: string) => (writes.push({ argv, stdin }), { exitCode: exit, stdout: '', stderr: '' }) } as never- const state = newState()+ const state = newState({})state.cwd = CWDstate.view = 'workflows'diff --git a/plugins/ruflo-console/tests/wf-wire.spec.ts b/plugins/ruflo-console/tests/wf-wire.spec.tsindex 3590c9ace6..d7796b0488 100644--- a/plugins/ruflo-console/tests/wf-wire.spec.ts+++ b/plugins/ruflo-console/tests/wf-wire.spec.ts@@ -267,7 +267,7 @@ describe('the keys', () => {for (const key of ['p', 'x', 'r', 'h', 'y', 'n']) expect(hotkeys, `hotkey ${key}`).not.toContain(key)expect(new Set(buttons(tree).map(el => el.props.key)).size).toBe(buttons(tree).length)// Pressing a button moves the cursor.- buttonOf(tree, 'wf-col-agents')?.props.onPress?.call(undefined)+ ;(buttonOf(tree, 'wf-col-agents')?.props.onPress as (() => void) | undefined)?.()expect(world.state.wf.ui.column).toBe('agents')})@@ -346,7 +346,7 @@ describe('the page', () => {expect(words(first.tree)).toMatch(/extra for/)expect(words(first.tree)).toMatch(/slot bad failed: exploded/)expect(buttonOf(first.tree, 'wf-key-mark')?.props.hotkey).toBe('m')- buttonOf(first.tree, 'wf-act-act')?.props.onPress?.call(undefined)+ ;(buttonOf(first.tree, 'wf-act-act')?.props.onPress as (() => void) | undefined)?.()expect(asked).toEqual([{ spec, why: 'nothing to do' }])// The tab shows only while the inspector is open.expect(buttonOf(first.tree, 'wf-tab-cost')).toBeUndefined()@@ -356,7 +356,7 @@ describe('the page', () => {const open = pageOf(world.state, world.host)expect(buttonOf(open.tree, 'wf-tab-cost')).toBeDefined()- buttonOf(open.tree, 'wf-tab-cost')?.props.onPress?.call(undefined)+ ;(buttonOf(open.tree, 'wf-tab-cost')?.props.onPress as (() => void) | undefined)?.()expect(words(pageOf(world.state, world.host).tree)).toMatch(/tab body/)expect(world.state.wf.tab).toBe('cost')workflowsActions(world.state, world.host, {} as never).tab('nope')diff --git a/plugins/ruflo-console/tsconfig.json b/plugins/ruflo-console/tsconfig.jsonindex 1e3839a1be..3bb82d63d4 100644--- a/plugins/ruflo-console/tsconfig.json+++ b/plugins/ruflo-console/tsconfig.json@@ -1,5 +1,5 @@{- "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) on load or validate; tsc -p . then reads them through typeRoots.",+ "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) when it LOADS the plugin (`claude plugin validate` does not); tsc -p . then reads them through typeRoots. A fresh clone or worktree has none and tsc stops at TS2688: scripts/typecheck.sh copies them from the main checkout, then runs tsc.","compilerOptions": {"target": "es2023","lib": ["es2023"],diff --git a/v3/docs/adr/ADR-473-console-incremental-transcripts.md b/v3/docs/adr/ADR-473-console-incremental-transcripts.mdnew file mode 100644index 0000000000..13d01f351b--- /dev/null+++ b/v3/docs/adr/ADR-473-console-incremental-transcripts.md@@ -0,0 +1,124 @@+# ADR 473: Console: a transcript that grew is parsed from where it ended, not from its first line++Status: Accepted++Date: 2026-10-06++Builds on: ADR-458 (workflows reader), ADR-459 (drill and search), ADR-468 (the first bench pass)++## 1. Context++ADR-468 made an unchanged transcript free (size and mtime say "unchanged", the parse is kept) but a transcript that changed was parsed again from+its first line: a live agent appends lines every few seconds, so every refresh of a busy run re-parsed megabytes to learn about a few kilobytes.+The search had the same shape: its first draw after the first typed query parsed every transcript it scans (the memo was empty), 330 to 590 ms+on the 6 runs x 60 agents x 400 KB bench project, and nothing could make that cheaper because there was nothing to resume from.++What the host can do bounds the fix. The engine's `$.fs` has `read` (whole file, rejected over 4 MiB), `list`, `stat`, `exists` and `write`:+no read from an offset, no tail read. `readTail` exists only on the console's own test and bench file systems. So today a transcript over 3 MB+is not read at all, and a smaller one is read whole. What can be saved on every host is the parse (the larger cost: 34 ms of a 3 MB refresh is+parsing, the read is a memcpy). What can be saved in bytes read is only where a host offers `readTail`. This ADR makes the parse incremental on+every host and says plainly that the read is incremental only there.++## 2. Decision++**A parse state per transcript** (`hooks/data/wf-incr.ts`, `wf-incr-activity.ts`): how far the text was consumed (always just after a newline),+a short anchor of the text before that point, the first 512 characters, and the running figures. Two folds share it: `FactsIncr` (tokens, tool+calls, first and last timestamps, model: what `parseTranscript` answers) and `ActivityIncr` (the entry ring, calls paired with results, touched+files: what `parseActivity` answers).++**Resuming is checked, never assumed.** A new text continues the old one when, for a whole file, its first characters match the old first+characters and the text just before the consumed point matches the anchor; for a tail window (which slides), when the anchor is found exactly+once in it and is at least 1024 characters long. Anything else (truncation, a rewrite, a window that slid past the anchor, an ambiguous match, a+different `tag` for the same bytes) is parsed whole. The fallback is always a full parse, never a guess. Same text and tag is the held answer.++**An unfinished last line is parsed for the answer and not committed**: the fold applies it, builds the answer, and takes it back (an undo log+over the ring, the id map, the files and the result it touched), so the next call sees that line again, finished, and it is counted once.++**Bounded.** The ring keeps the newest 2000 entries as before; the ids of calls that left it are kept (50,000, oldest first) so a late result for+one is absorbed as the whole-text parse absorbs it, not turned into a message. The memo is bounded by the text it holds (24 M characters), oldest+state out, as before. `LINE_CAP` (3,000,000 characters, the read cap) is shared by `jsonLines` and the incremental scan: a longer line is not read.++**The reference parsers are untouched** and are the oracle in `tests/wf-incr.spec.ts`: the incremental code is written beside them, not under+them, so a test that compares the two can fail. Only `jsonLines` gained the line cap, and `str`/`num` and a few activity helpers were exported.++**Wiring.** `data/workflows-read.ts` keeps a `FactsIncr` per path (the folder reader). `data/wf-drill-io.ts`'s `parsedOf` goes through+`data/wf-incr-store.ts`, which keeps an `ActivityIncr` per path under the old memo budget and the old `parsedStats()` (plus `resumed`, `fed`,+`warmed`). A tail read carries a tag (size and mtime) so two windows that read the same at different places are told apart.++**Warm-up for the search.** After each refresh, `workflows-read.ts` parses the transcripts it just read, in the order the search walks them (live+runs first, then each run's phases and agents), up to 400,000 characters a refresh (about 10 ms, inside a frame) and up to the memo's budget, so+the first draw after a typed query finds them parsed. The warm-up never parses a tail and is not counted in `parsedStats().parses`+(`warmed` counts it). This changes what `bench-guards.spec.ts` asserts: typing no longer parses more than an idle frame, because the refresh+already did; the old assertion now runs on an emptied memo, and a new one holds the warm case.++Not done, with the reason: `usageOfTranscript` (the cost read, `data/wf-cost.ts`) is called from `wf-cost-live.ts`, which another lane owns, and it+re-reads and re-parses on a size/mtime signature there. An incremental usage fold belongs next to that call; it is a follow-on.++## 3. Evidence++`tests/wf-incr.spec.ts` (54 tests): seeded random transcripts (assistant lines with usage and tool calls, streamed repeats, results for known,+early, unknown and evicted calls, errors, thinking, meta and attachment lines, junk, half lines, non-objects, CRLF and LF, astral characters and+escape sequences, 7,000-character lines), cut at random characters and grown step by step, for facts and activity, each step equal (`toEqual`)+to `parseTranscript` / `parseActivity` of the same text; the same past the entry ring (4,400 lines); truncation, rewrite and replacement;+an unfinished line taken back; a line over the cap; tail windows sliding over a growing file, compared with the whole parse of the file from the+first complete line of the first window (what a tail state means: it also knows the lines of the windows before this one). Through the readers: a+transcript that grew between two refreshes, and a tail-read one.++Mutations (19 mutants of the two source files, each applied alone and the spec run): anchor+compare skipped, head compare skipped, truncation guard removed, tail ambiguity check removed, tail minimum anchor removed, partial line consumed,+unfinished line never taken back, `same` ignoring the tag, facts line number not advanced, evicted ids forgotten, `dropped` ignoring ring overflow,+dedupe by id removed, `callIndex` not made relative, calls dropped from the ring not counted, and the undo of a result, of a status, of a message and+of the files, and the skipped count. All are dead now; the first pass left six alive, and what killed each is worth saying:++- anchor compare, head compare: a new test edits a character in the first 512 characters, and one in the text just before the parsed point, and+ appends (the resume must be refused).+- truncation guard: an equivalent mutant (the anchor compare already refuses a text shorter than the parsed point), so the redundant guard was removed+ from the source and a test that cuts a text shorter was added.+- `dropped` ignoring ring overflow: a new test with an unfinished last line that pushes the full ring over its cap.+- facts line number: `index = usage.size` is equivalent in its output (the key it makes is just as unique), so the mutant was replaced by+ `index = 0`, which the property test kills.+- undo of a result and of a status: these survived a second time, and the cause was a real defect, not a missing test: the cursor's head covered the+ unfinished last line, so any text under 512 characters never resumed (it re-parsed whole each time). The head now covers the committed part only;+ a new test that takes a pending result back then kills both mutants.+- partial line consumed: an infinite loop (the scan never advances past an unterminated line), killed by the runner's timeout, counted as killed.++`scripts/bench-workflows.mjs` (median ms, one host, node 22, load average ~30 so absolute numbers are noisy; BEFORE is the same script on+`origin/main` f1c52f70f, AFTER on this branch, every answer digest-compared):++| Case | Before | After |+|---|---|---|+| 50 lines appended to a 3 MB transcript (read whole), activity | 37-39 ms (whole parse) | 0.37 ms (19,584 characters parsed), answers identical to the whole parse at every step |+| the same, facts | 17-19 ms | 0.09 ms |+| 50 lines appended to a 5 MB transcript (400 KB tail window), activity / facts | 3.9-6.8 / 1.7-3.2 ms | 0.35-0.61 / 0.13-0.25 ms |+| the same, 50 MB | 3.7-4.5 / 1.5-2.1 ms | 0.58 / 0.17 ms |+| tail state against the whole parse of the 5 MB and 50 MB files from its anchor | n/a | identical |+| refresh at 200 runs on disk (newest 6 with 8 transcripts of 2.4 MB), one transcript grew by 50 lines | 16-17 ms | 1.8-3.6 ms |+| the same, unchanged (settled) | 0.65-0.75 ms | 0.46-0.55 ms |+| first draw of a typed search, project that fits the memo (120 transcripts, 12 M characters): memo cold | 112-141 ms | 112-141 ms (nothing to resume from) |+| the same, memo warmed by 40 refreshes | 112 ms, 120 parses | 6.2 ms, 0 parses on the frame |+| the same on 6 runs x 60 agents x 400 KB (its search scans 31 M characters, over the 24 M memo): cold / warmed by 100 refreshes | 355-465 / 347-412 ms | 355-590 / 102-141 ms (59 of the 78 transcripts parsed ahead; 19 still parse on the frame) |+| a warm-up tick (it comes on top of a refresh) | n/a | median 4-12 ms, slowest 12-22 ms |++`--check` holds budgets for the new cases (activity append 8 ms, facts 5 ms, the 200-run refresh with an append 40 ms, a warmed first draw 16 ms, a warm-up+tick 60 ms); the digests of the existing cases are unchanged. While the warm-up is working (the first minutes after a page opens, about one 400 KB+transcript a refresh) a refresh costs the warm-up on top; once the memo is full or the transcripts are current it costs what it did before.++## 4. Consequences++- A busy run's refresh costs the new lines, not the file: 37 ms to 0.4 ms for 50 lines onto 3 MB.+- The first search of a page left open is 15x faster on a project that fits the memo; a cold one (typed before any refresh) still pays the parse, and a+ project whose search scans more than the 24 M memo holds still parses the rest on the frame. The memo budget is not changed here.+- A tail state carries the history of earlier windows (more calls counted than a fresh window would), and says so only through this ADR.+- On the real engine nothing is read less: only the parse is. A host with a ranged read would also save the bytes.+- A state costs its ring (up to 2000 entries) and a copy of them in the answer while a transcript is held; the memo budget counts the text only.++## 5. Companions in this change++- `scripts/kit-seq.sh` runs the 25 kit tests one file at a time with `claude plugin test` in a temp COPY of the plugin (the CLI refuses a+ symlinked tree as path traversal): hooks, catalog, types, tsconfig, plugin.json and the test fixtures are copied, one `*.test.ts` is swapped in+ at a time, and the directory is removed on exit. Run all at once at load average 30+, 3 to 8 view tests exceed their own 5 s limits; one at a+ time they do not. It prints a line per file and a total, and exits 1 on any failure.+- `scripts/typecheck.sh`: `tsc -p` stops at TS2688 in a fresh clone or worktree because `.claude-plugin/types/` (written by Claude Code when it+ loads the plugin, gitignored on purpose: early access, regenerated per release) is not there. The script copies it from the main checkout or the+ installed plugin when missing, then runs tsc. With it, the specs type-check; six errors remain in sources owned by other lanes (listed in the+ change's report).