Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

feat(console): Workflows drill-down (ADR-459): levels, activity, log, files, result, cross-level search

ruv604dfa9932fb
diff --git a/plugins/ruflo-console/hooks/data/wf-activity.ts b/plugins/ruflo-console/hooks/data/wf-activity.ts
new file mode 100644
index 0000000000..0accd90d4d
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-activity.ts
@@ -0,0 +1,214 @@
+/**
+ * What an agent's transcript says it did (ADR-459): the tool-call timeline (a call paired with its result by id), the messages between
+ * them, the files its tool inputs name, and the structured result the run's journal kept for it. Pure: text in, records out; the
+ * reading of files is data/wf-drill-io.ts. Nothing is estimated: a call whose result is not in the text read stays `pending`, a field
+ * longer than its cap is cut and says so, and a line that does not parse is dropped, never thrown on.
+ *
+ * Every string kept is washed on the way in (an ANSI sequence or control character is removed, anything shaped like a credential is
+ * masked) so no cell, log line, export or notice built from these records can carry one. Newlines survive, so an input or an output
+ * still reads as the lines it was; ids and paths are not masked (a 36 character session id would read as a key to the mask).
+ */
+import { maskSecrets, jsonLines } from './workflows'
+
+/** Characters kept per field (an input, an output, a message). The page shows how many of how many, never a silent cut. */
+export const FIELD_CAP = 6000
+/** Entries kept per transcript: the newest, with the count of earlier ones said. */
+export const ENTRY_CAP = 2000
+export const FILE_CAP = 120
+
+export type Capped = { text: string; /** Characters in the original. */ total: number; isCut: boolean }
+
+// An escape sequence goes whole (stripping only the ESC byte would leave `[1m` in the text), then controls other than the newline, soft hyphen,
+// zero-width and bidi characters. Written as \u escapes so no invisible character sits in this source.
+const ANSI = new RegExp('\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)|\\u009d[^\\u0007\\u009c]*[\\u0007\\u009c]|(?:\\u001b\\[|\\u009b)[0-9;?]*[ -/]*[@-~]', 'g')
+const HIDE = new RegExp('[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2064\\u2066-\\u2069\\ufeff]', 'g')
+
+/** Washed text for a block: escapes and controls out (the newline stays), credentials masked, cut to `cap` characters with the original length kept. */
+export function cleanBlock(raw: string, cap = FIELD_CAP): Capped {
+ // The mask runs over a little more than the cap, so a token that straddles the cut is masked whole before the cut is made.
+ const head = raw.slice(0, cap + 256).replace(ANSI, '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').replace(HIDE, ' ')
+ const text = maskSecrets(head).slice(0, cap)
+
+ return { text, total: raw.length, isCut: raw.length > cap }
+}
+
+/** A path for a cell: escapes, controls and hidden characters out, whitespace collapsed, cut; NOT masked (a 36 character id or a hash segment would read as a key, and a path is matched against another path). */
+export const cleanPath = (raw: string, max = 300): string => {
+ const line = raw.slice(0, max * 2).replace(ANSI, '').replace(HIDE, ' ').replace(/\s+/g, ' ').trim()
+
+ return line.length <= max ? line : `${line.slice(0, max - 1)}…`
+}
+
+/** One washed line of at most `max` characters. */
+export const cleanLine = (raw: string, max = 160): string => {
+ const line = cleanBlock(raw, max * 3).text.replace(/\s+/g, ' ').trim()
+
+ return line.length <= max ? line : `${line.slice(0, Math.max(0, max - 1))}…`
+}
+
+export type CallStatus = 'ok' | 'error' | 'pending'
+export type MessageRole = 'user' | 'assistant' | 'thinking' | 'result'
+
+export type MessageEntry = { kind: 'message'; index: number; role: MessageRole; atMs?: number; body: Capped }
+export type CallEntry = { kind: 'call'; index: number; callIndex: number; id: string; tool: string; atMs?: number; endMs?: number; status: CallStatus; summary: string; input: Capped; output: Capped | null }
+export type Entry = MessageEntry | CallEntry
+
+export type TouchedFile = { path: string; read: number; edit: number; write: number }
+
+export type Parsed = {
+ entries: Entry[]
+ calls: CallEntry[]
+ files: TouchedFile[]
+ /** True where the text began mid-file: the first line was dropped and calls made before it are not here. */
+ isTail: boolean
+ /** Entries before the newest ENTRY_CAP that were not kept. */
+ dropped: number
+ /** Lines that were not a record this reader reads (attachments, meta lines, a half-written last line). */
+ skipped: number
+}
+
+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'])
+
+function summaryOf(input: unknown): string {
+ const record = asRecord(input)
+
+ if (record === null) return typeof input === 'string' ? cleanLine(input) : ''
+
+ for (const key of SUMMARY_KEYS) if (typeof record[key] === 'string' && record[key] !== '') return cleanLine(record[key] as string)
+
+ return ''
+}
+
+function pathOf(input: unknown): string | undefined {
+ const record = asRecord(input)
+ const value = record?.file_path ?? record?.notebook_path
+
+ return typeof value === 'string' && value !== '' ? cleanPath(value) : 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 {
+ if (typeof content === 'string') return content
+ if (!Array.isArray(content)) return ''
+
+ return content
+ .map(block => {
+ const b = asRecord(block)
+
+ return b?.type === 'text' && typeof b.text === 'string' ? b.text : b?.type === 'image' ? '[image]' : ''
+ })
+ .filter(part => part !== '')
+ .join('\n')
+}
+
+const stamp = (line: Record<string, unknown>): number | undefined => {
+ const at = typeof line.timestamp === 'string' ? Date.parse(line.timestamp) : Number.NaN
+
+ return Number.isFinite(at) ? at : undefined
+}
+
+/** A transcript's lines: user and assistant records carry `message.content` as a string or as typed blocks. */
+export function parseActivity(text: string | null, isTail = false): Parsed {
+ const lines = jsonLines(isTail && text !== null ? text.slice(text.indexOf('\n') + 1) : text)
+ const entries: Entry[] = []
+ const byId = new Map<string, CallEntry>()
+ const files = new Map<string, TouchedFile>()
+ let skipped = 0
+ let calls = 0
+
+ const message = (role: MessageRole, atMs: number | undefined, raw: string): void => {
+ if (raw.trim() === '') return
+
+ entries.push({ kind: 'message', index: entries.length, role, body: cleanBlock(raw), ...(atMs !== undefined && { atMs }) })
+ }
+
+ for (const line of lines) {
+ const body = asRecord(line.message)
+
+ if ((line.type !== 'user' && line.type !== 'assistant') || body === null || line.isMeta === true) {
+ skipped += 1
+ continue
+ }
+
+ const at = stamp(line)
+ const content = body.content
+
+ if (typeof content === 'string') {
+ message(line.type, at, content)
+ continue
+ }
+
+ if (!Array.isArray(content)) continue
+
+ for (const raw of content) {
+ const block = asRecord(raw)
+
+ if (block === null) continue
+
+ if (block.type === 'text' && typeof block.text === 'string') message(line.type, at, block.text)
+ else if (block.type === 'thinking' && typeof block.thinking === 'string') message('thinking', at, block.thinking)
+ else if (block.type === 'tool_use' && typeof block.id === 'string') {
+ // A streamed message repeats its blocks over several lines: a call is counted once, by its id.
+ if (byId.has(block.id)) continue
+
+ const tool = cleanLine(typeof block.name === 'string' ? block.name : 'tool', 40)
+ const entry: CallEntry = { kind: 'call', index: entries.length, callIndex: calls, id: block.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)
+
+ calls += 1
+ byId.set(block.id, entry)
+ entries.push(entry)
+
+ if (path !== undefined && (READ_TOOLS.has(tool) || EDIT_TOOLS.has(tool) || WRITE_TOOLS.has(tool))) {
+ const held = files.get(path) ?? { path, read: 0, edit: 0, write: 0 }
+
+ if (READ_TOOLS.has(tool)) held.read += 1
+ else if (EDIT_TOOLS.has(tool)) held.edit += 1
+ else held.write += 1
+
+ files.set(path, held)
+ }
+ } else if (block.type === 'tool_result') {
+ const call = typeof block.tool_use_id === 'string' ? byId.get(block.tool_use_id) : undefined
+ const out = resultText(block.content)
+
+ if (call === undefined) message('result', at, out === '' ? '(a result whose call is before the part read)' : out)
+ else {
+ call.output = cleanBlock(out === '' ? '(empty)' : out)
+ call.status = block.is_error === true ? 'error' : 'ok'
+ if (at !== undefined) call.endMs = at
+ }
+ }
+ }
+ }
+
+ const dropped = Math.max(0, entries.length - ENTRY_CAP)
+ const kept = dropped === 0 ? entries : entries.slice(dropped)
+ const ordered = [...files.values()].sort((a, b) => b.edit + b.write - (a.edit + a.write) || a.path.localeCompare(b.path)).slice(0, FILE_CAP)
+
+ // Re-index after a drop, so `index` and `callIndex` are positions in what is kept.
+ let nextCall = 0
+ const reindexed: Entry[] = kept.map((entry, i) => (entry.kind === 'call' ? { ...entry, index: i, callIndex: nextCall++ } : { ...entry, index: i }))
+
+ return { entries: reindexed, calls: reindexed.filter((entry): entry is CallEntry => entry.kind === 'call'), files: ordered, isTail, dropped, skipped }
+}
+
+/** The structured result the run's journal kept for one agent: a string as written, anything else as pretty JSON, washed and capped. Null where the journal has none. */
+export function journalResult(journal: string | null, agentId: string): Capped | null {
+ let found: unknown
+
+ for (const event of jsonLines(journal)) if (event.type === 'result' && event.agentId === agentId) found = event.result
+
+ if (found === undefined) return null
+
+ return cleanBlock(typeof found === 'string' ? found : (JSON.stringify(found, null, 2) ?? ''))
+}
+
+export const durationOf = (call: CallEntry): number | undefined => (call.atMs !== undefined && call.endMs !== undefined ? Math.max(0, call.endMs - call.atMs) : undefined)
+
+/** `1.2s` · `340ms`: a call's span, n/a where one end has no timestamp. */
+export const fmtSpan = (ms: number | undefined): string => (ms === undefined ? 'n/a' : ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`)
diff --git a/plugins/ruflo-console/hooks/data/wf-drill-io.ts b/plugins/ruflo-console/hooks/data/wf-drill-io.ts
new file mode 100644
index 0000000000..b119ed0d11
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-drill-io.ts
@@ -0,0 +1,293 @@
+/**
+ * What the drill-down reads, and the only place it reads anything (ADR-459). Everything here is read-only, byte-capped and path-checked:
+ *
+ * transcripts `<configDir>/projects/**\/agent-<id>.jsonl`, whole up to TRANSCRIPT_CAP, else the last TAIL_BYTES where the host can
+ * the journal `<run dir>/journal.jsonl`, up to JOURNAL_CAP, for the structured result of one agent
+ * a worktree one `git diff --numstat` over the agent's worktree, only if it lies inside the project's folder
+ *
+ * A view never reads: it asks `textOf` / `parsedOf` for what is already in memory (the page's own refresh keeps live runs' transcripts in
+ * the console's read cache), and a button calls a loader here for the rest. The loaders need the host, which no slot is handed, so the
+ * merge owner binds it once (`bindDrill`); unbound, the drill still draws everything the cache holds and says what it could not read.
+ * 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 { TAIL_BYTES, TRANSCRIPT_CAP, type WorkflowFs } from './workflows-read'
+import type { WfAgent, WfRun } from './workflows'
+
+export const JOURNAL_CAP = 1_000_000
+/** Bytes of transcript one "read the run's transcripts" press may bring in (each is also held to TRANSCRIPT_CAP). */
+export const LOAD_BUDGET = 24_000_000
+const DIFF_CAP_LINES = 400
+
+/** The engine pieces the loaders use; `Host` has them all. */
+export type DrillHost = { fs: WorkflowFs; run: (argv: readonly string[], timeoutMs: number) => Promise<{ exitCode: number; stdout: string; stderr?: string }>; invalidate: () => void }
+type Bound = { cache: ReadCache; configDir: string | null; cwd: string; host: DrillHost }
+
+let bound: Bound | null = null
+
+/** Gives the loaders the console's read cache, config directory, working directory and host. Call once at boot; calling again replaces it. */
+export function bindDrill(state: { cache: ReadCache; configDir: string | null; cwd: string }, host: DrillHost): void {
+ bound = { cache: state.cache, configDir: state.configDir, cwd: state.cwd, host }
+}
+
+export const isBound = (): boolean => bound !== null
+
+/** For tests: forgets the binding and everything held. */
+export function resetDrillIo(): void {
+ bound = null
+ parsedMemo.clear()
+ tails.clear()
+ notes.clear()
+ results.clear()
+ diffs.clear()
+}
+
+/** True for a path under `<configDir>/projects/` with no `..` part and no NUL: the only place a run's files live. */
+export function isRunFile(path: string, configDir: string | null): boolean {
+ if (configDir === null || path.includes('\0') || path.includes('\n') || path.split('/').includes('..')) return false
+
+ return path.startsWith(`${configDir.replace(/\/+$/, '')}/projects/`)
+}
+
+/** True for an absolute path inside the project's working directory (where Claude Code puts an agent's worktree), with no `..` part. */
+export function isProjectDir(path: string, cwd: string): boolean {
+ if (!path.startsWith('/') || path.includes('\0') || path.includes('\n') || path.split('/').includes('..')) return false
+
+ const root = cwd.replace(/\/+$/, '')
+
+ return root !== '' && (path === root || path.startsWith(`${root}/`))
+}
+
+export type Note = { phase: 'loading' | 'ok' | 'none' | 'failed'; why?: string }
+const notes = new Map<string, Note>()
+const MAX_HELD = 24
+
+const hold = <V>(map: Map<string, V>, key: string, value: V, max = MAX_HELD): void => {
+ map.delete(key)
+ map.set(key, value)
+
+ if (map.size > max) map.delete(map.keys().next().value as string)
+}
+
+export const noteOf = (key: string): Note | undefined => notes.get(key)
+
+const parsedMemo = new Map<string, { src: string; isTail: boolean; parsed: Parsed }>()
+const tails = new Map<string, { text: string; size: number }>()
+
+export type Text = { text: string; isTail: boolean }
+
+/** 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 {
+ const path = agent.transcriptPath
+
+ if (path === undefined) return null
+
+ const held = cache.get(path)
+
+ if (held !== undefined && 'text' in held) return { text: held.text, isTail: false }
+
+ const tail = tails.get(path)
+
+ return tail === undefined ? null : { text: tail.text, isTail: true }
+}
+
+/** The agent's transcript parsed, memoised by the text itself so an unchanged file is parsed once however often the page draws. */
+export function parsedOf(cache: ReadCache, agent: WfAgent): Parsed | null {
+ const text = textOf(cache, agent)
+ const path = agent.transcriptPath
+
+ if (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)
+
+ hold(parsedMemo, path, { src: text.text, isTail: text.isTail, parsed })
+
+ return parsed
+}
+
+/** Reads one agent's transcript into memory. Resolves when done; never rejects. */
+export async function loadTranscript(agent: WfAgent): Promise<void> {
+ const b = bound
+ const path = agent.transcriptPath
+
+ if (b === null || path === undefined) return
+
+ if (!isRunFile(path, b.configDir) || !/\/agent-[A-Za-z0-9]+\.jsonl$/.test(path)) {
+ notes.set(path, { phase: 'failed', why: 'that path is outside Claude Code\'s projects folder, so it is not read' })
+ b.host.invalidate()
+
+ return
+ }
+
+ notes.set(path, { phase: 'loading' })
+ b.host.invalidate()
+
+ try {
+ const read = await readBounded(b.host.fs, b.cache, path, TRANSCRIPT_CAP, true)
+
+ if (read.text !== null) notes.set(path, { phase: 'ok' })
+ 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 })
+ 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) {
+ notes.set(path, { phase: 'failed', why: cleanLine(error instanceof Error ? error.message : String(error), 80) || 'the read was refused' })
+ } finally {
+ b.host.invalidate()
+ }
+}
+
+/** Reads every workflow agent's transcript of a run that is not in memory yet, up to LOAD_BUDGET bytes in all. Returns how many were left for the budget. */
+export async function loadRun(run: WfRun): Promise<{ loaded: number; left: number }> {
+ const b = bound
+
+ if (b === null) return { loaded: 0, left: 0 }
+
+ const todo = run.phases.flatMap(phase => phase.agents).filter(agent => agent.ruflo === undefined && agent.transcriptPath !== undefined && textOf(b.cache, agent) === null)
+ let spent = 0
+ let loaded = 0
+
+ for (const [i, agent] of todo.entries()) {
+ const size = (await b.host.fs.stat(agent.transcriptPath as string).catch(() => undefined))?.size ?? 0
+
+ if (spent + Math.min(size, TRANSCRIPT_CAP) > LOAD_BUDGET) return { loaded, left: todo.length - i }
+
+ spent += Math.min(size, TRANSCRIPT_CAP)
+ await loadTranscript(agent)
+ loaded += 1
+ }
+
+ return { loaded, left: 0 }
+}
+
+/** Reads again every large transcript whose tail is held, so a followed log of one moves on: the last TAIL_BYTES, each time. */
+export async function reloadTails(): Promise<void> {
+ const b = bound
+
+ if (b === null || b.host.fs.readTail === undefined) return
+
+ for (const [path, held] of [...tails]) {
+ if (!isRunFile(path, b.configDir)) continue
+
+ try {
+ hold(tails, path, { text: await b.host.fs.readTail(path, TAIL_BYTES), size: held.size })
+ } catch {
+ // The held tail stays; the next tick tries again.
+ }
+ }
+
+ b.host.invalidate()
+}
+
+const results = new Map<string, Capped | 'none'>()
+
+/** The structured result a run's journal kept for an agent: the washed text, `'none'` where the journal has none, undefined before it is read. */
+export const resultOf = (run: WfRun, agent: WfAgent): Capped | 'none' | undefined => results.get(`${run.id}/${agent.id}`)
+
+export async function loadResult(run: WfRun, agent: WfAgent): Promise<void> {
+ const b = bound
+ const key = `${run.id}/${agent.id}`
+
+ if (b === null || run.dir === undefined) return
+
+ const path = `${run.dir.replace(/\/+$/, '')}/journal.jsonl`
+
+ if (!isRunFile(path, b.configDir)) {
+ notes.set(key, { phase: 'failed', why: 'the run folder is outside Claude Code\'s projects folder, so its journal is not read' })
+ b.host.invalidate()
+
+ return
+ }
+
+ notes.set(key, { phase: 'loading' })
+
+ try {
+ const read = await readBounded(b.host.fs, b.cache, path, JOURNAL_CAP, true)
+
+ if (read.text === null) notes.set(key, { phase: 'failed', why: read.reason === 'too-large' ? `the journal is over the ${(JOURNAL_CAP / 1_000_000).toFixed(0)} MB read cap` : read.reason === 'missing' ? 'the journal is gone' : 'the host refused the read' })
+ else {
+ hold(results, key, journalResult(read.text, agent.id) ?? 'none')
+ notes.set(key, { phase: 'ok' })
+ }
+ } catch {
+ notes.set(key, { phase: 'failed', why: 'the read was refused' })
+ } finally {
+ b.host.invalidate()
+ }
+}
+
+export type Diff = Map<string, { add: number | null; del: number | null }>
+const diffs = new Map<string, { files: Diff; extra: number }>()
+
+/** `git diff --numstat` lines: `12\t3\tpath`, and `-\t-\tpath` for a binary file (its counts are null). */
+export function parseNumstat(stdout: string): { files: Diff; extra: number } {
+ const files: Diff = new Map()
+ let extra = 0
+
+ for (const line of stdout.split('\n')) {
+ const match = /^(\d+|-)\t(\d+|-)\t(.+)$/.exec(line)
+
+ if (match === null) continue
+
+ if (files.size >= DIFF_CAP_LINES) {
+ extra += 1
+ continue
+ }
+
+ files.set(cleanPath(match[3] as string), { add: match[1] === '-' ? null : Number(match[1]), del: match[2] === '-' ? null : Number(match[2]) })
+ }
+
+ return { files, extra }
+}
+
+export const diffOf = (agent: WfAgent): { files: Diff; extra: number } | undefined => (agent.worktreePath === undefined ? undefined : diffs.get(agent.worktreePath))
+
+/**
+ * The fixed argv of the one process this module runs: no shell, the path is its own argument after `-C`, no external diff driver, no text
+ * conversion, no fsmonitor hook and no optional lock. A `filter.*.clean` command in the worktree's own config can still run when git compares
+ * the working tree with HEAD; that is why only a worktree inside this project's folder is read.
+ */
+export const diffArgv = (worktree: string): string[] => ['git', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', worktree, 'diff', '--numstat', '--no-renames', '--no-color', '--no-ext-diff', '--no-textconv', 'HEAD', '--']
+
+export async function loadDiff(agent: WfAgent): Promise<void> {
+ const b = bound
+ const path = agent.worktreePath
+
+ if (b === null || path === undefined) return
+
+ if (!isProjectDir(path, b.cwd)) {
+ notes.set(path, { phase: 'failed', why: 'the worktree is not inside this project\'s folder, so it is not read' })
+ b.host.invalidate()
+
+ return
+ }
+
+ notes.set(path, { phase: 'loading' })
+ b.host.invalidate()
+
+ try {
+ const stat = await b.host.fs.stat(path).catch(() => undefined)
+
+ if (stat === undefined) notes.set(path, { phase: 'none', why: 'the worktree folder no longer exists' })
+ else {
+ const result = await b.host.run(diffArgv(path), 8000)
+
+ if (result.exitCode !== 0) notes.set(path, { phase: 'failed', why: cleanLine(result.stderr ?? `git exited ${result.exitCode}`, 100) || `git exited ${result.exitCode}` })
+ else {
+ hold(diffs, path, parseNumstat(result.stdout.slice(0, 200_000)))
+ notes.set(path, { phase: 'ok' })
+ }
+ }
+ } catch (error) {
+ notes.set(path, { phase: 'failed', why: cleanLine(error instanceof Error ? error.message : String(error), 80) || 'the probe was refused' })
+ } finally {
+ b.host.invalidate()
+ }
+}
diff --git a/plugins/ruflo-console/hooks/data/wf-log.ts b/plugins/ruflo-console/hooks/data/wf-log.ts
new file mode 100644
index 0000000000..d1490212f3
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-log.ts
@@ -0,0 +1,70 @@
+/**
+ * The Log sub-tab's data (ADR-459): a transcript's entries as one washed line each, a level filter, an agent scope (one agent or the
+ * whole phase merged by time), and the window of lines on screen, which follows the newest line or stays where the person put it.
+ * Pure. "Follow" is a pin to the last line that the page's own refresh re-draws; it is not a stream, and the page says so.
+ */
+import { cleanLine, type Entry, type Parsed } from './wf-activity'
+
+export type LogLevel = 'user' | 'assistant' | 'thinking' | 'tool' | 'error'
+export type LevelFilter = 'all' | 'text' | 'tool' | 'error'
+/** The order the level key cycles through. */
+export const LEVEL_FILTERS: readonly LevelFilter[] = ['all', 'text', 'tool', 'error']
+export type LogScope = 'agent' | 'phase'
+
+export type LogLine = {
+ /** Position of the entry in its agent's transcript (what the item level opens). */
+ entry: number
+ agentId: string
+ agent: string
+ atMs?: number
+ level: LogLevel
+ text: string
+}
+
+/** Rows of the log drawn at once. */
+export const LOG_ROWS = 14
+
+const levelOf = (entry: Entry): LogLevel => (entry.kind === 'call' ? (entry.status === 'error' ? 'error' : 'tool') : entry.role === 'result' ? 'tool' : entry.role)
+
+const textOf = (entry: Entry): string =>
+ entry.kind === 'call' ? `${entry.tool} ${entry.summary}${entry.status === 'pending' ? ' (no result in the part read)' : entry.status === 'error' ? ' (failed)' : ''}`.trim() : cleanLine(entry.body.text, 200)
+
+/** One line per entry of an agent's transcript, in the order written. */
+export const logLines = (parsed: Parsed, agent: { id: string; label: string }): LogLine[] =>
+ parsed.entries.map(entry => ({ entry: entry.index, agentId: agent.id, agent: cleanLine(agent.label, 40), level: levelOf(entry), text: textOf(entry), ...(entry.atMs !== undefined && { atMs: entry.atMs }) }))
+
+/** Several agents' lines as one log, ordered by time; lines with no timestamp keep their place after the lines of their own agent. */
+export function mergeLines(lists: readonly (readonly LogLine[])[]): LogLine[] {
+ const tagged = lists.flatMap((list, order) => list.map((line, at) => ({ line, order, at })))
+
+ return tagged.sort((a, b) => (a.line.atMs ?? Number.POSITIVE_INFINITY) - (b.line.atMs ?? Number.POSITIVE_INFINITY) || a.order - b.order || a.at - b.at).map(item => item.line)
+}
+
+export function filterLines(lines: readonly LogLine[], filter: LevelFilter): LogLine[] {
+ if (filter === 'all') return [...lines]
+
+ return lines.filter(line => (filter === 'error' ? line.level === 'error' : filter === 'tool' ? line.level === 'tool' || line.level === 'error' : line.level === 'user' || line.level === 'assistant' || line.level === 'thinking'))
+}
+
+export const nextFilter = (filter: LevelFilter): LevelFilter => LEVEL_FILTERS[(LEVEL_FILTERS.indexOf(filter) + 1) % LEVEL_FILTERS.length] as LevelFilter
+
+export type LogWindow = { from: number; rows: LogLine[]; total: number; /** Index of the selected line inside `rows`, or -1. */ at: number; /** Lines above the window. */ above: number; below: number }
+
+/**
+ * The lines to draw. Following pins the window to the end and the selection to the last line; otherwise the window keeps the selected
+ * line (`sel`, an index into `lines`, clamped) on screen, as the board's lists do.
+ */
+export function tailWindow(lines: readonly LogLine[], opts: { size?: number; sel: number; follow: boolean }): LogWindow {
+ const size = Math.max(1, opts.size ?? LOG_ROWS)
+ const total = lines.length
+
+ if (total === 0) return { from: 0, rows: [], total: 0, at: -1, above: 0, below: 0 }
+
+ const sel = opts.follow ? total - 1 : Math.max(0, Math.min(total - 1, opts.sel))
+ const from = Math.max(0, Math.min(total - size, sel - size + 1))
+
+ return { from, rows: lines.slice(from, from + size), total, at: sel - from, above: from, below: Math.max(0, total - from - size) }
+}
+
+/** `20:03:45` in UTC, or `--:--:--` where the line has no timestamp. */
+export const clockOf = (atMs: number | undefined): string => (atMs === undefined ? '--:--:--' : new Date(atMs).toISOString().slice(11, 19))
diff --git a/plugins/ruflo-console/hooks/data/wf-search.ts b/plugins/ruflo-console/hooks/data/wf-search.ts
new file mode 100644
index 0000000000..91bcde9f89
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-search.ts
@@ -0,0 +1,135 @@
+/**
+ * Search across the drill's levels (ADR-459): run names, phase titles, agent labels, tool calls, transcript text and, where the project
+ * has them, mission tasks. Hits come grouped by level and each carries the exact place it jumps to. Pure, and it searches only text
+ * already in memory: an agent whose transcript has not been read is counted as unread, never guessed at. The scan is capped
+ * (SCAN_CHARS characters of transcript text in all, MAX_SHOWN hits a group) and the result says what was and was not looked at.
+ * Snippets come from washed text (data/wf-activity), so a hit can never show what the washing masked.
+ */
+import { cleanLine, type CallEntry, type Parsed } from './wf-activity'
+import type { Target } from './wf-trail'
+import { currentPhase, type WfAgent, type WfRun } from './workflows'
+
+export type HitLevel = 'run' | 'phase' | 'agent' | 'tool' | 'text' | 'mission'
+export const HIT_ORDER: readonly HitLevel[] = ['run', 'phase', 'agent', 'tool', 'text', 'mission']
+export const HIT_NAME: Record<HitLevel, string> = { run: 'Runs', phase: 'Phases', agent: 'Agents', tool: 'Tool calls', text: 'Transcript text', mission: 'Mission tasks' }
+
+export const MIN_QUERY = 2
+export const MAX_QUERY = 80
+export const MAX_SHOWN = 6
+/** Characters of transcript text looked through in one search, across all agents. */
+export const SCAN_CHARS = 8_000_000
+
+export type Hit = { level: HitLevel; title: string; detail: string; /** Where Enter goes; absent for a mission task, which lives on the Missions page. */ target?: Target }
+
+export type MissionTaskRef = { mission: string; id: string; title: string; status: string }
+
+export type SearchInput = {
+ runs: readonly WfRun[]
+ /** The transcript of an agent as already parsed, or null where it has not been read. */
+ parsed: (agent: WfAgent) => Parsed | null
+ tasks?: readonly MissionTaskRef[]
+}
+
+export type SearchResult = {
+ query: string
+ /** False for a query too short to search: nothing was looked at. */
+ isSearched: boolean
+ groups: Record<HitLevel, Hit[]>
+ /** Matches found per level, including those past MAX_SHOWN. */
+ counts: Record<HitLevel, number>
+ /** Agents with a transcript (workflow agents) that was searched / was not in memory. */
+ scanned: number
+ unread: number
+ chars: number
+ /** True where the character cap stopped the scan. */
+ isCapped: boolean
+}
+
+const empty = (query: string, isSearched: boolean): SearchResult => ({ query, isSearched, groups: { run: [], phase: [], agent: [], tool: [], text: [], mission: [] }, counts: { run: 0, phase: 0, agent: 0, tool: 0, text: 0, mission: 0 }, scanned: 0, unread: 0, chars: 0, isCapped: false })
+
+/** A short stretch of `text` around the first match, as one washed line. */
+function snippet(text: string, at: number, needle: number): string {
+ const from = Math.max(0, at - 40)
+ const body = cleanLine(text.slice(from, at + needle + 60), 110)
+
+ return `${from > 0 ? '…' : ''}${body}`
+}
+
+export function search(input: SearchInput, query: string): SearchResult {
+ const wanted = query.trim().slice(0, MAX_QUERY)
+ const needle = wanted.toLowerCase()
+
+ if (needle.length < MIN_QUERY) return empty(wanted, false)
+
+ const out = empty(wanted, true)
+ const add = (hit: Hit): void => {
+ out.counts[hit.level] += 1
+
+ if (out.groups[hit.level].length < MAX_SHOWN) out.groups[hit.level].push(hit)
+ }
+ const at = (text: string | undefined): number => (text === undefined ? -1 : text.toLowerCase().indexOf(needle))
+
+ for (const [r, run] of input.runs.entries()) {
+ if (at(run.name) >= 0 || at(run.id) >= 0) add({ level: 'run', title: run.name, detail: `${run.kind === 'workflow' ? 'workflow' : 'ruflo swarm'} · ${run.state} · ${run.total} agents`, target: { run: r, phase: currentPhase(run.phases) ?? 0, agent: -1 } })
+
+ for (const [p, phase] of run.phases.entries()) {
+ if (at(phase.title) >= 0 || at(phase.detail) >= 0) add({ level: 'phase', title: phase.title, detail: `${run.name} · ${phase.done}/${phase.total} done`, target: { run: r, phase: p, agent: -1 } })
+
+ for (const [a, agent] of phase.agents.entries()) {
+ const place = { run: r, phase: p, agent: a }
+ const field = [agent.label, agent.resultPreview, agent.lastTool, agent.model, agent.id].find(value => at(value) >= 0)
+
+ if (field !== undefined) add({ level: 'agent', title: agent.label, detail: `${run.name} · ${phase.title}${field === agent.label ? '' : ` · ${snippet(field, at(field), needle.length)}`}`, target: place })
+
+ if (agent.ruflo !== undefined) continue
+
+ const parsed = input.parsed(agent)
+
+ if (parsed === null) {
+ if (agent.transcriptPath !== undefined) out.unread += 1
+ continue
+ }
+
+ out.scanned += 1
+
+ if (out.isCapped) continue
+
+ for (const entry of parsed.entries) {
+ if (out.chars > SCAN_CHARS) {
+ out.isCapped = true
+ break
+ }
+
+ if (entry.kind === 'call') {
+ out.chars += entry.input.text.length + (entry.output?.text.length ?? 0)
+
+ const call: CallEntry = entry
+ const hay = `${call.tool} ${call.summary} ${call.input.text}`
+ const i = at(hay)
+
+ if (i >= 0) add({ level: 'tool', title: `${call.tool} ${call.summary}`.trim(), detail: `${agent.label} · call #${call.callIndex + 1} · ${call.status}`, target: { ...place, sub: 'activity', call: call.callIndex } })
+
+ const o = at(call.output?.text)
+
+ if (call.output !== null && o >= 0) add({ level: 'text', title: snippet(call.output.text, o, needle.length), detail: `${agent.label} · output of ${call.tool}`, target: { ...place, sub: 'log', line: call.index } })
+ } else {
+ out.chars += entry.body.text.length
+
+ const i = at(entry.body.text)
+
+ if (i >= 0) add({ level: 'text', title: snippet(entry.body.text, i, needle.length), detail: `${agent.label} · ${entry.role}`, target: { ...place, sub: 'log', line: entry.index } })
+ }
+ }
+ }
+ }
+ }
+
+ for (const task of input.tasks ?? []) {
+ if (at(task.title) >= 0 || at(task.id) >= 0) add({ level: 'mission', title: cleanLine(task.title, 100), detail: `${cleanLine(task.mission, 40)} · ${cleanLine(task.status, 20)} · on the Missions page` })
+ }
+
+ return out
+}
+
+/** Every hit in the order the page lists them: by level, then as found. */
+export const flatHits = (result: SearchResult): Hit[] => HIT_ORDER.flatMap(level => result.groups[level])
diff --git a/plugins/ruflo-console/hooks/data/wf-trail.ts b/plugins/ruflo-console/hooks/data/wf-trail.ts
new file mode 100644
index 0000000000..b829d36a19
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/wf-trail.ts
@@ -0,0 +1,150 @@
+/**
+ * Where the drill-down is (ADR-459), and how its keys move it. Pure, so the movement is tested without a screen.
+ *
+ * Runs > Phases > Agents > Agent (Activity | Log | Files | Result) > one tool call or message
+ *
+ * The first three levels are the page's own cursor (data/workflows-nav): going deeper there sends the page the `h` / `l` it already
+ * understands (`ui` below), so the board and the drill never disagree about where the person is. From the agent down the position is
+ * the drill's own: the sub-tab, the selected call or log line, whether the log follows the newest line, its level filter and scope.
+ */
+import type { LevelFilter, LogScope } from './wf-log'
+
+export type DrillLevel = 'runs' | 'phases' | 'agents' | 'agent' | 'item'
+export const LEVELS: readonly DrillLevel[] = ['runs', 'phases', 'agents', 'agent', 'item']
+export const LEVEL_NAME: Record<DrillLevel, string> = { runs: 'Runs', phases: 'Phases', agents: 'Agents', agent: 'Agent', item: 'Call' }
+
+export type Sub = 'activity' | 'log' | 'files' | 'result'
+export const SUBS: readonly Sub[] = ['activity', 'log', 'files', 'result']
+export const SUB_NAME: Record<Sub, string> = { activity: 'Activity', log: 'Log', files: 'Files', result: 'Result' }
+
+export type Drill = {
+ open: boolean
+ level: DrillLevel
+ sub: Sub
+ /** `<run id>/<agent id>` the selections below belong to: another agent resets them. */
+ at: string
+ /** Selected tool call (Activity) and selected line of the log. */
+ callSel: number
+ logSel: number
+ /** The log pins to its newest line, and is re-drawn on the page's refresh. */
+ follow: boolean
+ filter: LevelFilter
+ scope: LogScope
+ /** First line shown of an opened call or message. */
+ scroll: number
+ query: string
+ isSearching: boolean
+}
+
+export const newDrill = (): Drill => ({ open: false, level: 'runs', sub: 'activity', at: '', callSel: 0, logSel: 0, follow: true, filter: 'all', scope: 'agent', scroll: 0, query: '', isSearching: false })
+
+/** What the cursor is on, as far as moving needs to know. */
+export type Here = { column: 'phases' | 'agents'; phaseAgents: number; hasAgent: boolean; isRuflo: boolean; calls: number; lines: number }
+
+/** A key the page's own reducer should also see (`h` / `l` pick its column; `j` `k` `[` `]` move it). */
+export type PageKey = 'h' | 'l' | 'j' | 'k' | '[' | ']'
+
+export type Step = { drill: Drill; ui?: PageKey; /** Why nothing deeper happened, said on the page instead of a dead key. */ said?: string }
+
+export const clamp = (value: number, size: number): number => (size <= 0 ? 0 : Math.max(0, Math.min(size - 1, value)))
+
+/** Another agent (or run) is under the cursor: the call, line and scroll selections start over; the person's filter and scope stay. */
+export const sync = (drill: Drill, at: string): Drill => (drill.at === at ? drill : { ...drill, at, callSel: 0, logSel: 0, scroll: 0, follow: true })
+
+/** Opens the drill where the cursor already is: the phases column opens at Phases, the agents column at Agents. */
+export const openAt = (drill: Drill, here: Pick<Here, 'column'>): Drill => ({ ...drill, open: true, level: here.column === 'agents' ? 'agents' : 'phases', scroll: 0 })
+
+export function deeper(drill: Drill, here: Here): Step {
+ if (!drill.open) return { drill: openAt(drill, here) }
+
+ switch (drill.level) {
+ case 'runs':
+ return { drill: { ...drill, level: 'phases' }, ui: 'h' }
+ case 'phases':
+ return here.phaseAgents > 0 ? { drill: { ...drill, level: 'agents' }, ui: 'l' } : { drill, said: 'No agent has started in this phase yet, so there is nothing deeper.' }
+ case 'agents':
+ if (!here.hasAgent) return { drill, said: 'This phase has no agent to open.' }
+
+ return here.isRuflo ? { drill, said: 'A ruflo agent keeps no transcript, worktree or return: there is nothing deeper than its row.' } : { drill: { ...drill, level: 'agent', sub: 'activity', scroll: 0 } }
+ case 'agent': {
+ const count = drill.sub === 'activity' ? here.calls : drill.sub === 'log' ? here.lines : 0
+
+ return count > 0 ? { drill: { ...drill, level: 'item', scroll: 0, ...(drill.sub === 'log' && { follow: false, logSel: drill.follow ? clamp(here.lines - 1, here.lines) : drill.logSel }) } } : { drill, said: drill.sub === 'files' || drill.sub === 'result' ? 'Files and Result have no deeper level: pick Activity or Log for a call or message.' : 'No call or message has been read for this agent.' }
+ }
+ case 'item':
+ return { drill, said: 'This is the deepest level: one call or message in full.' }
+ }
+}
+
+export function shallower(drill: Drill): Step {
+ if (!drill.open) return { drill }
+
+ switch (drill.level) {
+ case 'item':
+ return { drill: { ...drill, level: 'agent', scroll: 0 } }
+ case 'agent':
+ return { drill: { ...drill, level: 'agents' }, ui: 'l' }
+ case 'agents':
+ return { drill: { ...drill, level: 'phases' }, ui: 'h' }
+ case 'phases':
+ return { drill: { ...drill, level: 'runs' } }
+ case 'runs':
+ return { drill: { ...drill, open: false } }
+ }
+}
+
+/** Goes straight to a level the breadcrumb names: only a shallower one (a deeper one needs the keys that check there is something there). */
+export function toLevel(drill: Drill, level: DrillLevel): Step {
+ let step: Step = { drill }
+ let ui: PageKey | undefined
+
+ for (let guard = 0; guard < LEVELS.length && step.drill.level !== level && LEVELS.indexOf(step.drill.level) > LEVELS.indexOf(level); guard += 1) {
+ step = shallower(step.drill)
+ ui = step.ui ?? ui
+ }
+
+ return { drill: step.drill, ...(ui !== undefined && { ui }) }
+}
+
+/** Next or previous: a run, phase or agent at the first three levels (the page's cursor), a call or line below. Selecting a line stops following. */
+export function move(drill: Drill, by: 1 | -1, here: Here): Step {
+ if (!drill.open) return { drill }
+
+ switch (drill.level) {
+ case 'runs':
+ return { drill, ui: by === 1 ? ']' : '[' }
+ case 'phases':
+ return { drill, ui: by === 1 ? 'j' : 'k' }
+ case 'agents':
+ return { drill, ui: by === 1 ? 'j' : 'k' }
+ case 'agent':
+ case 'item':
+ if (drill.sub === 'log') return { drill: { ...drill, follow: false, logSel: clamp((drill.follow ? here.lines - 1 : drill.logSel) + by, here.lines), scroll: 0 } }
+ if (drill.sub === 'activity') return { drill: { ...drill, callSel: clamp(drill.callSel + by, here.calls), scroll: 0 } }
+
+ return { drill }
+ }
+}
+
+export const nextSub = (drill: Drill): Drill => ({ ...drill, sub: SUBS[(SUBS.indexOf(drill.sub) + 1) % SUBS.length] as Sub, scroll: 0, level: drill.level === 'item' ? 'agent' : drill.level })
+
+/** The breadcrumb, from Runs down to where the person is, each with whether the person can go back to it. */
+export function crumbs(drill: Drill): { level: DrillLevel; label: string; isHere: boolean }[] {
+ const to = LEVELS.indexOf(drill.level)
+
+ return LEVELS.slice(0, to + 1).map(level => ({ level, label: level === 'agent' ? `${LEVEL_NAME.agent} · ${SUB_NAME[drill.sub]}` : LEVEL_NAME[level], isHere: level === drill.level }))
+}
+
+/** Where a search hit takes the person: the cursor's run, phase and agent, then a sub-tab and the call or line in it. */
+export type Target = { run: number; phase: number; agent: number; sub?: Sub; call?: number; line?: number; /** True to open the item (one call or message in full). */ item?: boolean }
+
+export type Jump = { drill: Drill; ui: { run: number; phase: number; agent: number; column: 'phases' | 'agents'; isInspecting: false } }
+
+export function jump(drill: Drill, target: Target, at: string): Jump {
+ const isAgent = target.sub !== undefined || target.call !== undefined || target.line !== undefined
+ const sub: Sub = target.sub ?? (target.line !== undefined ? 'log' : 'activity')
+ const level: DrillLevel = target.item === true ? 'item' : isAgent ? 'agent' : target.agent >= 0 ? 'agents' : 'phases'
+ const next: Drill = { ...drill, open: true, level, sub, at, isSearching: false, scroll: 0, callSel: target.call ?? 0, logSel: target.line ?? 0, follow: false, filter: 'all', scope: 'agent' }
+
+ return { drill: next, ui: { run: target.run, phase: target.phase, agent: Math.max(0, target.agent), column: isAgent || target.agent >= 0 ? 'agents' : 'phases', isInspecting: false } }
+}
diff --git a/plugins/ruflo-console/hooks/views/wf-detail.ts b/plugins/ruflo-console/hooks/views/wf-detail.ts
new file mode 100644
index 0000000000..37b657ca6b
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/wf-detail.ts
@@ -0,0 +1,300 @@
+/**
+ * The drill-down of the Workflows page (ADR-459), plugged in through the page's slots (views/wf-slots.ts) and nothing else:
+ *
+ * Runs > Phases > Agents > one Agent (Activity | Log | Files | Result) > one tool call or message in full
+ *
+ * A board slot draws the panel (breadcrumb, then the level you are on) and key slots move through it. The page's own `Enter`, `Esc`,
+ * `h` and `/` are not available to a slot (a hotkey is one free letter or digit, `h` is Help's, Enter and Esc are the page's), so the
+ * keys are buttons with letters, and `drillKey` is exported for the merge owner who wants Enter/Esc routed here too.
+ *
+ * The drill's own position lives in a module record keyed by the console's `State` object, not in `WfUi` (which is closed): a key
+ * handler stores the new position and asks the page to redraw with `setUi({})`. The first three levels are the page's cursor, so a key
+ * there sends the page the `h` `l` `j` `k` `[` `]` it already understands.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { isBound, loadDiff, loadResult, loadTranscript, noteOf, parsedOf, reloadTails, resultOf, textOf } from '../data/wf-drill-io'
+import { filterLines, logLines, mergeLines, nextFilter, type LogLine } from '../data/wf-log'
+import { crumbs, deeper, jump, LEVEL_NAME, move, nextSub, newDrill, shallower, sync, toLevel, type Drill, type DrillLevel, type Here, type PageKey, type Step, type Sub, type Target } from '../data/wf-trail'
+import { fmtElapsed, fmtTokens } from '../data/workflows'
+import { button, clip, col, row, text, THEME } from './common'
+import { agentBody, itemBody, type Model, type Ops } from './wf-drill-body'
+import { registerSlot, type SlotEnv } from './wf-slots'
+import type { State } from '../state'
+
+const drills = new WeakMap<object, Drill>()
+const said = new WeakMap<object, string>()
+let boundState: State | null = null
+
+/** The merge owner's binding hands the drill the `State` the follow tick should look at. */
+export const watchState = (state: State | null): void => void (boundState = state)
+
+export const drillOf = (state: object): Drill => drills.get(state) ?? newDrill()
+const keyOf = (env: SlotEnv): string => `${env.run?.id ?? ''}/${env.agent?.id ?? ''}`
+
+/** The drill as this frame sees it: the stored position, started over where the cursor moved to another agent, and what the log and calls hold. */
+export function modelOf(env: SlotEnv): Model {
+ const state = env.ctx.state
+ const drill = sync(drillOf(state), keyOf(env))
+ const agent = env.agent
+ const parsed = agent !== null && agent.ruflo === undefined ? parsedOf(state.cache, agent) : null
+ let lines: LogLine[] = []
+ let unread = 0
+
+ if (drill.open && drill.sub === 'log' && agent !== null && agent.ruflo === undefined && (drill.level === 'agent' || drill.level === 'item')) {
+ if (drill.scope === 'agent') lines = parsed === null ? [] : logLines(parsed, agent)
+ else {
+ const lists = (env.phase?.agents ?? []).filter(other => other.ruflo === undefined).flatMap(other => {
+ const p = parsedOf(state.cache, other)
+
+ if (p === null) {
+ unread += 1
+
+ return []
+ }
+
+ // A merged log of a whole phase keeps each agent's newest lines: sixty agents' full logs would be the cost of every frame.
+ return [logLines(p, other).slice(-400)]
+ })
+
+ lines = mergeLines(lists)
+ }
+ }
+
+ return { drill, parsed, lines: filterLines(lines, drill.filter), unread }
+}
+
+const hereOf = (env: SlotEnv, m: Model): Here => ({ column: env.ui.column, phaseAgents: env.phase?.agents.length ?? 0, hasAgent: env.agent !== null, isRuflo: env.agent?.ruflo !== undefined, calls: m.parsed?.calls.length ?? 0, lines: m.lines.length })
+
+/** Loads what the level now in front needs and is not in memory, when the host is bound. Nothing here runs from a draw. */
+function ensureLoaded(env: SlotEnv, drill: Drill): void {
+ const agent = env.agent
+ const run = env.run
+
+ if (!isBound() || !drill.open || (drill.level !== 'agent' && drill.level !== 'item') || agent === null || run === null || agent.ruflo !== undefined) return
+
+ const state = env.ctx.state
+
+ if (textOf(state.cache, agent) === null && agent.transcriptPath !== undefined && noteOf(agent.transcriptPath) === undefined) void loadTranscript(agent)
+ if (drill.sub === 'result' && resultOf(run, agent) === undefined && noteOf(`${run.id}/${agent.id}`) === undefined) void loadResult(run, agent)
+ if (drill.sub === 'files' && agent.worktreePath !== undefined && noteOf(agent.worktreePath) === undefined) void loadDiff(agent)
+}
+
+/** Stores a step, tells the page's cursor what it must (`h l j k [ ]`), and redraws. */
+function commit(env: SlotEnv, step: Step, keys: readonly PageKey[] = step.ui === undefined ? [] : [step.ui]): void {
+ const state = env.ctx.state
+ const wf = env.ctx.act.workflows
+
+ drills.set(state, step.drill)
+ if (step.said === undefined) said.delete(state)
+ else said.set(state, step.said)
+
+ if (keys.length === 0) wf.setUi({})
+ else for (const key of keys) wf.key(key)
+
+ ensureLoaded(env, step.drill)
+}
+
+type Verb = 'in' | 'out' | 'next' | 'prev' | 'sub' | 'follow' | 'filter' | 'scope' | 'search'
+
+/** What the keys do, by name; the registered hotkeys, the buttons and `drillKey` all come here. */
+export function drillKey(env: SlotEnv, verb: Verb): void {
+ const m = modelOf(env)
+ const here = hereOf(env, m)
+ const d = m.drill
+
+ switch (verb) {
+ case 'in':
+ return commit(env, deeper(d, here))
+ case 'out':
+ return commit(env, shallower(d))
+ case 'next':
+ case 'prev': {
+ const step = move(d, verb === 'next' ? 1 : -1, here)
+ // The page moves a phase or an agent by its column: say which column first.
+ const keys: PageKey[] = step.ui === undefined ? [] : d.level === 'phases' ? ['h', step.ui] : d.level === 'agents' ? ['l', step.ui] : [step.ui]
+
+ return commit(env, step, keys)
+ }
+ case 'sub':
+ return commit(env, { drill: nextSub(d) })
+ case 'follow':
+ return commit(env, { drill: { ...d, follow: !d.follow } })
+ case 'filter':
+ return commit(env, { drill: { ...d, filter: nextFilter(d.filter), logSel: 0 } })
+ case 'scope':
+ return commit(env, { drill: { ...d, scope: d.scope === 'agent' ? 'phase' : 'agent', logSel: 0 } })
+ case 'search':
+ commit(env, { drill: { ...d, isSearching: true } })
+ env.ctx.act.focus('wf-search')
+ }
+}
+
+/** Goes to a search hit: the page's cursor, then the drill's place. */
+export function jumpTo(env: SlotEnv, target: Target): void {
+ const wf = env.ctx.act.workflows
+ const next = jump(drillOf(env.ctx.state), target, '')
+ const run = env.runs[target.run]
+ const agent = run?.phases[target.phase]?.agents[target.agent]
+
+ drills.set(env.ctx.state, { ...next.drill, at: run === undefined ? '' : `${run.id}/${agent?.id ?? ''}` })
+ said.delete(env.ctx.state)
+ wf.setUi(next.ui)
+ wf.tab('detail')
+ ensureLoaded({ ...env, run: run ?? null, phase: run?.phases[target.phase] ?? null, agent: agent ?? null }, next.drill)
+}
+
+/** Keeps the search text the person typed (the field's own value), and redraws. */
+export function setQuery(env: SlotEnv, query: string): void {
+ drills.set(env.ctx.state, { ...sync(drillOf(env.ctx.state), keyOf(env)), query: query.slice(0, 80) })
+ env.ctx.act.workflows.setUi({})
+}
+
+const opsOf = (env: SlotEnv, m: Model): Ops => ({
+ sub: (sub: Sub) => commit(env, { drill: { ...m.drill, sub, scroll: 0, level: m.drill.level === 'item' ? 'agent' : m.drill.level } }),
+ follow: () => drillKey(env, 'follow'),
+ filter: () => drillKey(env, 'filter'),
+ scope: () => drillKey(env, 'scope'),
+ scroll: by => commit(env, { drill: { ...m.drill, scroll: Math.max(0, m.drill.scroll + by) } }),
+})
+
+/** The breadcrumb: each level so far as a button that goes back to it, the level you are on in bold. */
+function breadcrumb(env: SlotEnv, m: Model): RenderElement {
+ const { ctx } = env
+ const names: Record<DrillLevel, string> = {
+ runs: env.run?.name ?? '—',
+ phases: env.phase?.title ?? '—',
+ agents: env.agent?.label ?? '—',
+ agent: '',
+ item: m.drill.sub === 'log' ? `line ${m.drill.follow ? m.lines.length : m.drill.logSel + 1}` : `call ${m.drill.callSel + 1}`,
+ }
+ const parts: RenderElement[] = []
+
+ for (const crumb of crumbs(m.drill)) {
+ const label = crumb.level === 'agent' ? crumb.label : `${LEVEL_NAME[crumb.level]}: ${clip(names[crumb.level], 16)}`
+
+ if (parts.length > 0) parts.push(text(ctx, ' › ', { dimColor: true }))
+ parts.push(crumb.isHere ? ctx.kit.Text({ bold: true, color: THEME.head, children: label }) : button(ctx, `wf-crumb-${crumb.level}`, label, () => commit(env, toLevel(m.drill, crumb.level))))
+ }
+
+ return row(ctx, parts, 'wf-crumbs')
+}
+
+function list(env: SlotEnv, m: Model): RenderElement[] {
+ const { ctx } = env
+ const rows: RenderElement[] = []
+ const win = <T,>(items: readonly T[], at: number): { from: number; shown: readonly T[] } => {
+ const from = Math.max(0, Math.min(items.length - 8, at - 7))
+
+ return { from, shown: items.slice(from, from + 8) }
+ }
+
+ if (m.drill.level === 'runs') {
+ const w = win(env.runs, env.ui.run)
+
+ for (const [i, run] of w.shown.entries()) rows.push(text(ctx, `${w.from + i === env.ui.run ? '▸' : ' '} ${clip(run.name, 30)} ${run.state} · ${run.total} agents · ${run.kind === 'workflow' ? (run.totalTokens === null ? 'tokens n/a' : `${fmtTokens(run.totalTokens, run.isTokensPartial)} tok`) : 'ruflo swarm'}`, w.from + i === env.ui.run ? { bold: true } : {}))
+ if (env.runs.length > 8) rows.push(text(ctx, `${env.runs.length} runs: m w move`, { dimColor: true }))
+ } else if (m.drill.level === 'phases' && env.run !== null) {
+ const w = win(env.run.phases, env.ui.phase)
+
+ for (const [i, phase] of w.shown.entries()) rows.push(text(ctx, `${w.from + i === env.ui.phase ? '▸' : ' '} ${clip(`${w.from + i + 1} ${phase.title}`, 30)} ${phase.done}/${phase.total} done${phase.running > 0 ? ` · ${phase.running} running` : ''}${phase.failed > 0 ? ` · ${phase.failed} failed` : ''}`, w.from + i === env.ui.phase ? { bold: true } : {}))
+ } else if (m.drill.level === 'agents' && env.phase !== null) {
+ const w = win(env.phase.agents, env.ui.agent)
+
+ for (const [i, agent] of w.shown.entries()) rows.push(text(ctx, `${w.from + i === env.ui.agent ? '▸' : ' '} ${clip(agent.label, 30)} ${agent.state} · ${agent.toolCalls === undefined ? 'calls n/a' : `${agent.toolCalls} calls`} · ${fmtElapsed(agent.elapsedMs)}`, w.from + i === env.ui.agent ? { bold: true } : {}))
+ if (env.phase.agents.length === 0) rows.push(text(ctx, 'No agent has started in this phase yet.', { dimColor: true }))
+ }
+
+ return rows
+}
+
+const HOT: Partial<Record<Verb, string>> = {}
+
+const hint = (verb: Verb, what: string): string => `${HOT[verb] ?? '·'} ${what}`
+
+/** The board slot: collapsed to a hint line until opened. */
+function panel(env: SlotEnv): RenderElement[] {
+ const { ctx } = env
+ const m = modelOf(env)
+ const msg = said.get(ctx.state)
+
+ if (!m.drill.open) {
+ return [
+ row(ctx, [button(ctx, 'wf-drill-open', 'Drill into this run', () => drillKey(env, 'in')), text(ctx, ` ${hint('in', 'deeper')} · ${hint('search', 'search')} — runs › phases › agents › one agent (activity, log, files, result) › one call`, { dimColor: true })]),
+ ...(msg === undefined ? [] : [text(ctx, msg, { color: THEME.warn })]),
+ ]
+ }
+
+ const ops = opsOf(env, m)
+ const body: RenderElement[] =
+ m.drill.level === 'agent' && env.run !== null && env.agent !== null
+ ? agentBody(ctx, env.run, env.agent, m, ops)
+ : m.drill.level === 'item' && env.agent !== null
+ ? itemBody(ctx, env.agent, m, ops)
+ : list(env, m)
+
+ return [
+ breadcrumb(env, m),
+ row(ctx, [button(ctx, 'wf-drill-in', '▸ deeper', () => drillKey(env, 'in')), button(ctx, 'wf-drill-out', m.drill.level === 'runs' ? '✕ close' : '◂ back', () => drillKey(env, 'out')), button(ctx, 'wf-drill-prev', '▴ prev', () => drillKey(env, 'prev')), button(ctx, 'wf-drill-next', '▾ next', () => drillKey(env, 'next'))], 'wf-drill-moves'),
+ ...(msg === undefined ? [] : [text(ctx, msg, { color: THEME.warn })]),
+ col(ctx, body, 'wf-drill-body'),
+ text(ctx, `keys: ${hint('in', 'deeper')} · ${hint('out', 'back')} · ${hint('next', 'next')} · ${hint('prev', 'prev')} · ${hint('sub', 'next tab')} · ${hint('follow', 'follow')} · ${hint('filter', 'level')} · ${hint('search', 'search')}`, { dimColor: true }),
+ ]
+}
+
+/** Each key tries its letters in turn: another feature may have taken one, and a slot is refused (not thrown) for a taken key. */
+const KEYS: readonly { verb: Verb; label: string; letters: string }[] = [
+ { verb: 'in', label: '▸ deeper', letters: 'ge' },
+ { verb: 'out', label: '◂ back', letters: 'zq' },
+ { verb: 'next', label: '▾ next', letters: 'mc' },
+ { verb: 'prev', label: '▴ prev', letters: 'wa' },
+ { verb: 'sub', label: 'tab ▸', letters: 'tv' },
+ { verb: 'follow', label: 'follow', letters: 'fs' },
+ { verb: 'filter', label: 'level', letters: 'vy' },
+ { verb: 'search', label: 'search', letters: 'sk0123456789' },
+]
+
+/** Registers the panel and its keys. Returns what was refused and why (empty when all went in), for a test or the merge owner to see. */
+export function registerDrill(): { verb: string; why: string }[] {
+ const refused: { verb: string; why: string }[] = []
+
+ const board = registerSlot({ kind: 'board', id: 'drill', title: 'Drill-down', order: 10, render: panel })
+
+ if (!board.ok) refused.push({ verb: 'panel', why: board.why })
+
+ for (const key of KEYS) {
+ let last = 'no letter left'
+
+ for (const letter of key.letters) {
+ const done = registerSlot({ kind: 'key', id: `drill-${key.verb}`, key: letter, label: key.label, run: env => drillKey(env, key.verb) })
+
+ if (done.ok) {
+ HOT[key.verb] = letter
+ last = ''
+ break
+ }
+
+ last = done.why
+ if (last.includes('already registered')) break
+ }
+
+ if (last !== '') refused.push({ verb: key.verb, why: last })
+ }
+
+ registerSlot({
+ kind: 'notice',
+ id: 'drill-follow',
+ // A page read just finished: a followed log of a transcript too large to hold whole is read again (its tail), once per read, never otherwise.
+ between: () => {
+ const d = boundState === null ? null : drillOf(boundState)
+
+ if (d !== null && d.open && d.follow && d.sub === 'log' && (d.level === 'agent' || d.level === 'item')) void reloadTails()
+
+ return []
+ },
+ })
+
+ return refused
+}
+
+export const hotkeyOf = (verb: Verb): string | undefined => HOT[verb]
diff --git a/plugins/ruflo-console/hooks/views/wf-drill-body.ts b/plugins/ruflo-console/hooks/views/wf-drill-body.ts
new file mode 100644
index 0000000000..973b2391e1
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/wf-drill-body.ts
@@ -0,0 +1,234 @@
+/**
+ * What the drill-down draws from one agent down (ADR-459): the four sub-tabs (Activity, Log, Files, Result) and one call or message in
+ * full. Drawing only: every number comes from the parsed transcript, the journal's result or the worktree probe, and where a source has
+ * not been read the page says which and offers the button that reads it (or says the host binding that would is not attached).
+ * The caps in force are printed beside what they cut: the transcript read cap, the characters kept per field, the rows on screen.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { durationOf, fmtSpan, FIELD_CAP, ENTRY_CAP, type CallEntry, type Capped, type Entry, type Parsed } from '../data/wf-activity'
+import { diffOf, isBound, loadDiff, loadResult, loadTranscript, noteOf, resultOf, textOf } from '../data/wf-drill-io'
+import { clockOf, tailWindow, type LogLine } from '../data/wf-log'
+import { SUBS, SUB_NAME, type Drill, type Sub } from '../data/wf-trail'
+import { TAIL_BYTES, TRANSCRIPT_CAP } from '../data/workflows-read'
+import { fmtTokens, type WfAgent, type WfRun } from '../data/workflows'
+import { button, clip, row, text, THEME, type Ctx } from './common'
+import type { LevelFilter } from '../data/wf-log'
+
+export type Model = { drill: Drill; parsed: Parsed | null; lines: LogLine[]; /** Phase scope: agents of the phase whose transcript is not in memory. */ unread: number }
+
+/** What the body can ask the panel to do. */
+export type Ops = { sub: (sub: Sub) => void; follow: () => void; filter: () => void; scope: () => void; scroll: (by: number) => void }
+
+const mb = (bytes: number): string => (bytes < 100_000 ? `${Math.max(1, Math.round(bytes / 1000))} KB` : `${(bytes / 1_000_000).toFixed(1)} MB`)
+const cap = (bytes: number): string => `${(bytes / 1_000_000).toFixed(1)} MB`
+const ROWS = 10
+const ITEM_ROWS = 20
+const CALL_MARK = { ok: '✔', error: '✖', pending: '…' } as const
+const CALL_COLOR = { ok: THEME.ok, error: THEME.bad, pending: THEME.warn } as const
+const FILTER_WORD: Record<LevelFilter, string> = { all: 'all lines', text: 'messages', tool: 'tool calls', error: 'errors only' }
+
+/** A line the page says in place of a source it has not got: why, and the button that gets it (or why there is none). */
+function unread(ctx: Ctx, what: string, path: string | undefined, load: () => void): RenderElement[] {
+ const note = path === undefined ? undefined : noteOf(path)
+ const why = note?.phase === 'failed' ? ` (${note.why ?? 'the read failed'})` : note?.phase === 'loading' ? ' (reading…)' : ''
+
+ return [
+ text(ctx, `${what} is not in memory${why}.`, { color: THEME.warn }),
+ isBound()
+ ? row(ctx, [button(ctx, 'wf-drill-load', note?.phase === 'loading' ? 'reading…' : `Read it (up to ${cap(TRANSCRIPT_CAP)}; the last ${Math.round(TAIL_BYTES / 1000)} KB of a larger file)`, load)])
+ : text(ctx, 'The page reads a live run\'s transcripts as it refreshes; a finished run\'s figures come from its record, so they are not read. Reading them on demand needs the drill bound to the host (ADR-459).', { dimColor: true }),
+ ]
+}
+
+function subTabs(ctx: Ctx, drill: Drill, ops: Ops): RenderElement {
+ return row(ctx, [text(ctx, 'view'), ...SUBS.map(sub => button(ctx, `wf-sub-${sub}`, `${drill.sub === sub ? '●' : '○'} ${SUB_NAME[sub]}`, () => ops.sub(sub)))], 'wf-subs')
+}
+
+const sourceLine = (ctx: Ctx, agent: WfAgent, parsed: Parsed, cache: Ctx['state']['cache']): RenderElement => {
+ const read = textOf(cache, agent)
+ const bytes = read === null ? 0 : read.text.length
+ const how = parsed.isTail ? `the last ${Math.round(TAIL_BYTES / 1000)} KB of a file over the ${cap(TRANSCRIPT_CAP)} read cap (earlier calls are not here)` : `whole file, ${mb(bytes)} of the ${cap(TRANSCRIPT_CAP)} read cap`
+
+ return text(ctx, `transcript: ${how} · ${parsed.entries.length} entries${parsed.dropped > 0 ? ` (newest ${ENTRY_CAP} of ${parsed.entries.length + parsed.dropped})` : ''} · ${parsed.calls.length} tool calls`, { dimColor: true })
+}
+
+function activity(ctx: Ctx, m: Model, agent: WfAgent): RenderElement[] {
+ const parsed = m.parsed
+
+ if (parsed === null) return []
+ if (parsed.calls.length === 0) return [text(ctx, 'No tool call in the part of the transcript read.', { dimColor: true })]
+
+ const sel = Math.max(0, Math.min(parsed.calls.length - 1, m.drill.callSel))
+ const from = Math.max(0, Math.min(parsed.calls.length - ROWS, sel - ROWS + 1))
+ const first = parsed.calls[0] as CallEntry
+ const origin = first.atMs
+ const rows: RenderElement[] = parsed.calls.slice(from, from + ROWS).map(call => {
+ const here = call.callIndex === sel
+ const at = origin === undefined || call.atMs === undefined ? ' ' : `+${fmtSpan(call.atMs - origin)}`.padEnd(7)
+
+ return row(ctx, [
+ ctx.kit.Text({ ...(here && { bold: true }), children: `${here ? '▸' : ' '}#${String(call.callIndex + 1).padEnd(3)}` }),
+ ctx.kit.Text({ color: CALL_COLOR[call.status], children: `${CALL_MARK[call.status]} ` }),
+ ctx.kit.Text({ ...(here && { bold: true }), wrap: 'truncate-end', children: clip(`${call.tool.padEnd(10)} ${call.summary}`, Math.max(12, ctx.columns - 26)) }),
+ ctx.kit.Text({ dimColor: true, children: ` ${at}${fmtSpan(durationOf(call)).padStart(6)}` }),
+ ])
+ })
+
+ return [...rows, text(ctx, `${from > 0 ? `${from} earlier · ` : ''}${Math.max(0, parsed.calls.length - from - ROWS)} later · call ${sel + 1} of ${parsed.calls.length} · ${agent.toolCalls !== undefined && agent.toolCalls !== parsed.calls.length ? `the run says ${agent.toolCalls} in all · ` : ''}open it for the full input and output`, { dimColor: true })]
+}
+
+function log(ctx: Ctx, m: Model, ops: Ops, isPhase: boolean): RenderElement[] {
+ const window = tailWindow(m.lines, { sel: m.drill.logSel, follow: m.drill.follow })
+ const head = row(ctx, [
+ button(ctx, 'wf-log-follow', m.drill.follow ? '● following' : '○ follow', ops.follow),
+ button(ctx, 'wf-log-filter', `level: ${FILTER_WORD[m.drill.filter]}`, ops.filter),
+ button(ctx, 'wf-log-scope', isPhase ? 'scope: whole phase' : 'scope: this agent', ops.scope),
+ ], 'wf-log-head')
+
+ if (window.total === 0) return [head, text(ctx, m.drill.filter === 'all' ? 'No line in the part of the transcript read.' : `No ${FILTER_WORD[m.drill.filter]} among the lines read: change the level.`, { dimColor: true })]
+
+ const rows = window.rows.map((line, i) => {
+ const here = i === window.at
+
+ return row(ctx, [
+ ctx.kit.Text({ ...(here && { bold: true }), children: `${here ? '▸' : ' '}${clockOf(line.atMs)} ` }),
+ ctx.kit.Text({ color: line.level === 'error' ? THEME.bad : line.level === 'tool' ? THEME.info : line.level === 'assistant' ? THEME.ok : undefined, dimColor: line.level === 'thinking' || line.level === 'user', children: `${line.level.slice(0, 4).padEnd(5)}` }),
+ ...(isPhase ? [ctx.kit.Text({ dimColor: true, children: `${clip(line.agent, 14).padEnd(15)}` })] : []),
+ ctx.kit.Text({ ...(here && { bold: true }), wrap: 'truncate-end', children: clip(line.text, Math.max(12, ctx.columns - (isPhase ? 38 : 22))) }),
+ ])
+ })
+
+ return [
+ head,
+ ...rows,
+ text(ctx, `${window.above} above · ${window.below} below · line ${window.from + window.at + 1} of ${window.total}${m.unread > 0 ? ` · ${m.unread} agents of the phase not in memory` : ''}`, { dimColor: true }),
+ text(ctx, 'follow pins the newest line and is re-drawn on this page\'s refresh; it is not a stream', { dimColor: true }),
+ ]
+}
+
+function files(ctx: Ctx, m: Model, agent: WfAgent): RenderElement[] {
+ const parsed = m.parsed
+ const diff = diffOf(agent)
+ const wt = agent.worktreePath
+ const note = wt === undefined ? undefined : noteOf(wt)
+ const rel = (path: string): string => (wt !== undefined && path.startsWith(`${wt}/`) ? path.slice(wt.length + 1) : path)
+ const rows: RenderElement[] = []
+
+ if (wt === undefined) rows.push(text(ctx, agent.hasWorktree ? 'The agent ran in a worktree whose path its metadata does not name: no diff stat.' : 'This agent has no worktree, so there is no diff stat: the list below is only the files its tool inputs name.', { dimColor: true }))
+ else if (diff !== undefined) rows.push(text(ctx, `worktree ${clip(wt, Math.max(20, ctx.columns - 40))} · ${diff.files.size + diff.extra} changed files vs HEAD (tracked files only; \`git diff --numstat\`)`, { dimColor: true }))
+ else rows.push(row(ctx, [text(ctx, `worktree ${clip(wt, Math.max(20, ctx.columns - 50))}`, { dimColor: true }), ...(isBound() ? [button(ctx, 'wf-diff-load', note?.phase === 'loading' ? 'reading…' : 'Read diff stat', () => void loadDiff(agent))] : [text(ctx, ' diff stat: n/a (host not bound)', { dimColor: true })])]))
+
+ if (note?.phase === 'failed' || note?.phase === 'none') rows.push(text(ctx, `diff stat not read: ${note.why ?? 'failed'}`, { color: THEME.warn }))
+
+ const touched = parsed?.files ?? []
+ const named = new Set(touched.map(file => rel(file.path)))
+
+ for (const file of touched.slice(0, 14)) {
+ const stat = diff?.files.get(rel(file.path))
+ const ops = `${file.edit > 0 ? `edit×${file.edit} ` : ''}${file.write > 0 ? `write×${file.write} ` : ''}${file.read > 0 ? `read×${file.read}` : ''}`.trim()
+
+ rows.push(row(ctx, [
+ ctx.kit.Text({ dimColor: file.edit + file.write === 0, wrap: 'truncate-end', children: ` ${clip(file.path, Math.max(14, ctx.columns - 38))} ` }),
+ ctx.kit.Text({ dimColor: true, children: ops.padEnd(18) }),
+ ...(stat === undefined ? [] : [ctx.kit.Text({ color: THEME.ok, children: stat.add === null ? ' bin' : ` +${stat.add}` }), ctx.kit.Text({ color: THEME.bad, children: stat.del === null ? '' : ` -${stat.del}` })]),
+ ]))
+ }
+
+ if (touched.length === 0) rows.push(text(ctx, 'No tool input names a file in the part of the transcript read.', { dimColor: true }))
+ if (touched.length > 14) rows.push(text(ctx, `+${touched.length - 14} more files named`, { dimColor: true }))
+
+ if (diff !== undefined) {
+ const others = [...diff.files].filter(([path]) => !named.has(path))
+
+ if (others.length > 0) rows.push(text(ctx, `also changed in the worktree, not named by a tool input (e.g. by a shell command): ${others.slice(0, 5).map(([path, s]) => `${clip(path, 40)} +${s.add ?? '·'} -${s.del ?? '·'}`).join(', ')}${others.length > 5 ? ` +${others.length - 5} more` : ''}`, { dimColor: true }))
+ }
+
+ return rows
+}
+
+function result(ctx: Ctx, run: WfRun, agent: WfAgent): RenderElement[] {
+ const held = resultOf(run, agent)
+ const note = noteOf(`${run.id}/${agent.id}`)
+
+ if (held === undefined) {
+ return [
+ ...(agent.resultPreview !== undefined ? [text(ctx, `preview: ${agent.resultPreview}`, { dimColor: true })] : []),
+ ...unread(ctx, 'The agent\'s return', `${run.id}/${agent.id}`, () => void loadResult(run, agent)).slice(0, 1),
+ ...(isBound() ? [row(ctx, [button(ctx, 'wf-result-load', note?.phase === 'loading' ? 'reading…' : 'Read the journal (up to 1.0 MB)', () => void loadResult(run, agent))])] : [text(ctx, 'Reading the journal needs the drill bound to the host (ADR-459).', { dimColor: true })]),
+ ]
+ }
+
+ if (held === 'none') return [text(ctx, agent.state === 'done' ? 'The journal holds no result for this agent.' : `No result yet: the agent is ${agent.state}.`, { dimColor: true })]
+
+ return blockRows(ctx, 'result', held, 0, ITEM_ROWS).rows
+}
+
+/** A washed block as screen rows: `max` lines from line `from`, hard-wrapped to the width; and how many lines the block has. */
+export function blockRows(ctx: Ctx, title: string, block: Capped, from: number, max: number): { rows: RenderElement[]; total: number } {
+ const width = Math.max(20, ctx.columns - 4)
+ const lines = block.text.split('\n').flatMap(line => (line.length <= width ? [line] : (line.match(new RegExp(`.{1,${width}}`, 'g')) ?? [line])))
+ const shown = lines.slice(from, from + max)
+ const rows: RenderElement[] = [text(ctx, `${title} · ${block.isCut ? `first ${block.text.length.toLocaleString('en-US')} of ${block.total.toLocaleString('en-US')} characters (cap ${FIELD_CAP.toLocaleString('en-US')})` : `${block.total.toLocaleString('en-US')} characters`} · lines ${Math.min(from + 1, lines.length)}–${from + shown.length} of ${lines.length}`, { bold: true })]
+
+ for (const line of shown) rows.push(ctx.kit.Text({ wrap: 'truncate-end', children: ` ${line}` }))
+
+ return { rows, total: lines.length }
+}
+
+/** The sub-tab rows of one agent. */
+export function agentBody(ctx: Ctx, run: WfRun, agent: WfAgent, m: Model, ops: Ops): RenderElement[] {
+ const rows: RenderElement[] = [subTabs(ctx, m.drill, ops)]
+ const tokens = agent.tokens === undefined ? '' : ` · ${fmtTokens(agent.tokens, agent.isTokensPartial)} tok`
+
+ rows.push(text(ctx, `${agent.label} · ${agent.state}${tokens}${agent.model === undefined ? '' : ` · ${agent.model}`}`, { dimColor: true }))
+
+ if (agent.ruflo !== undefined) return [...rows, text(ctx, 'A ruflo agent keeps no transcript, worktree or return: its row on the board is everything the store records.', { dimColor: true })]
+
+ if (m.drill.sub === 'files' || m.drill.sub === 'result') {
+ if (m.parsed !== null) rows.push(sourceLine(ctx, agent, m.parsed, ctx.state.cache))
+
+ return [...rows, ...(m.drill.sub === 'files' ? files(ctx, m, agent) : result(ctx, run, agent))]
+ }
+
+ if (m.parsed === null && !(m.drill.sub === 'log' && m.drill.scope === 'phase' && m.lines.length > 0)) return [...rows, ...unread(ctx, 'This agent\'s transcript', agent.transcriptPath, () => void loadTranscript(agent))]
+
+ if (m.parsed !== null) rows.push(sourceLine(ctx, agent, m.parsed, ctx.state.cache))
+
+ return [...rows, ...(m.drill.sub === 'activity' ? activity(ctx, m, agent) : log(ctx, m, ops, m.drill.scope === 'phase'))]
+}
+
+const KIND = (entry: Entry): string => (entry.kind === 'call' ? `tool call ${entry.tool}` : `${entry.role} message`)
+
+/** One call or message in full: its input and output (calls), or its text, washed and capped, scrolled by the person. */
+export function itemBody(ctx: Ctx, agent: WfAgent, m: Model, ops: Ops): RenderElement[] {
+ const parsed = m.parsed
+ const line = m.drill.sub === 'log' ? m.lines[Math.max(0, Math.min(m.lines.length - 1, m.drill.logSel))] : undefined
+
+ if (line !== undefined && line.agentId !== agent.id) return [text(ctx, `That line is from agent ${line.agent}: go back to Agents and open that agent to see it in full.`, { dimColor: true })]
+
+ const entry: Entry | undefined = parsed === null ? undefined : line !== undefined ? parsed.entries[line.entry] : m.drill.sub === 'log' ? undefined : parsed.calls[Math.max(0, Math.min(parsed.calls.length - 1, m.drill.callSel))]
+
+ if (entry === undefined) return [text(ctx, 'Nothing is selected: go back and pick a call or a line.', { dimColor: true })]
+
+ const rows: RenderElement[] = [text(ctx, `${KIND(entry)} · #${entry.index + 1} of ${parsed?.entries.length ?? 0} · ${clockOf(entry.atMs)}${entry.kind === 'call' ? ` · ${entry.status} · ${fmtSpan(durationOf(entry))}` : ''}`, { bold: true })]
+ const blocks: [string, Capped][] = entry.kind === 'call' ? [['input', entry.input], ...(entry.output === null ? [] : ([['output', entry.output]] as [string, Capped][]))] : [['text', entry.body]]
+ let from = m.drill.scroll
+ let budget = ITEM_ROWS
+ let total = 0
+
+ for (const [title, block] of blocks) {
+ const drawn = blockRows(ctx, title, block, Math.max(0, from), budget)
+
+ total += drawn.total
+ rows.push(...drawn.rows)
+ from -= drawn.total
+ budget = Math.max(2, budget - (drawn.rows.length - 1))
+ }
+
+ if (entry.kind === 'call' && entry.output === null) rows.push(text(ctx, entry.status === 'pending' ? 'No result for this call in the part of the transcript read (it may still be running, or lie before the tail).' : 'No output.', { dimColor: true }))
+
+ rows.push(row(ctx, [button(ctx, 'wf-item-up', '▴ up', () => ops.scroll(-ITEM_ROWS / 2)), button(ctx, 'wf-item-down', '▾ down', () => ops.scroll(ITEM_ROWS / 2)), text(ctx, ` ${total} lines in all`, { dimColor: true })], 'wf-item-scroll'))
+
+ return rows
+}
diff --git a/plugins/ruflo-console/hooks/views/wf-search.ts b/plugins/ruflo-console/hooks/views/wf-search.ts
new file mode 100644
index 0000000000..128dd86d93
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/wf-search.ts
@@ -0,0 +1,99 @@
+/**
+ * The search box of the Workflows drill-down (ADR-459), a board slot under the drill panel. One field searches every level at once:
+ * run names, phase titles, agent labels, tool calls, transcript text and, where the project has them, mission tasks. Hits are listed
+ * by level, and a hit (a click, or Enter in the field for the first) jumps to the exact place: the run, phase and agent under the
+ * cursor, then the sub-tab and the call or line. It looks only through what is in memory and says how much that was, what was left
+ * unread, and the cap; a button reads the run's transcripts when the host is bound.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { MAX_QUERY, flatHits, HIT_NAME, HIT_ORDER, MAX_SHOWN, MIN_QUERY, SCAN_CHARS, search, type Hit, type MissionTaskRef, type SearchResult } from '../data/wf-search'
+import { isBound, LOAD_BUDGET, loadRun, parsedOf } from '../data/wf-drill-io'
+import { button, clip, col, row, text, THEME } from './common'
+import { drillOf, jumpTo, setQuery } from './wf-detail'
+import { registerSlot, type SlotEnv } from './wf-slots'
+
+const memo = new WeakMap<object, { query: string; sig: string; result: SearchResult }>()
+
+const tasksOf = (env: SlotEnv): MissionTaskRef[] =>
+ (env.ctx.state.snapshot?.missions?.missions ?? []).flatMap(mission => mission.plan.tasks.map(task => ({ mission: mission.objective, id: task.id, title: task.title, status: task.status }))).slice(0, 400)
+
+/** The search for this frame, kept while the query, the runs and what is parsed in memory are the same (a frame is drawn far more often than any of them changes). */
+export function resultOf(env: SlotEnv, query: string): SearchResult {
+ const cache = env.ctx.state.cache
+ const parsed = env.runs.flatMap(run => run.phases.flatMap(phase => phase.agents)).map(agent => (agent.ruflo === undefined ? parsedOf(cache, agent) : null))
+ const sig = `${env.runs.length}:${parsed.map(p => p?.entries.length ?? -1).join(',')}:${tasksOf(env).length}`
+ const held = memo.get(env.ctx.state)
+
+ if (held !== undefined && held.query === query && held.sig === sig) return held.result
+
+ const byAgent = new Map(env.runs.flatMap(run => run.phases.flatMap(phase => phase.agents)).map((agent, i) => [agent, parsed[i] ?? null] as const))
+ const result = search({ runs: env.runs, parsed: agent => byAgent.get(agent) ?? null, tasks: tasksOf(env) }, query)
+
+ memo.set(env.ctx.state, { query, sig, result })
+
+ return result
+}
+
+const mark = (hit: Hit): string => (hit.target === undefined ? '↗' : '▸')
+
+function hitButton(env: SlotEnv, hit: Hit, i: number): RenderElement {
+ const { ctx } = env
+
+ return button(ctx, `wf-hit-${hit.level}-${i}`, `${mark(hit)} ${clip(hit.title, Math.max(14, Math.floor(ctx.columns / 2) - 4))} ${clip(hit.detail, Math.max(10, Math.floor(ctx.columns / 2) - 8))}`, () => (hit.target === undefined ? ctx.act.view('missions') : jumpTo(env, hit.target)))
+}
+
+/** The board slot's rows. */
+export function searchPanel(env: SlotEnv): RenderElement[] {
+ const { ctx } = env
+ const drill = drillOf(ctx.state)
+ const Input = ctx.kit.Input
+
+ if (Input === undefined) return [text(ctx, 'Search needs a text field, which this surface does not have.', { dimColor: true })]
+
+ const result = resultOf(env, drill.query)
+ const first = flatHits(result).find(hit => hit.target !== undefined)
+ const rows: RenderElement[] = [
+ Input({ key: 'wf-search', label: 'search', value: drill.query, placeholder: `${MIN_QUERY}+ characters: a run, label, tool call, transcript text or mission task`, submitLabel: 'go', onInput: (value: string) => setQuery(env, value), onSubmit: (value: string) => {
+ setQuery(env, value)
+
+ const hit = flatHits(resultOf(env, value.trim().slice(0, MAX_QUERY))).find(entry => entry.target !== undefined)
+
+ if (hit?.target !== undefined) jumpTo(env, hit.target)
+ } }),
+ ]
+
+ if (!result.isSearched) return [...rows, text(ctx, drill.query.trim() === '' ? 'Type to search every level at once; Enter jumps to the first hit.' : `Type at least ${MIN_QUERY} characters.`, { dimColor: true })]
+
+ const total = HIT_ORDER.reduce((sum, level) => sum + result.counts[level], 0)
+
+ rows.push(text(ctx, total === 0 ? `No match for "${clip(result.query, 40)}".` : `${total} matches · Enter in the field goes to ${first === undefined ? 'none with a place' : 'the first'}`, total === 0 ? { color: THEME.warn } : { dimColor: true }))
+
+ for (const level of HIT_ORDER) {
+ const hits = result.groups[level]
+
+ if (hits.length === 0) continue
+
+ rows.push(text(ctx, `${HIT_NAME[level]} (${result.counts[level]}${result.counts[level] > MAX_SHOWN ? `, first ${MAX_SHOWN} shown` : ''})`, { bold: true }))
+ for (const [i, hit] of hits.entries()) rows.push(hitButton(env, hit, i))
+ }
+
+ rows.push(text(ctx, `looked through ${result.scanned} agents' transcripts (${result.chars.toLocaleString('en-US')} characters of ${SCAN_CHARS.toLocaleString('en-US')} cap)${result.isCapped ? ' · the cap stopped the scan' : ''}`, { dimColor: true }))
+
+ if (result.unread > 0) rows.push(text(ctx, `${result.unread} agents' transcripts are not in memory, so they were not searched`, { color: THEME.warn }))
+
+ if (result.unread > 0 && env.run !== null) {
+ const run = env.run
+
+ rows.push(isBound() ? row(ctx, [button(ctx, 'wf-search-load', `Read this run's transcripts (up to ${(LOAD_BUDGET / 1_000_000).toFixed(0)} MB in all)`, () => void loadRun(run).then(() => ctx.act.workflows.setUi({})))]) : text(ctx, 'Reading them on demand needs the drill bound to the host (ADR-459).', { dimColor: true }))
+ }
+
+ return [col(ctx, rows, 'wf-search-panel')]
+}
+
+/** Registers the search slot; returns why it was refused, or null. */
+export function registerSearch(): string | null {
+ const done = registerSlot({ kind: 'board', id: 'drill-search', title: 'Search', order: 11, render: searchPanel })
+
+ return done.ok ? null : done.why
+}
diff --git a/plugins/ruflo-console/hooks/wf-drill.ts b/plugins/ruflo-console/hooks/wf-drill.ts
new file mode 100644
index 0000000000..1fd08818ac
--- /dev/null
+++ b/plugins/ruflo-console/hooks/wf-drill.ts
@@ -0,0 +1,22 @@
+/**
+ * The drill-down of the Workflows page (ADR-459), switched on by one line in views/wf-register.ts:
+ *
+ * import '../wf-drill'
+ *
+ * Importing registers the drill panel, its keys, the search slot and the follow tick through the page's slots; nothing else is edited.
+ * `bindWorkflowDrill(state, host)` is the one optional call that lets the buttons read what the page's own refresh does not (a finished
+ * run's transcripts, a journal's result, a worktree's diff stat, the tail of a transcript over the read cap); unbound, everything the
+ * console's read cache holds is still drawn, and the page says what it could not read and why.
+ */
+import { bindDrill, type DrillHost } from './data/wf-drill-io'
+import type { State } from './state'
+import { registerDrill, watchState } from './views/wf-detail'
+import { registerSearch } from './views/wf-search'
+
+/** What registering the slots came to: anything refused, with the reason (a hotkey another feature already holds, a full slot kind). */
+export const refused: { slot: string; why: string }[] = [...registerDrill().map(entry => ({ slot: entry.verb, why: entry.why })), ...[registerSearch()].flatMap(why => (why === null ? [] : [{ slot: 'search', why }]))]
+
+export function bindWorkflowDrill(state: State, host: DrillHost): void {
+ bindDrill(state, host)
+ watchState(state)
+}
diff --git a/plugins/ruflo-console/tests/fixtures/wf-drill-world.ts b/plugins/ruflo-console/tests/fixtures/wf-drill-world.ts
new file mode 100644
index 0000000000..74f224a984
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/wf-drill-world.ts
@@ -0,0 +1,131 @@
+/**
+ * The shared world of the drill-down specs (ADR-459): an in-memory disk of a live workflow run, a recording kit, the real page, refresh and
+ * actions, and the helpers that press a registered key or click a button by its key. No engine.
+ */
+import { afterEach, beforeEach, expect } from 'vitest'
+
+import { resetDrillIo } from '../../hooks/data/wf-drill-io'
+import { pick } from '../../hooks/data/workflows-nav'
+import type { WorkflowFs } from '../../hooks/data/workflows-read'
+import type { Host } from '../../hooks/host'
+import { newState, type State } from '../../hooks/state'
+import { workflowsActions } from '../../hooks/wf-actions'
+import { refreshWorkflows, workflowsModelOf } from '../../hooks/wf-live'
+import type { Actions, Ctx, Kit } from '../../hooks/views/common'
+import { registerDrill } from '../../hooks/views/wf-detail'
+import { registerSearch } from '../../hooks/views/wf-search'
+import { resetSlots, slotsFor, type SlotEnv } from '../../hooks/views/wf-slots'
+import { workflowsPage } from '../../hooks/views/wf-page'
+import { line, sample, use } from './wf-drill'
+import { journal, meta, started, T0 } from './workflows'
+
+export const NOW = T0 + 10_000
+export const CONFIG = '/home/u/.claude'
+export const ROOT = `${CONFIG}/projects/-work-proj`
+export const SESSION = '11111111-2222-3333-4444-555555555555'
+export const RUN = `${ROOT}/${SESSION}/subagents/workflows/wf_live`
+export const WT = '/work/proj/.claude/worktrees/agent-a1'
+
+export type El = { kind: string; props: Record<string, unknown> }
+
+export const kit = { Box: (props: Record<string, unknown>): El => ({ kind: 'Box', props }), Text: (props: Record<string, unknown>): El => ({ kind: 'Text', props }), Button: (props: Record<string, unknown>): El => ({ kind: 'Button', props }), Input: (props: Record<string, unknown>): El => ({ kind: 'Input', props }) } as unknown as Kit
+
+export const flat = (node: unknown, out: El[] = []): El[] => {
+ if (Array.isArray(node)) node.forEach(child => flat(child, out))
+ else if (typeof node === 'object' && node !== null) {
+ out.push(node as El)
+ flat((node as El).props?.children, out)
+ }
+
+ return out
+}
+
+export const words = (tree: unknown): string => flat(tree).filter(el => el.kind === 'Text' && typeof el.props.children === 'string').map(el => el.props.children as string).join('\n') + '\n' + flat(tree).filter(el => el.kind === 'Button').map(el => String(el.props.label)).join('\n')
+export const buttonOf = (tree: unknown, key: string): El | undefined => flat(tree).find(el => el.kind === 'Button' && el.props.key === key)
+export const inputOf = (tree: unknown): El | undefined => flat(tree).find(el => el.kind === 'Input' && el.props.key === 'wf-search')
+export const click = (tree: unknown, key: string): void => {
+ const button = buttonOf(tree, key)
+
+ if (button === undefined) throw new Error(`no button ${key}`)
+
+ ;(button.props.onPress as () => void)()
+}
+export const flush = (): Promise<void> => new Promise(done => setTimeout(done, 0))
+
+export function memoryFs(files: Record<string, string>, over: { size?: Record<string, number>; tail?: string } = {}): WorkflowFs & { reads: string[] } {
+ const reads: string[] = []
+ const under = (dir: string) => [...new Set(Object.keys(files).filter(path => path.startsWith(`${dir}/`)).map(path => path.slice(dir.length + 1).split('/')[0] as string))]
+
+ return {
+ reads,
+ read: async path => (reads.push(path), files[path] ?? Promise.reject(new Error('ENOENT'))),
+ stat: async path => (files[path] !== undefined ? { mtimeMs: T0, size: over.size?.[path] ?? files[path].length, kind: 'file' } : under(path).length > 0 ? { mtimeMs: T0, kind: 'directory' } : Promise.reject(new Error('ENOENT'))),
+ list: async dir => {
+ const names = under(dir)
+
+ return names.length === 0 ? Promise.reject(new Error('ENOENT')) : names.map(name => ({ name, mtimeMs: T0, size: files[`${dir}/${name}`]?.length }))
+ },
+ ...(over.tail !== undefined && { readTail: async () => over.tail as string }),
+ }
+}
+
+export const liveFiles = (over: Record<string, string> = {}): Record<string, string> => ({
+ [`${RUN}/journal.jsonl`]: journal(started('a1', 'build:x', 'Build'), started('a2', 'review:x', 'Review')),
+ [`${RUN}/agent-a1.meta.json`]: meta('build:x', 'Build', { spawnedWithWorktree: true, worktreePath: WT }),
+ [`${RUN}/agent-a1.jsonl`]: sample(WT),
+ [`${RUN}/agent-a2.meta.json`]: meta('review:x', 'Review'),
+ [`${WT}/.git`]: 'gitdir: x',
+ [`${RUN}/agent-a2.jsonl`]: `${line('user', 0, 'review the parser')}\n${line('assistant', 1, [use('r1', 'Grep', { pattern: 'parser' })])}\n`,
+ ...over,
+})
+
+export type World = { state: State; host: Host; spied: { runs: string[][]; views: string[]; focused: string[] } }
+
+export async function worldOf(files: Record<string, string>, fsOver: Parameters<typeof memoryFs>[1] = {}, run?: (argv: readonly string[]) => Promise<{ exitCode: number; stdout: string; stderr?: string }>): Promise<World> {
+ const state = newState({})
+ const spied = { runs: [] as string[][], views: [] as string[], focused: [] as string[] }
+ const fs = memoryFs(files, fsOver)
+ const host = { fs, invalidate: () => undefined, run: async (argv: readonly string[]) => (spied.runs.push([...argv]), run === undefined ? { exitCode: 0, stdout: '' } : run(argv)) } as unknown as Host
+
+ state.view = 'workflows'
+ state.configDir = CONFIG
+ state.cwd = '/work/proj'
+ state.isInteractive = false
+ await refreshWorkflows(state, host, true, NOW)
+
+ return { state, host, spied }
+}
+
+export function frame(world: World, columns = 110): { tree: unknown; ctx: Ctx; env: SlotEnv } {
+ const act = { workflows: workflowsActions(world.state, world.host, { ask: () => undefined } as never), focus: (key: string) => void world.spied.focused.push(key), view: (id: string) => void world.spied.views.push(id) } as unknown as Actions
+ const ctx: Ctx = { kit, state: world.state, nowMs: NOW, columns, pictures: new Map(), act }
+ const model = workflowsModelOf(world.state, NOW)
+ const here = pick(world.state.wf.ui, model?.runs ?? [])
+
+ return { tree: workflowsPage(ctx), ctx, env: { ctx, runs: model?.runs ?? [], run: here.run, phase: here.phase, agent: here.agent, ui: here.ui, nowMs: NOW } }
+}
+
+/** Presses a registered key by what it does. */
+export const press = (world: World, verb: string): void => void slotsFor('key').find(slot => slot.id === `drill-${verb}`)?.run(frame(world).env)
+export const screen = (world: World): string => words(frame(world).tree)
+
+/** Opens the drill and walks it down to the agent's Activity. */
+export function toAgent(world: World): void {
+ click(frame(world).tree, 'wf-drill-open')
+ press(world, 'in')
+ press(world, 'in')
+}
+
+/** Registers the drill and the search before each test, and forgets everything after. */
+export function useDrill(): void {
+ beforeEach(() => {
+ resetSlots()
+ resetDrillIo()
+ expect(registerDrill()).toEqual([])
+ expect(registerSearch()).toBeNull()
+ })
+ afterEach(() => {
+ resetSlots()
+ resetDrillIo()
+ })
+}
diff --git a/plugins/ruflo-console/tests/fixtures/wf-drill.ts b/plugins/ruflo-console/tests/fixtures/wf-drill.ts
new file mode 100644
index 0000000000..2cb37b738a
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/wf-drill.ts
@@ -0,0 +1,27 @@
+/**
+ * A transcript with the shapes a real Claude Code one has (ADR-459): a streamed duplicate block, an error result, an array result with an
+ * image, an unanswered call, a credential, an escape sequence, a meta line. Content is invented; timestamps are fixed offsets from T0.
+ */
+import { T0 } from './workflows'
+
+const iso = (s: number): string => new Date(T0 + s * 1000).toISOString()
+
+export const line = (type: 'user' | 'assistant', at: number, content: unknown, extra: Record<string, unknown> = {}): string => JSON.stringify({ type, timestamp: iso(at), message: { role: type, content }, ...extra })
+export const use = (id: string, name: string, input: unknown): unknown => ({ type: 'tool_use', id, name, input })
+export const back = (id: string, content: unknown, isError = false): unknown => ({ type: 'tool_result', tool_use_id: id, content, ...(isError && { is_error: true }) })
+
+export const SECRET = 'sk-ABCDEFGHIJKLMNOPQRSTUVWX'
+
+export const sample = (root = '/wt'): string =>
+ [
+ line('user', 0, `do the work, key ${SECRET}`),
+ line('assistant', 1, [{ type: 'thinking', thinking: 'plan it' }]),
+ line('assistant', 2, [use('t1', 'Bash', { command: 'ls -la', description: 'list' })]),
+ line('assistant', 2, [use('t1', 'Bash', { command: 'ls -la', description: 'list' })]),
+ line('user', 4, [back('t1', 'total 3\n\u001b[31mred\u001b[0m\nAuthorization: Bearer abcdefghijklmnop')]),
+ line('assistant', 5, [use('t2', 'Edit', { file_path: `${root}/a.ts`, old_string: 'x', new_string: 'y' })]),
+ line('user', 6, [back('t2', [{ type: 'text', text: 'boom' }, { type: 'image' }], true)]),
+ line('assistant', 7, [use('t3', 'Read', { file_path: `${root}/b.ts` }), use('t4', 'Write', { file_path: `${root}/c.ts`, content: 'z' })]),
+ line('user', 7.5, 'meta line', { isMeta: true }),
+ line('assistant', 9, [{ type: 'text', text: 'all done' }]),
+ ].join('\n') + '\n'
diff --git a/plugins/ruflo-console/tests/wf-data.spec.ts b/plugins/ruflo-console/tests/wf-data.spec.ts
new file mode 100644
index 0000000000..59d4c2c68a
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-data.spec.ts
@@ -0,0 +1,306 @@
+/**
+ * The drill-down's pure halves (ADR-459): what a transcript says (pairing, caps, washing), the log's filters and window, the
+ * navigation reducer and the cross-level search. No screen, no disk. Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-data.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { cleanBlock, ENTRY_CAP, FIELD_CAP, journalResult, parseActivity } from '../hooks/data/wf-activity'
+import { filterLines, logLines, mergeLines, nextFilter, tailWindow, LOG_ROWS } from '../hooks/data/wf-log'
+import { flatHits, MAX_SHOWN, SCAN_CHARS, search } from '../hooks/data/wf-search'
+import { crumbs, deeper, jump, move, newDrill, shallower, sync, toLevel, type Drill, type Here } from '../hooks/data/wf-trail'
+import { buildRun, type WfAgent } from '../hooks/data/workflows'
+import { back, line, sample, SECRET, use } from './fixtures/wf-drill'
+import { journal, meta, result, started, T0 } from './fixtures/workflows'
+
+describe('cleanBlock', () => {
+ it('strips escapes and controls but keeps newlines, and masks credentials', () => {
+ const out = cleanBlock(`a\u001b[31mred\u001b[0m\tb\nline2 ${SECRET} \u0007bell`)
+
+ expect(out.text).toBe('ared b\nline2 ‹masked› bell')
+ expect(out.text).not.toContain('\u001b')
+ expect(out.text).not.toContain(SECRET)
+ })
+
+ it('cuts at the cap and says how long the original was', () => {
+ // Words, not one long run: a 32-character alphanumeric run is masked as a key, by design.
+ const words = (n: number): string => 'ab '.repeat(n / 3)
+
+ expect(cleanBlock(words(FIELD_CAP))).toMatchObject({ isCut: false, total: FIELD_CAP })
+ expect(cleanBlock(words(FIELD_CAP + 3))).toMatchObject({ isCut: true, total: FIELD_CAP + 3 })
+ expect(cleanBlock(words(FIELD_CAP + 3)).text).toHaveLength(FIELD_CAP)
+ })
+
+ it('masks a token that straddles the cut instead of leaving its head visible', () => {
+ const head = 'y'.repeat(20)
+ const out = cleanBlock(`${head}${SECRET}`, 30)
+
+ expect(out.text).not.toMatch(/sk-/)
+ })
+})
+
+describe('parseActivity', () => {
+ const parsed = parseActivity(sample())
+
+ it('pairs a result with its call by id, counts a streamed call once, and marks an error', () => {
+ expect(parsed.calls.map(call => [call.tool, call.status])).toEqual([['Bash', 'ok'], ['Edit', 'error'], ['Read', 'pending'], ['Write', 'pending']])
+ expect(parsed.calls[0]?.output?.text).toContain('total 3')
+ expect(parsed.calls[1]?.output?.text).toBe('boom\n[image]')
+ expect(parsed.calls[2]?.output).toBeNull()
+ })
+
+ it('keeps the span of a call from its two timestamps', () => {
+ expect(parsed.calls[0]?.atMs).toBe(T0 + 2000)
+ expect(parsed.calls[0]?.endMs).toBe(T0 + 4000)
+ })
+
+ it('washes every free-text field: no escape and no credential in a message, an input or an output', () => {
+ const all = JSON.stringify(parsed.entries)
+
+ expect(all).not.toContain(SECRET)
+ expect(all).not.toContain('abcdefghijklmnop')
+ expect(all).not.toContain('\\u001b')
+ expect(parsed.entries[0]).toMatchObject({ kind: 'message', role: 'user' })
+ })
+
+ it('skips meta lines and keeps thinking and the closing text as messages', () => {
+ expect(parsed.entries.filter(entry => entry.kind === 'message').map(entry => (entry as { role: string }).role)).toEqual(['user', 'thinking', 'assistant'])
+ expect(parsed.skipped).toBe(1)
+ })
+
+ it('collects the files tool inputs name, with what was done to each', () => {
+ expect(parsed.files.map(file => [file.path, file.read, file.edit, file.write])).toEqual([['/wt/a.ts', 0, 1, 0], ['/wt/c.ts', 0, 0, 1], ['/wt/b.ts', 1, 0, 0]])
+ })
+
+ it('names a result whose call is before a tail, and drops the first line of a tail', () => {
+ const tail = `{"type":"assistant","timesta\n${line('user', 3, [back('gone', 'late result')])}\n`
+ const out = parseActivity(tail, true)
+
+ expect(out.isTail).toBe(true)
+ expect(out.entries).toHaveLength(1)
+ expect(out.entries[0]).toMatchObject({ kind: 'message', role: 'result' })
+ })
+
+ it('keeps only the newest ENTRY_CAP entries and re-indexes them', () => {
+ const many = Array.from({ length: ENTRY_CAP + 5 }, (_, i) => line('assistant', i, [{ type: 'text', text: `m${i}` }])).join('\n')
+ const out = parseActivity(many)
+
+ expect(out.entries).toHaveLength(ENTRY_CAP)
+ expect(out.dropped).toBe(5)
+ expect(out.entries[0]).toMatchObject({ index: 0, body: { text: 'm5' } })
+ })
+
+ it('drops a half-written last line and reads null as nothing', () => {
+ expect(parseActivity(`${line('user', 0, 'hi')}\n{"type":"assis`).entries).toHaveLength(1)
+ expect(parseActivity(null).entries).toEqual([])
+ })
+})
+
+describe('journalResult', () => {
+ it('returns the agent\'s own result, washed, as text or pretty JSON, and null where there is none', () => {
+ const text = journal(started('a1', 'x', 'P'), result('a1', { verdict: 'ok', key: SECRET }), result('a2', 'other'))
+ const found = journalResult(text, 'a1')
+
+ expect(found?.text).toContain('"verdict": "ok"')
+ expect(found?.text).not.toContain(SECRET)
+ expect(journalResult(text, 'a2')?.text).toBe('other')
+ expect(journalResult(text, 'a9')).toBeNull()
+ expect(journalResult(null, 'a1')).toBeNull()
+ })
+})
+
+const agent = { id: 'a1', label: 'build:x' }
+
+describe('the log', () => {
+ const lines = logLines(parseActivity(sample()), agent)
+
+ it('is one line per entry with a level, and an unanswered or failed call says so', () => {
+ expect(lines.map(l => l.level)).toEqual(['user', 'thinking', 'tool', 'error', 'tool', 'tool', 'assistant'])
+ expect(lines[3]?.text).toBe('Edit /wt/a.ts (failed)')
+ expect(lines[4]?.text).toContain('no result in the part read')
+ })
+
+ it('filters by level: messages, tool calls (errors included), errors only', () => {
+ expect(filterLines(lines, 'all')).toHaveLength(7)
+ expect(filterLines(lines, 'text').map(l => l.level)).toEqual(['user', 'thinking', 'assistant'])
+ expect(filterLines(lines, 'tool').map(l => l.level)).toEqual(['tool', 'error', 'tool', 'tool'])
+ expect(filterLines(lines, 'error').map(l => l.level)).toEqual(['error'])
+ expect(['all', 'text', 'tool', 'error'].map(f => nextFilter(f as 'all'))).toEqual(['text', 'tool', 'error', 'all'])
+ })
+
+ it('merges agents by time, keeping an untimed line after its own agent\'s', () => {
+ const a = [{ entry: 0, agentId: 'a', agent: 'a', atMs: 5, level: 'user' as const, text: 'a5' }, { entry: 1, agentId: 'a', agent: 'a', level: 'user' as const, text: 'a-untimed' }]
+ const b = [{ entry: 0, agentId: 'b', agent: 'b', atMs: 3, level: 'user' as const, text: 'b3' }, { entry: 1, agentId: 'b', agent: 'b', atMs: 9, level: 'user' as const, text: 'b9' }]
+
+ expect(mergeLines([a, b]).map(l => l.text)).toEqual(['b3', 'a5', 'b9', 'a-untimed'])
+ })
+
+ it('windows the lines: follow pins the end, otherwise the selection stays on screen', () => {
+ const many = Array.from({ length: 40 }, (_, i) => ({ entry: i, agentId: 'a', agent: 'a', level: 'tool' as const, text: `l${i}` }))
+ const following = tailWindow(many, { sel: 0, follow: true })
+
+ expect(following.rows).toHaveLength(LOG_ROWS)
+ expect(following.rows.at(-1)?.text).toBe('l39')
+ expect(following.at).toBe(LOG_ROWS - 1)
+ expect(following.below).toBe(0)
+
+ const held = tailWindow(many, { sel: 3, follow: false })
+
+ expect(held.from).toBe(0)
+ expect(held.rows[held.at]?.text).toBe('l3')
+ expect(tailWindow(many, { sel: 99, follow: false }).rows.at(-1)?.text).toBe('l39')
+ expect(tailWindow([], { sel: 0, follow: true })).toMatchObject({ total: 0, at: -1 })
+ })
+})
+
+const here = (over: Partial<Here> = {}): Here => ({ column: 'phases', phaseAgents: 2, hasAgent: true, isRuflo: false, calls: 4, lines: 7, ...over })
+const open = (over: Partial<Drill> = {}): Drill => ({ ...newDrill(), open: true, ...over })
+
+describe('the trail', () => {
+ it('opens where the page cursor is, then goes deeper level by level, telling the page which column key it needs', () => {
+ const first = deeper(newDrill(), here({ column: 'phases' }))
+
+ expect(first.drill).toMatchObject({ open: true, level: 'phases' })
+ expect(deeper(newDrill(), here({ column: 'agents' })).drill.level).toBe('agents')
+
+ const toAgents = deeper(first.drill, here())
+
+ expect(toAgents).toMatchObject({ drill: { level: 'agents' }, ui: 'l' })
+ expect(deeper(toAgents.drill, here()).drill).toMatchObject({ level: 'agent', sub: 'activity' })
+ })
+
+ it('says why it cannot go deeper instead of doing nothing: an empty phase, a ruflo agent, a tab with no depth, the deepest level', () => {
+ expect(deeper(open({ level: 'phases' }), here({ phaseAgents: 0 })).said).toMatch(/No agent has started/)
+ expect(deeper(open({ level: 'agents' }), here({ isRuflo: true })).said).toMatch(/ruflo agent keeps no transcript/)
+ expect(deeper(open({ level: 'agents' }), here({ hasAgent: false })).said).toMatch(/no agent to open/)
+ expect(deeper(open({ level: 'agent', sub: 'files' }), here()).said).toMatch(/no deeper level/)
+ expect(deeper(open({ level: 'agent', sub: 'activity' }), here({ calls: 0 })).said).toMatch(/No call or message/)
+ expect(deeper(open({ level: 'item' }), here()).said).toMatch(/deepest/)
+ })
+
+ it('goes back one level at a time and closes from Runs', () => {
+ expect(shallower(open({ level: 'item' })).drill.level).toBe('agent')
+ expect(shallower(open({ level: 'agent' }))).toMatchObject({ drill: { level: 'agents' }, ui: 'l' })
+ expect(shallower(open({ level: 'agents' }))).toMatchObject({ drill: { level: 'phases' }, ui: 'h' })
+ expect(shallower(open({ level: 'phases' })).drill.level).toBe('runs')
+ expect(shallower(open({ level: 'runs' })).drill.open).toBe(false)
+ })
+
+ it('goes straight back to a named level, never forward', () => {
+ expect(toLevel(open({ level: 'item' }), 'phases').drill.level).toBe('phases')
+ expect(toLevel(open({ level: 'phases' }), 'item').drill.level).toBe('phases')
+ })
+
+ it('moves a call or a line within bounds, and selecting a line stops following', () => {
+ expect(move(open({ level: 'agent', sub: 'activity', callSel: 3 }), 1, here()).drill.callSel).toBe(3)
+ expect(move(open({ level: 'agent', sub: 'activity', callSel: 0 }), -1, here()).drill.callSel).toBe(0)
+ expect(move(open({ level: 'agent', sub: 'activity', callSel: 1 }), 1, here()).drill.callSel).toBe(2)
+
+ const fromEnd = move(open({ level: 'agent', sub: 'log', follow: true }), -1, here())
+
+ expect(fromEnd.drill).toMatchObject({ follow: false, logSel: 5 })
+ expect(move(open({ level: 'runs' }), 1, here()).ui).toBe(']')
+ expect(move(open({ level: 'agents' }), -1, here()).ui).toBe('k')
+ })
+
+ it('starts the selections over when the cursor lands on another agent, keeping the filter', () => {
+ const held = open({ at: 'r/a1', callSel: 4, logSel: 6, follow: false, filter: 'error' })
+
+ expect(sync(held, 'r/a1')).toBe(held)
+ expect(sync(held, 'r/a2')).toMatchObject({ at: 'r/a2', callSel: 0, logSel: 0, follow: true, filter: 'error' })
+ })
+
+ it('draws a breadcrumb down to where it is', () => {
+ expect(crumbs(open({ level: 'agent', sub: 'log' })).map(c => c.label)).toEqual(['Runs', 'Phases', 'Agents', 'Agent · Log'])
+ expect(crumbs(open({ level: 'agent' })).at(-1)?.isHere).toBe(true)
+ })
+
+ it('jumps to a hit: the cursor, the sub-tab, the call or the line, with the filter back to all', () => {
+ const toLine = jump(open({ filter: 'error', scope: 'phase' }), { run: 1, phase: 2, agent: 3, line: 5 }, '')
+
+ expect(toLine.ui).toEqual({ run: 1, phase: 2, agent: 3, column: 'agents', isInspecting: false })
+ expect(toLine.drill).toMatchObject({ level: 'agent', sub: 'log', logSel: 5, filter: 'all', scope: 'agent', follow: false })
+ expect(jump(open(), { run: 0, phase: 1, agent: -1 }, '').drill.level).toBe('phases')
+ expect(jump(open(), { run: 0, phase: 1, agent: 2, sub: 'activity', call: 3 }, '').drill).toMatchObject({ level: 'agent', sub: 'activity', callSel: 3 })
+ })
+})
+
+const T = T0 + 60_000
+
+function runsOf(): { runs: ReturnType<typeof buildRun>[]; byAgent: Map<WfAgent, ReturnType<typeof parseActivity>> } {
+ const run = buildRun({
+ id: 'wf_s',
+ journal: journal(started('a1', 'build:parser', 'Build'), started('a2', 'review:parser', 'Review'), result('a2', 'looks fine')),
+ agents: new Map([
+ ['a1', { meta: meta('build:parser', 'Build'), transcript: null, isTail: false, path: '/c/projects/p/s/subagents/workflows/wf_s/agent-a1.jsonl' }],
+ ['a2', { meta: meta('review:parser', 'Review'), transcript: null, isTail: false, path: '/c/projects/p/s/subagents/workflows/wf_s/agent-a2.jsonl' }],
+ ]),
+ record: null,
+ script: null,
+ nowMs: T,
+ })
+ const [a1, a2] = run.phases.flatMap(phase => phase.agents)
+
+ return { runs: [run], byAgent: new Map([[a1 as WfAgent, parseActivity(sample())], [a2 as WfAgent, parseActivity(`${line('user', 0, 'review the parser')}\n${line('assistant', 1, [use('r1', 'Grep', { pattern: 'parser' })])}\n`)]]) }
+}
+
+describe('search', () => {
+ const { runs, byAgent } = runsOf()
+ const input = { runs, parsed: (a: WfAgent) => byAgent.get(a) ?? null, tasks: [{ mission: 'ship the parser', id: 'T-1', title: 'Write the parser tests', status: 'running' }] }
+
+ it('does nothing under two characters', () => {
+ expect(search(input, 'p')).toMatchObject({ isSearched: false })
+ expect(search(input, ' ')).toMatchObject({ isSearched: false })
+ })
+
+ it('groups hits by level and gives each the exact place it jumps to', () => {
+ const out = search(input, 'parser')
+
+ expect(out.counts.agent).toBe(2)
+ expect(out.groups.agent[0]).toMatchObject({ title: 'build:parser', target: { run: 0, phase: 0, agent: 0 } })
+ expect(out.groups.tool[0]).toMatchObject({ title: 'Grep parser', target: { run: 0, phase: 1, agent: 0, sub: 'activity', call: 0 } })
+ expect(out.groups.text[0]).toMatchObject({ target: { run: 0, phase: 1, agent: 0, sub: 'log', line: 0 } })
+ expect(out.groups.mission[0]).toMatchObject({ title: 'Write the parser tests' })
+ expect(out.groups.mission[0]?.target).toBeUndefined()
+ })
+
+ it('finds a run by name, a phase by title, a call by its input, and text in an output', () => {
+ expect(search(input, 'wf_s').groups.run).toHaveLength(1)
+ expect(search(input, 'review').groups.phase[0]).toMatchObject({ title: 'Review', target: { phase: 1, agent: -1 } })
+ expect(search(input, 'ls -la').groups.tool[0]).toMatchObject({ target: { sub: 'activity', call: 0 } })
+ expect(search(input, 'total 3').groups.text[0]).toMatchObject({ target: { sub: 'log', line: 2 } })
+ })
+
+ it('never finds what the washing masked, and matches without regard to case', () => {
+ expect(flatHits(search(input, SECRET))).toEqual([])
+ expect(search(input, 'BASH').groups.tool).toHaveLength(1)
+ })
+
+ it('counts an agent whose transcript is not in memory as unread instead of guessing', () => {
+ const out = search({ ...input, parsed: () => null }, 'parser')
+
+ expect(out.unread).toBe(2)
+ expect(out.scanned).toBe(0)
+ expect(out.groups.tool).toEqual([])
+ expect(out.groups.agent).toHaveLength(2)
+ })
+
+ it('shows at most MAX_SHOWN a group but counts them all, and stops at the scan cap', () => {
+ const many = { ...input, parsed: () => parseActivity(Array.from({ length: 20 }, (_, i) => line('assistant', i, [{ type: 'text', text: `needle ${i}` }])).join('\n')) }
+ const out = search(many, 'needle')
+
+ expect(out.counts.text).toBe(40)
+ expect(out.groups.text).toHaveLength(MAX_SHOWN)
+ expect(out.isCapped).toBe(false)
+ expect(SCAN_CHARS).toBeGreaterThan(1_000_000)
+ })
+
+ it('stops scanning at the character cap and says so', () => {
+ const huge = parseActivity(Array.from({ length: 2000 }, (_, i) => line('assistant', i, [{ type: 'text', text: 'ab '.repeat(2000) }])).join('\n'))
+ const out = search({ ...input, parsed: a => (a === [...byAgent.keys()][0] ? huge : null) }, 'zzz')
+
+ expect(out.isCapped).toBe(true)
+ expect(out.chars).toBeGreaterThan(SCAN_CHARS)
+ expect(out.chars).toBeLessThanOrEqual(SCAN_CHARS + 6000)
+ })
+})
diff --git a/plugins/ruflo-console/tests/wf-drill-read.spec.ts b/plugins/ruflo-console/tests/wf-drill-read.spec.ts
new file mode 100644
index 0000000000..0849433206
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-drill-read.spec.ts
@@ -0,0 +1,211 @@
+/**
+ * What the drill-down reads, and refuses to read or run (ADR-459): Files and Result on demand through a bound host, a finished run's transcripts, the tail of a large one, path checks, and the printed caps.
+ * Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-drill-read.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { diffArgv, isProjectDir, isRunFile, parseNumstat } from '../hooks/data/wf-drill-io'
+import { bindWorkflowDrill } from '../hooks/wf-drill'
+import { drillOf } from '../hooks/views/wf-detail'
+import { back, line, sample, SECRET, use } from './fixtures/wf-drill'
+import { journal, meta, record, result, started, T0 } from './fixtures/workflows'
+import { buttonOf, click, CONFIG, flush, frame, liveFiles, press, RUN, ROOT, screen, SESSION, toAgent, useDrill, words, worldOf, WT } from './fixtures/wf-drill-world'
+
+useDrill()
+
+
+describe('Files and Result', () => {
+ it('lists the files the tool inputs name even with no worktree reading, with the diff stat honestly n/a', async () => {
+ const world = await worldOf(liveFiles())
+
+ toAgent(world)
+ click(frame(world).tree, 'wf-sub-files')
+
+ const text = screen(world)
+
+ expect(text).toMatch(/a\.ts/)
+ expect(text).toMatch(/edit×1/)
+ expect(text).toMatch(/diff stat: n\/a \(host not bound\)/)
+ })
+
+ it('reads the worktree diff stat through one fixed argv when bound, and joins it to the named files', async () => {
+ const world = await worldOf(liveFiles(), {}, async () => ({ exitCode: 0, stdout: '3\t1\ta.ts\n-\t-\timg.png\nnot a numstat line\n' }))
+
+ bindWorkflowDrill(world.state, world.host as never)
+ toAgent(world)
+ click(frame(world).tree, 'wf-sub-files')
+ await flush()
+
+ expect(world.spied.runs).toEqual([diffArgv(WT)])
+ expect(world.spied.runs[0]).toEqual(['git', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', WT, 'diff', '--numstat', '--no-renames', '--no-color', '--no-ext-diff', '--no-textconv', 'HEAD', '--'])
+
+ const text = screen(world)
+
+ expect(text).toMatch(/2 changed files vs HEAD/)
+ expect(text).toMatch(/\+3/)
+ expect(text).toMatch(/-1/)
+ expect(text).toMatch(/also changed in the worktree.*img\.png/)
+ })
+
+ it('shows a path with a long hash segment unmasked and joins it to the diff stat line of the same path', async () => {
+ const hash = 'a'.repeat(40)
+ const path = `${WT}/node_modules/.pnpm/[email protected]_${hash}/index.ts`
+ const text = [line('assistant', 1, [use('t1', 'Edit', { file_path: path, old_string: 'a', new_string: 'b' })]), line('user', 2, [back('t1', 'ok')])].join('\n')
+ const world = await worldOf(liveFiles({ [`${RUN}/agent-a1.jsonl`]: text }), {}, async () => ({ exitCode: 0, stdout: `5\t2\tnode_modules/.pnpm/[email protected]_${hash}/index.ts\n` }))
+
+ bindWorkflowDrill(world.state, world.host as never)
+ toAgent(world)
+ click(frame(world).tree, 'wf-sub-files')
+ await flush()
+
+ const shown = words(frame(world, 160).tree)
+
+ expect(shown).toContain(hash)
+ expect(shown).not.toMatch(/‹masked›/)
+ expect(shown).toMatch(/\+5/)
+ expect(shown).toMatch(/-2/)
+ expect(shown).not.toMatch(/also changed in the worktree/)
+ })
+
+ it('does not run git for a worktree outside the project, and says so', async () => {
+ const world = await worldOf(liveFiles({ [`${RUN}/agent-a1.meta.json`]: meta('build:x', 'Build', { spawnedWithWorktree: true, worktreePath: '/etc' }) }))
+
+ bindWorkflowDrill(world.state, world.host as never)
+ toAgent(world)
+ click(frame(world).tree, 'wf-sub-files')
+ await flush()
+ click(frame(world).tree, 'wf-diff-load')
+ await flush()
+
+ expect(world.spied.runs).toEqual([])
+ expect(screen(world)).toMatch(/not inside this project's folder/)
+ })
+
+ it('reads the agent\'s structured return from the journal on demand, washed, and says where there is none', async () => {
+ const world = await worldOf(liveFiles({ [`${RUN}/journal.jsonl`]: journal(started('a1', 'build:x', 'Build'), started('a2', 'review:x', 'Review'), result('a1', { verdict: 'pass', note: SECRET })) }))
+
+ bindWorkflowDrill(world.state, world.host as never)
+ world.state.wf.ui = { ...world.state.wf.ui, phase: 0 }
+ toAgent(world)
+ press(world, 'sub')
+ press(world, 'sub')
+ press(world, 'sub')
+ expect(drillOf(world.state).sub).toBe('result')
+ await flush()
+
+ const text = screen(world)
+
+ expect(text).toMatch(/"verdict": "pass"/)
+ expect(text).not.toContain(SECRET)
+ expect(text).toMatch(/characters/)
+ })
+
+ it('without the host binding, says reading the journal needs it instead of a dead button', async () => {
+ const world = await worldOf(liveFiles())
+
+ toAgent(world)
+ press(world, 'sub')
+ press(world, 'sub')
+ press(world, 'sub')
+
+ const tree = frame(world).tree
+
+ expect(buttonOf(tree, 'wf-result-load')).toBeUndefined()
+ expect(words(tree)).toMatch(/needs the drill bound to the host/)
+ })
+})
+describe('a finished run', () => {
+ const finished = (): Record<string, string> => liveFiles({ [`${ROOT}/${SESSION}/workflows/wf_live.json`]: record({ workflowProgress: [{ type: 'workflow_agent', label: 'build:x', phaseTitle: 'Build', agentId: 'a1', state: 'done', startedAt: T0, tokens: 1000, durationMs: 9000 }, { type: 'workflow_agent', label: 'review:x', phaseTitle: 'Review', agentId: 'a2', state: 'done', startedAt: T0, tokens: 500, durationMs: 4000 }] }) })
+
+ it('has no transcript in memory (the page reads figures from the record): says why, and offers no button it cannot honour', async () => {
+ const world = await worldOf(finished())
+
+ toAgent(world)
+
+ const tree = frame(world).tree
+ const text = words(tree)
+
+ expect(text).toMatch(/This agent's transcript is not in memory/)
+ expect(text).toMatch(/a finished run's figures come from its record/)
+ expect(buttonOf(tree, 'wf-drill-load')).toBeUndefined()
+ })
+
+ it('reads it on demand once the host is bound, and draws the calls', async () => {
+ const world = await worldOf(finished())
+
+ bindWorkflowDrill(world.state, world.host as never)
+ toAgent(world)
+ await flush()
+
+ expect(screen(world)).toMatch(/Bash\s+ls -la/)
+ })
+
+ it('reads only the tail of a transcript over the read cap, and says the earlier calls are not there', async () => {
+ const path = `${RUN}/agent-a1.jsonl`
+ const world = await worldOf(finished(), { size: { [path]: 4_000_000 }, tail: `{"cut half line\n${sample(WT)}` })
+
+ bindWorkflowDrill(world.state, world.host as never)
+ toAgent(world)
+ await flush()
+
+ const text = screen(world)
+
+ expect(text).toMatch(/the last 400 KB of a file over the 3\.0 MB read cap/)
+ expect(text).toMatch(/earlier calls are not here/)
+ expect(text).toMatch(/Bash\s+ls -la/)
+ })
+
+ it('refuses a path outside Claude Code\'s projects folder, without reading it', async () => {
+ const world = await worldOf(finished())
+ const fs = world.host.fs as unknown as { reads: string[] }
+
+ bindWorkflowDrill(world.state, world.host as never)
+
+ const agent = world.state.wf.read?.runs[0]?.phases[0]?.agents[0]
+
+ if (agent === undefined) throw new Error('no agent')
+
+ const { loadTranscript } = await import('../hooks/data/wf-drill-io')
+
+ for (const bad of ['/etc/passwd', `${CONFIG}/projects/../../etc/agent-a1.jsonl`, `${CONFIG}/projects/x/agent-a1.jsonl\0`, `${CONFIG}/projects/p/notes.txt`]) {
+ fs.reads.length = 0
+ await loadTranscript({ ...agent, transcriptPath: bad })
+ expect(fs.reads).toEqual([])
+ }
+ })
+})
+
+describe('what the drill refuses to read or run', () => {
+ it('knows a run file from a stray path, and a project folder from another', () => {
+ expect(isRunFile(`${CONFIG}/projects/p/s/agent-a1.jsonl`, CONFIG)).toBe(true)
+ expect(isRunFile(`${CONFIG}/projects/../x`, CONFIG)).toBe(false)
+ expect(isRunFile(`${CONFIG}/other/x`, CONFIG)).toBe(false)
+ expect(isRunFile(`${CONFIG}/projects/x`, null)).toBe(false)
+ expect(isProjectDir('/work/proj/.claude/worktrees/a', '/work/proj')).toBe(true)
+ expect(isProjectDir('/work/proj', '/work/proj')).toBe(true)
+ expect(isProjectDir('/work/projother', '/work/proj')).toBe(false)
+ expect(isProjectDir('/work/proj/../etc', '/work/proj')).toBe(false)
+ expect(isProjectDir('relative', '/work/proj')).toBe(false)
+ })
+
+ it('reads numstat lines and ignores anything else', () => {
+ const out = parseNumstat('12\t3\tsrc/a.ts\n-\t-\tlogo.png\nwarning: nope\n')
+
+ expect([...out.files]).toEqual([['src/a.ts', { add: 12, del: 3 }], ['logo.png', { add: null, del: null }]])
+ })
+})
+
+describe('caps are printed', () => {
+ it('says how many of how many characters an over-long output shows', async () => {
+ const big = 'ab '.repeat(2400)
+ const text = [line('assistant', 1, [use('t1', 'Bash', { command: 'cat big' })]), line('user', 2, [back('t1', big)])].join('\n')
+ const world = await worldOf(liveFiles({ [`${RUN}/agent-a1.jsonl`]: text }))
+
+ toAgent(world)
+ press(world, 'in')
+
+ expect(screen(world)).toMatch(/first 6,000 of 7,200 characters \(cap 6,000\)/)
+ })
+})
+
diff --git a/plugins/ruflo-console/tests/wf-drill-search.spec.ts b/plugins/ruflo-console/tests/wf-drill-search.spec.ts
new file mode 100644
index 0000000000..91899d84e8
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-drill-search.spec.ts
@@ -0,0 +1,92 @@
+/**
+ * Search across the drill-down's levels as the person uses it (ADR-459): one field, hits by level, a click or Enter goes to the exact place, and what was not in memory is counted, not guessed.
+ * Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-drill-search.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { bindWorkflowDrill } from '../hooks/wf-drill'
+import { drillOf } from '../hooks/views/wf-detail'
+import { record } from './fixtures/workflows'
+import { buttonOf, click, flush, frame, inputOf, liveFiles, press, ROOT, screen, SESSION, useDrill, words, worldOf } from './fixtures/wf-drill-world'
+
+useDrill()
+
+
+describe('search', () => {
+ it('lists hits by level and a click goes to the exact call', async () => {
+ const world = await worldOf(liveFiles())
+
+ ;(inputOf(frame(world).tree)?.props.onInput as (v: string) => void)('ls -la')
+
+ const tree = frame(world).tree
+
+ expect(words(tree)).toMatch(/Tool calls \(1\)/)
+ expect(words(tree)).toMatch(/looked through 2 agents' transcripts/)
+
+ click(tree, 'wf-hit-tool-0')
+ expect(world.state.wf.ui).toMatchObject({ run: 0, phase: 0, agent: 0, isInspecting: false })
+ expect(drillOf(world.state)).toMatchObject({ open: true, level: 'agent', sub: 'activity', callSel: 0 })
+ expect(screen(world)).toMatch(/call 1 of 4/)
+ })
+
+ it('goes to the exact line of transcript text, in the Log, on another agent', async () => {
+ const world = await worldOf(liveFiles())
+
+ ;(inputOf(frame(world).tree)?.props.onInput as (v: string) => void)('review the parser')
+ click(frame(world).tree, 'wf-hit-text-0')
+ expect(world.state.wf.ui).toMatchObject({ phase: 1, agent: 0 })
+ expect(drillOf(world.state)).toMatchObject({ level: 'agent', sub: 'log', logSel: 0 })
+ expect(screen(world)).toMatch(/▸01:30:00\s*\nuser\s*\nreview the parser/)
+ })
+
+ it('jumps to the first hit with a place when Enter is pressed in the field', async () => {
+ const world = await worldOf(liveFiles())
+
+ ;(inputOf(frame(world).tree)?.props.onSubmit as (v: string) => void)('boom')
+ expect(drillOf(world.state)).toMatchObject({ level: 'agent', sub: 'log', logSel: 3 })
+ })
+
+ it('says it needs two characters, and says when nothing matches', async () => {
+ const world = await worldOf(liveFiles())
+ const type = (v: string): void => void (inputOf(frame(world).tree)?.props.onInput as (v: string) => void)(v)
+
+ type('x')
+ expect(screen(world)).toMatch(/at least 2 characters/)
+ type('zzzzqqq')
+ expect(screen(world)).toMatch(/No match for "zzzzqqq"/)
+ })
+
+ it('counts transcripts not in memory instead of guessing, and offers to read them only when bound', async () => {
+ const world = await worldOf(liveFiles({ [`${ROOT}/${SESSION}/workflows/wf_live.json`]: record({ workflowProgress: [{ type: 'workflow_agent', label: 'build:x', phaseTitle: 'Build', agentId: 'a1', state: 'done', durationMs: 1 }] }) }))
+ const type = (v: string): void => void (inputOf(frame(world).tree)?.props.onInput as (v: string) => void)(v)
+
+ type('Bash')
+ expect(screen(world)).toMatch(/2 agents' transcripts are not in memory, so they were not searched/)
+ expect(buttonOf(frame(world).tree, 'wf-search-load')).toBeUndefined()
+
+ bindWorkflowDrill(world.state, world.host as never)
+ expect(buttonOf(frame(world).tree, 'wf-search-load')).toBeDefined()
+ click(frame(world).tree, 'wf-search-load')
+ await flush()
+ await flush()
+ expect(screen(world)).toMatch(/Tool calls \(1\)/)
+ })
+
+ it('lists mission tasks when the project has them, and sends the click to the Missions page', async () => {
+ const world = await worldOf(liveFiles())
+
+ world.state.snapshot = { missions: { missions: [{ objective: 'ship it', plan: { tasks: [{ id: 'T1', title: 'verify the ls output', status: 'running', dependsOn: [] }] } }] } } as never
+ ;(inputOf(frame(world).tree)?.props.onInput as (v: string) => void)('verify the ls')
+ expect(screen(world)).toMatch(/Mission tasks \(1\)/)
+ click(frame(world).tree, 'wf-hit-mission-0')
+ expect(world.spied.views).toEqual(['missions'])
+ })
+
+ it('the search key puts the keys in the field', async () => {
+ const world = await worldOf(liveFiles())
+
+ press(world, 'search')
+ expect(world.spied.focused).toEqual(['wf-search'])
+ })
+})
diff --git a/plugins/ruflo-console/tests/wf-drill.spec.ts b/plugins/ruflo-console/tests/wf-drill.spec.ts
new file mode 100644
index 0000000000..4f0ce690f4
--- /dev/null
+++ b/plugins/ruflo-console/tests/wf-drill.spec.ts
@@ -0,0 +1,201 @@
+/**
+ * The Workflows drill-down's panel (ADR-459): registered through the page's slots only, drawn from the files, moved by its keys, never showing a credential or an escape sequence.
+ * Run with
+ * npx vitest run plugins/ruflo-console/tests/wf-drill.spec.ts --testTimeout=30000
+ */
+import { describe, expect, it } from 'vitest'
+
+import { drillOf, registerDrill } from '../hooks/views/wf-detail'
+import { registerSearch } from '../hooks/views/wf-search'
+import { registerSlot, resetSlots, slotsFor, type SlotEnv } from '../hooks/views/wf-slots'
+import { SECRET } from './fixtures/wf-drill'
+import { buttonOf, click, frame, inputOf, press, screen, toAgent, useDrill, words, worldOf, liveFiles } from './fixtures/wf-drill-world'
+
+useDrill()
+
+
+describe('registration', () => {
+ it('registers the panel, the search and eight keys; a letter another feature holds falls back to the next one', () => {
+ resetSlots()
+ expect(registerSlot({ kind: 'key', id: 'other', key: 'g', label: 'x', run: () => undefined }).ok).toBe(true)
+ expect(registerDrill()).toEqual([])
+ expect(slotsFor('key').filter(slot => slot.id.startsWith('drill-')).map(slot => `${slot.id}:${slot.key}`)).toEqual(['drill-in:e', 'drill-out:z', 'drill-next:m', 'drill-prev:w', 'drill-sub:t', 'drill-follow:f', 'drill-filter:v', 'drill-search:s'])
+ expect(slotsFor('board').map(slot => slot.id)).toEqual(['drill'])
+ })
+
+ it('never takes a key the page owns, and a second registration is refused with its reason, not thrown', () => {
+ const reserved = ['p', 'x', 'r', 'h', 'y', 'n', 'j', 'k', 'l', 'b', 'd', 'o', 'u', 'i']
+
+ expect(slotsFor('key').every(slot => !reserved.includes(slot.key))).toBe(true)
+ expect(registerDrill().length).toBeGreaterThan(0)
+ expect(registerSearch()).toMatch(/already registered/)
+ })
+})
+describe('the panel', () => {
+ it('is one line and a search field until opened', async () => {
+ const world = await worldOf(liveFiles())
+ const { tree } = frame(world)
+
+ expect(words(tree)).toMatch(/Drill into this run/)
+ expect(inputOf(tree)).toBeDefined()
+ expect(words(tree)).not.toMatch(/Activity/)
+ })
+
+ it('walks Runs > Phases > Agents > Agent > one call, drawing each level from the files, and back out', async () => {
+ const world = await worldOf(liveFiles())
+
+ click(frame(world).tree, 'wf-drill-open')
+ expect(drillOf(world.state).level).toBe('phases')
+ expect(screen(world)).toMatch(/Phases: Build/)
+ expect(screen(world)).toMatch(/1 Build\s+0\/1 done/)
+
+ press(world, 'in')
+ expect(drillOf(world.state).level).toBe('agents')
+ expect(world.state.wf.ui.column).toBe('agents')
+ expect(screen(world)).toMatch(/build:x\s+running/)
+
+ press(world, 'in')
+
+ const agent = screen(world)
+
+ expect(drillOf(world.state)).toMatchObject({ level: 'agent', sub: 'activity' })
+ expect(agent).toMatch(/Agent · Activity/)
+ expect(agent).toMatch(/Bash\s+ls -la/)
+ expect(agent).toMatch(/Edit\s+\/work\/proj\/.*a\.ts/)
+ expect(agent).toMatch(/transcript: whole file/)
+ expect(agent).toMatch(/3\.0 MB read cap/)
+ expect(agent).toMatch(/4 tool calls/)
+
+ press(world, 'next')
+ press(world, 'in')
+
+ const item = screen(world)
+
+ expect(drillOf(world.state)).toMatchObject({ level: 'item', callSel: 1 })
+ expect(item).toMatch(/tool call Edit/)
+ expect(item).toMatch(/error/)
+ expect(item).toMatch(/boom/)
+ expect(item).toMatch(/"file_path"/)
+
+ press(world, 'out')
+ expect(drillOf(world.state).level).toBe('agent')
+ press(world, 'out')
+ press(world, 'out')
+ press(world, 'out')
+ expect(drillOf(world.state)).toMatchObject({ level: 'runs', open: true })
+ press(world, 'out')
+ expect(drillOf(world.state).open).toBe(false)
+ })
+
+ it('shows no credential and no escape sequence at any level', async () => {
+ const world = await worldOf(liveFiles())
+
+ for (const step of ['open', 'in', 'in', 'next', 'in']) {
+ if (step === 'open') click(frame(world).tree, 'wf-drill-open')
+ else press(world, step)
+
+ const text = screen(world)
+
+ expect(text).not.toContain(SECRET)
+ expect(text).not.toContain('abcdefghijklmnop')
+ expect(text).not.toMatch(/\u001b/)
+ }
+
+ expect(screen(world)).toMatch(/Edit/)
+ })
+
+ it('says why it cannot go deeper, in the page, instead of a dead key', async () => {
+ const world = await worldOf(liveFiles())
+
+ click(frame(world).tree, 'wf-drill-open')
+ press(world, 'in')
+ press(world, 'in')
+ press(world, 'sub')
+ press(world, 'sub')
+ expect(drillOf(world.state).sub).toBe('files')
+ press(world, 'in')
+ expect(screen(world)).toMatch(/no deeper level/)
+ expect(drillOf(world.state).level).toBe('agent')
+ })
+
+ it('keeps its breadcrumb clickable: a shallower level is one press away', async () => {
+ const world = await worldOf(liveFiles())
+
+ toAgent(world)
+ click(frame(world).tree, 'wf-crumb-phases')
+ expect(drillOf(world.state).level).toBe('phases')
+ expect(buttonOf(frame(world).tree, 'wf-crumb-item')).toBeUndefined()
+ })
+})
+describe('the Log', () => {
+ it('lists the lines with the newest last while following, and the level filter narrows them', async () => {
+ const world = await worldOf(liveFiles())
+
+ toAgent(world)
+ click(frame(world).tree, 'wf-sub-log')
+
+ const all = screen(world)
+
+ expect(all).toMatch(/following/)
+ expect(all).toMatch(/assist\s+all done|assi\s+all done/)
+ expect(all).toMatch(/level: all lines/)
+ expect(all).toMatch(/not a stream/)
+
+ press(world, 'filter')
+ press(world, 'filter')
+ press(world, 'filter')
+ expect(screen(world)).toMatch(/level: errors only/)
+ expect(screen(world)).toMatch(/Edit .*\(failed\)/)
+ expect(screen(world)).not.toMatch(/all done/)
+
+ press(world, 'follow')
+ expect(drillOf(world.state).follow).toBe(false)
+ expect(screen(world)).toMatch(/○ follow/)
+ })
+
+ it('merges the whole phase when the scope is switched, and says how many agents were not in memory', async () => {
+ const world = await worldOf(liveFiles())
+
+ toAgent(world)
+ click(frame(world).tree, 'wf-sub-log')
+ click(frame(world).tree, 'wf-log-scope')
+ expect(screen(world)).toMatch(/scope: whole phase/)
+ expect(drillOf(world.state).scope).toBe('phase')
+ })
+})
+describe('a ruflo agent', () => {
+ it('has nothing deeper than its row, and the page says so', async () => {
+ const world = await worldOf(liveFiles())
+ const { env } = frame(world)
+ const agent = { ...(env.agent as NonNullable<SlotEnv['agent']>), ruflo: { id: 'agent-1', type: 'coder', status: 'idle' } as never }
+ const ruflo: SlotEnv = { ...env, agent }
+ const board = slotsFor('board').find(slot => slot.id === 'drill')
+
+ world.state.wf.ui = { ...world.state.wf.ui, column: 'agents' }
+ click(frame(world).tree, 'wf-drill-open')
+ slotsFor('key').find(slot => slot.id === 'drill-in')?.run({ ...ruflo, ui: { ...ruflo.ui, column: 'agents' } })
+
+ const text = words(board?.render({ ...ruflo, ui: { ...ruflo.ui, column: 'agents' } }))
+
+ expect(text).toMatch(/A ruflo agent keeps no transcript, worktree or return/)
+ expect(drillOf(world.state).level).toBe('agents')
+ })
+})
+
+describe('layout', () => {
+ it('draws at 40, 80 and 150 columns, opened at every level, without throwing', async () => {
+ const world = await worldOf(liveFiles())
+
+ for (const columns of [40, 80, 150]) {
+ expect(() => words(frame(world, columns).tree)).not.toThrow()
+ }
+
+ click(frame(world).tree, 'wf-drill-open')
+
+ for (const step of ['in', 'in', 'next', 'in', 'out']) {
+ press(world, step)
+
+ for (const columns of [40, 80, 150]) expect(words(frame(world, columns).tree)).toMatch(/Drill-down/)
+ }
+ })
+})
diff --git a/v3/docs/adr/ADR-459-workflows-drill-down.md b/v3/docs/adr/ADR-459-workflows-drill-down.md
new file mode 100644
index 0000000000..9468d97148
--- /dev/null
+++ b/v3/docs/adr/ADR-459-workflows-drill-down.md
@@ -0,0 +1,97 @@
+# ADR 459: Workflows drill-down: levels, activity, log, files, result, search
+
+Status: Accepted
+
+Date: 2026-10-05
+
+Builds on: ADR-458 (the page and its data), ADR-464 (the page's wiring and slot seams)
+
+## 1. Context
+
+The Workflows page shows a run, its phases and one phase's agents, and an inspector with the numbers of one agent. It cannot answer
+the next questions: what did that agent do, what did it say, which files did it touch, what did it hand back, and where in all of this
+did the word X appear. The answers are in files Claude Code already writes (the agent's transcript, the run's journal, the agent's
+worktree), so the console can show them without running anything, if it keeps to what it can verify and says what it cannot read.
+
+The seams are fixed by ADR-464: a feature adds a slot from its own module and edits no shared file. A slot is handed the frame's
+context and the cursor (no host, no `fs`), a pane hotkey is one lowercase letter or digit the page does not own, and Enter, Esc, `h`
+(Help's) and `/` are not available to a slot.
+
+## 2. Decision
+
+**Levels.** `Runs > Phases > Agents > one Agent (Activity | Log | Files | Result) > one tool call or message`, drawn by a board slot under
+the run board with a clickable breadcrumb. The first three levels are the page's own cursor (a key there sends the page the `h l j k [ ]`
+it already understands), so the board and the drill never disagree. From the agent down the position is the drill's own, kept in a
+module record keyed by the console's `State` (the page's `WfUi` is closed).
+
+**Keys.** Eight key slots, each trying its letters in turn because another feature may hold one: `g` deeper (then `e`), `z` back, `m`
+next, `w` prev, `t` next tab, `f` follow, `v` level filter, `s` search (the field takes the keys). Every one is also a button. Enter,
+Esc, `h` and `/` cannot be bound through a slot: `drillKey(env, verb)` is exported so the merge owner can route them if the page grows
+that, and until then this is stated rather than faked.
+
+**Activity** is the tool-call timeline: each `tool_use` paired with its `tool_result` by id (a streamed message repeats its blocks, a call
+counts once), with time from the first call and span, a mark for ok, error and no result in the part read. **Log** is the transcript tail,
+one washed line per entry, with a level filter (all, messages, tool calls, errors), a scope (this agent, or the whole phase merged by
+time, each agent's newest 400 lines) and follow, which pins the window to the newest line and is re-drawn on the page's refresh: it is
+not a stream and the page says so. **Files** lists the files the tool inputs name, with what was done to each, and the worktree's diff
+stat when the agent had one. **Result** is the structured return the run's journal kept for the agent. The deepest level shows one call
+(input and output) or one message in full, scrolled by buttons.
+
+**Search** is one field under the panel over every level at once: run names and ids, phase titles, agent labels and previews, tool calls
+(name, summary, input), transcript text (messages and outputs) and mission tasks when `observation.json` has them. Hits are grouped by
+level (six shown a group, all counted) and a click, or Enter in the field for the first, goes to the exact place: the cursor, then the
+sub-tab and the call or line. A mission task has no place on this page, so its hit opens the Missions page. It searches only what is in
+memory and says how many agents' transcripts were not (never guessing), and the scan stops at 8,000,000 characters and says so.
+
+**What is read, and by whom.** Views never read. They look at what is already in memory: the console's read cache, which the page's own
+refresh fills for runs still in progress. A finished run's figures come from its record, so the page does not read its transcripts, and a
+transcript over the 3.0 MB read cap is only tail-read by the host. For those the drill offers a button, and the buttons work only if the
+merge owner calls `bindWorkflowDrill(state, host)` once at boot (the host is not part of a slot's environment). Unbound, the drill draws
+everything the cache holds and says, in place, what it could not read and why: no dead button. Bound, the loaders are:
+
+- a transcript: `<configDir>/projects/**/agent-<id>.jsonl`, whole to 3.0 MB, else the last 400 KB;
+- the journal: `<run dir>/journal.jsonl` to 1.0 MB, for one agent's result;
+- the worktree: one process, `git --no-optional-locks -c core.fsmonitor=false -C <worktree> diff --numstat --no-renames --no-color
+ --no-ext-diff --no-textconv HEAD --`, fixed argv with no shell, only for a worktree path inside the project's working directory with no
+ `..` part, 8 s, output cut at 200 KB and 400 files. It reads tracked changes only and says so; it is not behind the confirm card because
+ it changes nothing.
+
+Paths are checked before any read: a transcript or journal path must lie under `<configDir>/projects/` with no `..`, NUL or newline.
+
+**Washing.** Every string kept from a file passes `cleanBlock`: whole ANSI sequences removed, controls (newline kept), hidden and bidi
+characters, credentials masked (the mask runs over a little more than the cap, so a token straddling the cut is masked whole), then cut.
+Ids and paths are not masked. Caps are printed: characters per field (6,000, "first N of M"), entries per transcript (newest 2,000), rows
+on screen, the transcript read cap and the scan cap.
+
+**No stop, no message.** The console cannot stop or message a running Claude Code workflow. The page already says so where that would be
+(ADR-464); the drill adds no verb and no button for it, and none for a ruflo agent either: it keeps no transcript, worktree or return, so
+the drill says that instead of opening an empty level.
+
+**Seam use.** Board slots `drill` and `drill-search`, eight key slots, one notice slot (`drill-follow`) used as the "a read just finished"
+tick that re-reads the held tail of a followed log. `views/wf-register.ts` gets one line: `import '../wf-drill'`.
+
+## 3. Consequences
+
+- The drill costs nothing while closed beyond one hint line and the search field; parsing is memoised by the transcript text itself.
+- On a finished run, or a transcript over the read cap, the drill is only as complete as the host binding. That is the one decision the
+ merge owner takes: call `bindWorkflowDrill` (recommended) or accept the stated empty states.
+- The whole-phase log re-merges each draw: 66 ms at 60 agents, worst case, about 10 ms for a typical phase.
+- Enter, Esc, `h` and `/` are buttons and letters until the page lets a slot see them.
+- The follow tick for a tail-read transcript fires once per page read, so it moves at the console's refresh cadence.
+
+## 4. Test and benchmark plan
+
+`tests/wf-data.spec.ts` (31 tests): washing and caps (the boundary, a straddling token), pairing by id, errors, the tail and the entry cap,
+the journal result, the log's filters, merge and window, the trail's every step and refusal, the search's levels, jumps, unread and caps.
+`tests/wf-drill.spec.ts`, `wf-drill-read.spec.ts` and `wf-drill-search.spec.ts` (31 tests) run the real page over an in-memory disk:
+registration and key fallback, the walk from Runs to one call and back, no credential or escape at any level, the diff argv, the path and
+worktree refusals, the finished-run empty state and the on-demand read, the tail, the search by click and by Enter. Mutation-checked: the
+field cap boundary, pairing by id, the level filter, the mask, the finished-run empty state, hit grouping, the ruflo gate, the
+project-directory gate, follow, the scan cap, the diff hardening flags, the jump's filter reset and the no-mask rule for paths (two mutants) each fail a test.
+Measured (this host): parsing a 4.8 MB, 6,000-line transcript 59 ms once (then memoised); a real 0.35 MB workflow transcript 4 to 13 ms;
+search over 60 agents of 2,000 entries 23 ms (the cap stops it); filter and window 0.1 ms.
+
+## 5. Rollback
+
+Remove the `import '../wf-drill'` line from `views/wf-register.ts` (and the `bindWorkflowDrill` call if added). The page returns to ADR-464's
+board. Nothing is persisted and no file outside the new modules was edited.