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): swarm and workflow management page (ADR-458)

ruv6ac184d481fe
diff --git a/plugins/ruflo-console/hooks/data/workflows-nav.ts b/plugins/ruflo-console/hooks/data/workflows-nav.ts
new file mode 100644
index 0000000000..7496444123
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/workflows-nav.ts
@@ -0,0 +1,63 @@
+/**
+ * Where the cursor is in the workflows view, and how a key moves it (ADR-458). Pure, so the keys are tested without a
+ * screen: j/k move within the focused column, h/l switch column, Enter inspects the row, [ and ] switch run.
+ */
+import { currentPhase, swarmRun, type WfAgent, type WfPhase, type WfRun } from './workflows'
+import type { AgentRecord, SwarmInfo } from './parse'
+
+export type WfColumn = 'phases' | 'agents'
+export type WfUi = { run: number; phase: number; agent: number; column: WfColumn; isInspecting: boolean }
+export type WfKey = 'j' | 'k' | 'h' | 'l' | 'enter' | 'escape' | '[' | ']'
+
+export const newWfUi = (): WfUi => ({ run: 0, phase: 0, agent: 0, column: 'phases', isInspecting: false })
+
+/** Workflow runs and the ruflo swarm in one list: whatever is running first, the rest as they come (newest first). */
+export function allRuns(workflows: readonly WfRun[], swarm: SwarmInfo | null, agents: readonly AgentRecord[], nowMs: number): WfRun[] {
+ const own = swarmRun(swarm, agents, nowMs)
+ const runs = own === null ? [...workflows] : [...workflows, own]
+ const isLive = (run: WfRun) => run.running > 0
+
+ return [...runs.filter(isLive), ...runs.filter(run => !isLive(run))]
+}
+
+const clamp = (value: number, size: number): number => (size <= 0 ? 0 : Math.max(0, Math.min(size - 1, value)))
+
+/** The run, phase and agent the cursor is on, each null where the list is empty; indexes that fell off a shorter list are pulled back. */
+export function pick(ui: WfUi, runs: readonly WfRun[]): { run: WfRun | null; phase: WfPhase | null; agent: WfAgent | null; ui: WfUi } {
+ const run = runs[clamp(ui.run, runs.length)] ?? null
+ const phase = run?.phases[clamp(ui.phase, run.phases.length)] ?? null
+ const agent = phase?.agents[clamp(ui.agent, phase.agents.length)] ?? null
+
+ return { run, phase, agent, ui: { ...ui, run: clamp(ui.run, runs.length), phase: clamp(ui.phase, run?.phases.length ?? 0), agent: clamp(ui.agent, phase?.agents.length ?? 0) } }
+}
+
+/** A run's first view: the cursor starts on the phase the run is in. */
+export const startOn = (ui: WfUi, run: WfRun | null): WfUi => ({ ...ui, phase: run === null ? 0 : (currentPhase(run.phases) ?? 0), agent: 0, isInspecting: false })
+
+export function walk(ui: WfUi, runs: readonly WfRun[], key: WfKey): WfUi {
+ const here = pick(ui, runs)
+ const at = here.ui
+
+ switch (key) {
+ case 'h':
+ return { ...at, column: 'phases' }
+ case 'l':
+ return here.phase !== null && here.phase.agents.length > 0 ? { ...at, column: 'agents' } : at
+ case 'j':
+ case 'k': {
+ const by = key === 'j' ? 1 : -1
+
+ return at.column === 'phases' ? { ...at, phase: clamp(at.phase + by, here.run?.phases.length ?? 0), agent: 0 } : { ...at, agent: clamp(at.agent + by, here.phase?.agents.length ?? 0) }
+ }
+ case 'enter':
+ return at.isInspecting ? { ...at, isInspecting: false } : here.agent === null ? at : { ...at, isInspecting: true, column: 'agents' }
+ case 'escape':
+ return { ...at, isInspecting: false }
+ case '[':
+ case ']': {
+ const run = clamp(at.run + (key === ']' ? 1 : -1), runs.length)
+
+ return run === at.run ? at : startOn({ ...at, run, column: 'phases' }, runs[run] ?? null)
+ }
+ }
+}
diff --git a/plugins/ruflo-console/hooks/data/workflows-read.ts b/plugins/ruflo-console/hooks/data/workflows-read.ts
new file mode 100644
index 0000000000..b9ce599e0d
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/workflows-read.ts
@@ -0,0 +1,91 @@
+/**
+ * The disk half of the workflows view (ADR-458): finds the newest workflow runs of this project under Claude Code's
+ * config directory and hands their text to `buildRun`. Read-only and bounded: at most MAX_RUNS runs, MAX_AGENTS agents
+ * a run, and a transcript over TRANSCRIPT_CAP bytes is tail-read where the host can (`readTail`), else not read at all and
+ * counted in `skipped`, so its tokens read n/a rather than a guess. A finished run's own record carries every figure, so
+ * its transcripts are not read.
+ */
+import { readBounded, under, type ReadCache, type ReaderFs } from './files'
+import { buildRun, type RunInput, type WfRun } from './workflows'
+
+/** The engine refuses files over 4 MiB; below this a transcript is read whole. */
+export const TRANSCRIPT_CAP = 3_000_000
+/** How much of an oversized transcript's end is read, where the host offers it. */
+export const TAIL_BYTES = 400_000
+export const MAX_RUNS = 6
+export const MAX_AGENTS = 60
+const MAX_SESSIONS = 30
+
+export type WorkflowFs = ReaderFs & { readTail?: (path: string, bytes: number) => Promise<string> }
+
+export type WorkflowRuns = { runs: WfRun[]; /** The project's folder under the config directory, or null where none is known. */ root: string | null; capBytes: number; /** Transcripts left unread for size, by path. */ skipped: string[]; /** How many runs the folders hold beyond those shown. */ more: number }
+
+/** Claude Code's folder name for a project: every character that is not a letter or digit becomes `-`. */
+export const slugOf = (cwd: string): string => cwd.replace(/[^A-Za-z0-9]/g, '-')
+
+const safeList = (fs: ReaderFs, path: string) => fs.list(path).catch(() => [] as Awaited<ReturnType<ReaderFs['list']>>)
+
+export async function readWorkflowRuns(fs: WorkflowFs, cache: ReadCache, options: { configDir: string | null; cwd: string; nowMs: number; maxRuns?: number }): Promise<WorkflowRuns> {
+ const empty: WorkflowRuns = { runs: [], root: null, capBytes: TRANSCRIPT_CAP, skipped: [], more: 0 }
+
+ if (options.configDir === null) return empty
+
+ const root = under(options.configDir, `projects/${slugOf(options.cwd)}`)
+ const sessions = (await safeList(fs, root)).filter(entry => /^[0-9a-f-]{36}$/.test(entry.name)).sort((a, b) => (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0)).slice(0, MAX_SESSIONS)
+ const found = (
+ await Promise.all(sessions.map(async session => (await safeList(fs, under(root, `${session.name}/subagents/workflows`))).filter(entry => /^wf_[A-Za-z0-9-]{1,40}$/.test(entry.name)).map(entry => ({ session: session.name, id: entry.name, mtimeMs: entry.mtimeMs ?? 0 }))))
+ )
+ .flat()
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
+ const chosen = found.slice(0, options.maxRuns ?? MAX_RUNS)
+ const skipped: string[] = []
+
+ const runs = await Promise.all(
+ chosen.map(async ({ session, id }) => {
+ const dir = under(root, `${session}/subagents/workflows/${id}`)
+ const entries = await safeList(fs, dir)
+ const text = async (path: string, max?: number) => (await readBounded(fs, cache, path, max)).text
+ const record = await text(under(root, `${session}/workflows/${id}.json`), 6_000_000)
+ const scripts = record === null ? await safeList(fs, under(root, `${session}/workflows/scripts`)) : []
+ const scriptName = scripts.find(entry => entry.name.endsWith(`-${id}.js`))?.name
+ const agentIds = [...new Set(entries.flatMap(entry => /^agent-([A-Za-z0-9]+)\.(?:meta\.json|jsonl)$/.exec(entry.name)?.[1] ?? []))].slice(0, MAX_AGENTS)
+ const agents: RunInput['agents'] = new Map(
+ await Promise.all(
+ agentIds.map(async agentId => {
+ const path = under(dir, `agent-${agentId}.jsonl`)
+ const meta = await text(under(dir, `agent-${agentId}.meta.json`), 20_000)
+ const size = entries.find(entry => entry.name === `agent-${agentId}.jsonl`)?.size ?? 0
+ let transcript: string | null = null
+ let isTail = false
+
+ if (record === null && size > 0) {
+ if (size <= TRANSCRIPT_CAP) transcript = await text(path, TRANSCRIPT_CAP)
+ else if (fs.readTail !== undefined) {
+ transcript = await fs.readTail(path, TAIL_BYTES).catch(() => null)
+ isTail = transcript !== null
+ }
+
+ if (transcript === null) skipped.push(path)
+ }
+
+ return [agentId, { meta, transcript, isTail, path }] as const
+ }),
+ ),
+ )
+ const lastActivityMs = entries.reduce((latest, entry) => Math.max(latest, entry.mtimeMs ?? 0), 0)
+
+ return buildRun({
+ id,
+ dir,
+ journal: await text(under(dir, 'journal.jsonl'), 1_000_000),
+ agents,
+ record,
+ script: scriptName === undefined ? null : await text(under(root, `${session}/workflows/scripts/${scriptName}`), 200_000),
+ nowMs: options.nowMs,
+ ...(lastActivityMs > 0 && { lastActivityMs }),
+ })
+ }),
+ )
+
+ return { runs, root, capBytes: TRANSCRIPT_CAP, skipped, more: Math.max(0, found.length - chosen.length) }
+}
diff --git a/plugins/ruflo-console/hooks/data/workflows.ts b/plugins/ruflo-console/hooks/data/workflows.ts
new file mode 100644
index 0000000000..9f6bb25fe9
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/workflows.ts
@@ -0,0 +1,447 @@
+/**
+ * Workflow runs as Claude Code writes them, and the ruflo swarm in the same shape (ADR-458). Pure: every function here
+ * takes text or records and returns records; `data/workflows-read.ts` is the only part that touches the disk.
+ *
+ * What a run directory holds (schemas read from real runs, Claude Code 2.1.x):
+ * <session>/subagents/workflows/<runId>/journal.jsonl {type:'launched'} | {type:'started',key,agentId,label,phase} | {type:'result',key,agentId,result}
+ * <session>/subagents/workflows/<runId>/agent-<id>.meta.json {description, workflowPhase, spawnedWithWorktree?, worktreePath?, agentType}
+ * <session>/subagents/workflows/<runId>/agent-<id>.jsonl transcript lines; assistant lines carry message.{id,model,usage}, every line a timestamp
+ * <session>/workflows/<runId>.json written when the run ends: {status, phases, durationMs, startTime, workflowProgress[]}
+ * <session>/workflows/scripts/<name>-<runId>.js the script, whose `meta.phases` names the phases (live runs have no .json yet)
+ * Unknown event types and keys are ignored, a half-written last line is dropped, and a missing source is a missing fact:
+ * nothing here is estimated.
+ */
+import { agentLabels, shortId, type AgentRecord, type SwarmInfo } from './parse'
+
+export type AgentState = 'running' | 'done' | 'failed' | 'stale' | 'idle' | 'queued'
+
+export type WfAgent = {
+ id: string
+ label: string
+ phase: string
+ state: AgentState
+ model?: string
+ hasWorktree: boolean
+ worktreePath?: string
+ /** Context tokens of the agent's latest request (the figure Claude Code's panel shows); a tail-read transcript makes it a floor. */
+ tokens?: number
+ isTokensPartial?: boolean
+ startedMs?: number
+ /** For a running agent the time since it started; for a finished one the span of its transcript or the run record's own figure. */
+ elapsedMs?: number
+ /** The transcript to open (workflow agents), or the agent's id (ruflo agents). */
+ transcriptPath?: string
+ resultPreview?: string
+ toolCalls?: number
+ lastTool?: string
+ /** Set for a ruflo agent: what the confirm-gated verbs act on. */
+ ruflo?: AgentRecord
+}
+
+export type WfPhase = { title: string; detail?: string; agents: WfAgent[]; done: number; total: number; running: number; failed: number }
+
+export type RunState = 'running' | 'completed' | 'failed' | 'stalled' | 'finished' | 'active'
+
+export type WfRun = {
+ id: string
+ name: string
+ kind: 'workflow' | 'ruflo-swarm'
+ state: RunState
+ phases: WfPhase[]
+ running: number
+ done: number
+ failed: number
+ idle: number
+ total: number
+ /** Sum of the agents whose tokens are known; null when none is. */
+ totalTokens: number | null
+ isTokensPartial: boolean
+ startedMs?: number
+ durationMs?: number
+ dir?: string
+ /** True where the run record's `workflowProgress` gave the figures (a finished run), false where they were derived from journal and transcripts. */
+ hasRecord: boolean
+}
+
+const asRecord = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)
+const str = (value: unknown, max = 200): string | undefined => (typeof value === 'string' && value !== '' ? value.slice(0, max) : undefined)
+const num = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)
+
+/** JSONL as records: a line that does not parse (a half-written tail) is dropped, never thrown on. */
+export function jsonLines(text: string | null): Record<string, unknown>[] {
+ if (text === null) return []
+
+ const out: Record<string, unknown>[] = []
+
+ for (const line of text.split('\n')) {
+ if (line.length < 2 || line[0] !== '{') continue
+
+ try {
+ const record = asRecord(JSON.parse(line))
+
+ if (record !== null) out.push(record)
+ } catch {
+ /* a partial line */
+ }
+ }
+
+ return out
+}
+
+export type JournalAgent = { agentId: string; label: string; phase?: string; hasResult: boolean; resultPreview?: string }
+
+/** The agents a journal names, in launch order, with whether each has reported a result. Events of any other type are ignored. */
+export function parseJournal(text: string | null): { isLaunched: boolean; agents: JournalAgent[] } {
+ const byId = new Map<string, JournalAgent>()
+ let isLaunched = false
+
+ for (const event of jsonLines(text)) {
+ const id = str(event.agentId, 80)
+
+ if (event.type === 'launched') isLaunched = true
+ else if (event.type === 'started' && id !== undefined) {
+ const phase = str(event.phase, 80)
+
+ byId.set(id, { agentId: id, label: str(event.label, 80) ?? id, hasResult: false, ...(phase !== undefined && { phase }) })
+ } else if (event.type === 'result' && id !== undefined) {
+ const held = byId.get(id) ?? { agentId: id, label: id, hasResult: false }
+ const preview = typeof event.result === 'string' ? event.result.replace(/\s+/g, ' ').slice(0, 160) : asRecord(event.result) !== null ? `structured result (${Object.keys(event.result as object).length} fields)` : undefined
+
+ byId.set(id, { ...held, hasResult: true, ...(preview !== undefined && preview !== '' && { resultPreview: preview }) })
+ }
+ }
+
+ return { isLaunched, agents: [...byId.values()] }
+}
+
+export type AgentMeta = { description?: string; phase?: string; hasWorktree: boolean; worktreePath?: string; agentType?: string }
+
+export function parseAgentMeta(text: string | null): AgentMeta {
+ let record: Record<string, unknown> | null = null
+
+ try {
+ record = text === null ? null : asRecord(JSON.parse(text))
+ } catch {
+ record = null
+ }
+
+ const description = str(record?.description, 80)
+ const phase = str(record?.workflowPhase, 80)
+ const worktreePath = str(record?.worktreePath, 300)
+ const agentType = str(record?.agentType, 60)
+
+ return { hasWorktree: record?.spawnedWithWorktree === true, ...(description !== undefined && { description }), ...(phase !== undefined && { phase }), ...(worktreePath !== undefined && { worktreePath }), ...(agentType !== undefined && { agentType }) }
+}
+
+export type TranscriptFacts = { model?: string; tokens?: number; firstMs?: number; lastMs?: number; toolCalls: number; lastTool?: string; messages: number }
+
+/**
+ * What a transcript says: the model of its last answer, the context tokens of its latest request (input + cache read + cache
+ * write + output, each request counted once however many lines streamed it), the first and last timestamps, and tool calls.
+ * `isTail` says the text begins mid-file: the first line is dropped and the first timestamp is then not the start.
+ */
+export function parseTranscript(text: string | null, isTail = false): TranscriptFacts {
+ const lines = jsonLines(isTail && text !== null ? text.slice(text.indexOf('\n') + 1) : text)
+ const usage = new Map<string, number>()
+ let model: string | undefined
+ let firstMs: number | undefined
+ let lastMs: number | undefined
+ let lastKey: string | undefined
+ let toolCalls = 0
+ let lastTool: string | undefined
+
+ for (const [index, line] of lines.entries()) {
+ const at = typeof line.timestamp === 'string' ? Date.parse(line.timestamp) : Number.NaN
+
+ if (Number.isFinite(at)) {
+ firstMs ??= at
+ lastMs = at
+ }
+
+ const message = asRecord(line.message)
+
+ if (line.type !== 'assistant' || message === null) continue
+
+ const u = asRecord(message.usage)
+ const key = str(message.id, 80) ?? `line-${index}`
+
+ if (u !== null) {
+ usage.set(key, (num(u.input_tokens) ?? 0) + (num(u.cache_creation_input_tokens) ?? 0) + (num(u.cache_read_input_tokens) ?? 0) + (num(u.output_tokens) ?? 0))
+ lastKey = key
+ }
+
+ model = str(message.model, 60) ?? model
+
+ // A streamed message repeats its content blocks: count a tool_use by its id.
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ const b = asRecord(block)
+
+ if (b?.type === 'tool_use') {
+ toolCalls += 1
+ lastTool = str(b.name, 40) ?? lastTool
+ }
+ }
+ }
+ }
+
+ const tokens = lastKey === undefined ? undefined : usage.get(lastKey)
+
+ return { toolCalls, messages: usage.size, ...(model !== undefined && { model }), ...(tokens !== undefined && { tokens }), ...(firstMs !== undefined && { firstMs }), ...(lastMs !== undefined && { lastMs }), ...(lastTool !== undefined && { lastTool }) }
+}
+
+export type RunRecordAgent = { agentId: string; label?: string; phase?: string; model?: string; state?: string; startedMs?: number; tokens?: number; durationMs?: number; toolCalls?: number; lastTool?: string }
+export type RunRecord = { name?: string; status?: string; phases: { title: string; detail?: string }[]; startedMs?: number; durationMs?: number; totalTokens?: number; defaultModel?: string; agents: RunRecordAgent[] }
+
+/** `<session>/workflows/<runId>.json`: the finished run's own account of its phases and agents. */
+export function parseRunRecord(text: string | null): RunRecord | null {
+ let record: Record<string, unknown> | null = null
+
+ try {
+ record = text === null ? null : asRecord(JSON.parse(text))
+ } catch {
+ return null
+ }
+
+ if (record === null) return null
+
+ const phases = (Array.isArray(record.phases) ? record.phases : []).flatMap(entry => {
+ const p = asRecord(entry)
+ const title = str(p?.title, 60)
+ const detail = str(p?.detail, 100)
+
+ return title === undefined ? [] : [{ title, ...(detail !== undefined && { detail }) }]
+ })
+ const agents = (Array.isArray(record.workflowProgress) ? record.workflowProgress : []).flatMap(entry => {
+ const a = asRecord(entry)
+ const agentId = str(a?.agentId, 80)
+
+ if (a === null || a.type !== 'workflow_agent' || agentId === undefined) return []
+
+ const label = str(a.label, 80)
+ const phase = str(a.phaseTitle, 80)
+ const model = str(a.model, 60)
+ const state = str(a.state, 20)
+ const startedMs = num(a.startedAt)
+ const tokens = num(a.tokens)
+ const durationMs = num(a.durationMs)
+ const toolCalls = num(a.toolCalls)
+ const lastTool = str(a.lastToolName, 40)
+
+ return [{ agentId, ...(label !== undefined && { label }), ...(phase !== undefined && { phase }), ...(model !== undefined && { model }), ...(state !== undefined && { state }), ...(startedMs !== undefined && { startedMs }), ...(tokens !== undefined && { tokens }), ...(durationMs !== undefined && { durationMs }), ...(toolCalls !== undefined && { toolCalls }), ...(lastTool !== undefined && { lastTool })}]
+ })
+ const name = str(record.workflowName, 80)
+ const status = str(record.status, 30)
+ const startedMs = num(record.startTime)
+ const durationMs = num(record.durationMs)
+ const totalTokens = num(record.totalTokens)
+ const defaultModel = str(record.defaultModel, 60)
+
+ return { phases, agents, ...(name !== undefined && { name }), ...(status !== undefined && { status }), ...(startedMs !== undefined && { startedMs }), ...(durationMs !== undefined && { durationMs }), ...(totalTokens !== undefined && { totalTokens }), ...(defaultModel !== undefined && { defaultModel }) }
+}
+
+/** `meta = { name, phases: [{ title }, …] }` out of a workflow script's text, read as text (the script is never run). */
+export function parseScriptMeta(text: string | null): { name?: string; phases: { title: string; detail?: string }[] } {
+ const head = text?.slice(0, 6000) ?? ''
+ const name = /\bname:\s*['"`]([^'"`\n]{1,80})['"`]/.exec(head)?.[1]
+ const block = /\bphases:\s*\[([\s\S]*?)\]\s*,?\s*\n?\s*\}/.exec(head)?.[1] ?? ''
+ const phases = [...block.matchAll(/title:\s*['"`]([^'"`\n]{1,60})['"`](?:\s*,\s*detail:\s*['"`]([^'"`\n]{1,100})['"`])?/g)].map(match => ({ title: match[1] as string, ...(match[2] !== undefined && { detail: match[2] }) }))
+
+ return { phases, ...(name !== undefined && { name }) }
+}
+
+/** An agent with no result and no sign of life this long is shown as stale, not running: a crashed run leaves the same files. */
+export const STALE_MS = 15 * 60_000
+
+export type RunInput = {
+ id: string
+ dir?: string
+ journal: string | null
+ /** agentId → meta file text, transcript text (and whether it is a tail), and its path. */
+ agents: ReadonlyMap<string, { meta: string | null; transcript: string | null; isTail: boolean; path: string }>
+ record: string | null
+ script: string | null
+ nowMs: number
+ /** The newest mtime among the run's files: what "no sign of life" is measured from when a transcript is unread. */
+ lastActivityMs?: number
+}
+
+const STATE_OF_RECORD: Record<string, AgentState> = { done: 'done', completed: 'done', running: 'running', queued: 'queued', failed: 'failed', error: 'failed', errored: 'failed' }
+
+/** One run, merged from every source it has: the record where it exists, else the journal, metas and transcripts. */
+export function buildRun(input: RunInput): WfRun {
+ const journal = parseJournal(input.journal)
+ const record = parseRunRecord(input.record)
+ const script = parseScriptMeta(input.script)
+ const ids = [...new Set([...journal.agents.map(a => a.agentId), ...(record?.agents.map(a => a.agentId) ?? [])])]
+ const fromJournal = new Map(journal.agents.map(a => [a.agentId, a]))
+ const fromRecord = new Map((record?.agents ?? []).map(a => [a.agentId, a]))
+
+ const agents: WfAgent[] = ids.map(id => {
+ const j = fromJournal.get(id)
+ const r = fromRecord.get(id)
+ const source = input.agents.get(id)
+ const meta = parseAgentMeta(source?.meta ?? null)
+ const facts = source === undefined ? null : parseTranscript(source.transcript, source.isTail)
+ const startedMs = r?.startedMs ?? (source?.isTail === true ? undefined : facts?.firstMs)
+ const lastSeen = facts?.lastMs ?? input.lastActivityMs
+ const hasResult = j?.hasResult === true
+ const recorded = r?.state === undefined ? undefined : STATE_OF_RECORD[r.state.toLowerCase()]
+ const state: AgentState = recorded ?? (hasResult ? 'done' : lastSeen !== undefined && input.nowMs - lastSeen > STALE_MS ? 'stale' : j === undefined ? 'queued' : 'running')
+ const elapsedMs = r?.durationMs ?? (startedMs === undefined ? undefined : Math.max(0, (state === 'running' ? input.nowMs : (facts?.lastMs ?? input.nowMs)) - startedMs))
+ const tokens = r?.tokens ?? facts?.tokens
+ const model = r?.model ?? facts?.model ?? record?.defaultModel
+ const phase = r?.phase ?? j?.phase ?? meta.phase ?? '—'
+ const label = r?.label ?? j?.label ?? meta.description ?? id
+ const resultPreview = j?.resultPreview
+ const toolCalls = r?.toolCalls ?? (facts !== null && facts.toolCalls > 0 ? facts.toolCalls : undefined)
+ const lastTool = r?.lastTool ?? facts?.lastTool
+
+ return {
+ id,
+ label,
+ phase,
+ state,
+ hasWorktree: meta.hasWorktree,
+ ...(model !== undefined && { model }),
+ ...(meta.worktreePath !== undefined && { worktreePath: meta.worktreePath }),
+ ...(tokens !== undefined && { tokens }),
+ ...(r?.tokens === undefined && tokens !== undefined && source?.isTail === true && { isTokensPartial: true }),
+ ...(startedMs !== undefined && { startedMs }),
+ ...(elapsedMs !== undefined && { elapsedMs }),
+ ...(source !== undefined && { transcriptPath: source.path }),
+ ...(resultPreview !== undefined && { resultPreview }),
+ ...(toolCalls !== undefined && { toolCalls }),
+ ...(lastTool !== undefined && { lastTool }),
+ }
+ })
+
+ const declared = record?.phases.length ? record.phases : script.phases
+ const phases = groupPhases(agents, declared)
+ const counts = tally(agents)
+ const known = agents.filter(agent => agent.tokens !== undefined)
+ const sum = known.reduce((total, agent) => total + (agent.tokens ?? 0), 0)
+ const status = record?.status?.toLowerCase()
+ const state: RunState = status === undefined ? (counts.running > 0 ? 'running' : counts.stale > 0 ? 'stalled' : counts.failed > 0 ? 'failed' : 'finished') : /fail|error/.test(status) ? 'failed' : /complete|done|success/.test(status) ? 'completed' : counts.running > 0 ? 'running' : 'finished'
+ const startedMs = record?.startedMs ?? agents.reduce<number | undefined>((least, agent) => (agent.startedMs === undefined ? least : least === undefined ? agent.startedMs : Math.min(least, agent.startedMs)), undefined)
+
+ return {
+ id: input.id,
+ name: record?.name ?? script.name ?? input.id,
+ kind: 'workflow',
+ state,
+ phases,
+ running: counts.running,
+ done: counts.done,
+ failed: counts.failed,
+ idle: 0,
+ total: agents.length,
+ // Where the record states a total it is the one to show: it counts agents whose files are gone.
+ totalTokens: record?.totalTokens ?? (known.length === 0 ? null : sum),
+ isTokensPartial: record?.totalTokens === undefined && agents.some(agent => agent.isTokensPartial === true || agent.tokens === undefined),
+ ...(startedMs !== undefined && { startedMs }),
+ ...(record?.durationMs !== undefined ? { durationMs: record.durationMs } : startedMs !== undefined ? { durationMs: Math.max(0, (state === 'running' ? input.nowMs : lastEnd(agents, startedMs)) - startedMs) } : {}),
+ ...(input.dir !== undefined && { dir: input.dir }),
+ hasRecord: record !== null,
+ }
+}
+
+const lastEnd = (agents: readonly WfAgent[], fallback: number): number => agents.reduce((latest, agent) => (agent.startedMs !== undefined && agent.elapsedMs !== undefined ? Math.max(latest, agent.startedMs + agent.elapsedMs) : latest), fallback)
+
+function tally(agents: readonly WfAgent[]): Record<AgentState, number> {
+ const counts: Record<AgentState, number> = { running: 0, done: 0, failed: 0, stale: 0, idle: 0, queued: 0 }
+
+ for (const agent of agents) counts[agent.state] += 1
+
+ return counts
+}
+
+/** Declared phases first, in the script's order; a phase an agent names that the script did not declare follows. */
+export function groupPhases(agents: readonly WfAgent[], declared: readonly { title: string; detail?: string }[]): WfPhase[] {
+ const titles = [...declared.map(phase => phase.title)]
+
+ for (const agent of agents) if (!titles.includes(agent.phase)) titles.push(agent.phase)
+
+ return titles.map(title => {
+ const members = agents.filter(agent => agent.phase === title)
+ const detail = declared.find(phase => phase.title === title)?.detail
+
+ return { title, agents: members, done: members.filter(agent => agent.state === 'done').length, total: members.length, running: members.filter(agent => agent.state === 'running').length, failed: members.filter(agent => agent.state === 'failed').length, ...(detail !== undefined && { detail }) }
+ })
+}
+
+/** The phase the run is in: the first with an agent running, else the first not finished; null when every phase is done. */
+export function currentPhase(phases: readonly WfPhase[]): number | null {
+ const running = phases.findIndex(phase => phase.running > 0)
+
+ if (running >= 0) return running
+
+ const open = phases.findIndex(phase => phase.done < phase.total)
+
+ return open >= 0 ? open : null
+}
+
+const RUFLO_STATE = (status: string): AgentState => (/error|fail/i.test(status) ? 'failed' : /busy|active|running/i.test(status) ? 'running' : /stop|terminat|offline/i.test(status) ? 'done' : 'idle')
+
+/**
+ * The ruflo swarm as one more run: its phases are the agent types (that is the only grouping the store has), a stopped agent
+ * counts as done, an idle one as ready. ruflo records no model, tokens or worktree per agent, so those stay n/a.
+ */
+export function swarmRun(swarm: SwarmInfo | null, agents: readonly AgentRecord[], nowMs: number): WfRun | null {
+ if (swarm === null && agents.length === 0) return null
+
+ const labels = agentLabels(agents)
+ const rows: WfAgent[] = agents.map(agent => ({
+ id: agent.id,
+ label: labels.get(agent.id) ?? agent.type,
+ phase: agent.type,
+ state: RUFLO_STATE(agent.status),
+ hasWorktree: false,
+ ...(agent.createdAtMs !== undefined && { startedMs: agent.createdAtMs, elapsedMs: Math.max(0, nowMs - agent.createdAtMs) }),
+ ruflo: agent,
+ }))
+ const counts = tally(rows)
+
+ return {
+ id: swarm?.id ?? 'ruflo-swarm',
+ name: `ruflo swarm${swarm === null ? '' : ` · ${swarm.topology}`}`,
+ kind: 'ruflo-swarm',
+ state: counts.running > 0 ? 'active' : counts.failed > 0 ? 'failed' : 'finished',
+ phases: groupPhases(rows, []),
+ running: counts.running,
+ done: counts.done,
+ failed: counts.failed,
+ idle: counts.idle,
+ total: rows.length,
+ totalTokens: null,
+ isTokensPartial: false,
+ hasRecord: false,
+ }
+}
+
+/** 145.4k · 1.2M · 812 */
+export function fmtTokens(tokens: number | undefined, isPartial = false): string {
+ if (tokens === undefined) return 'n/a'
+
+ const text = tokens >= 1_000_000 ? `${(tokens / 1_000_000).toFixed(1)}M` : tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens)
+
+ return `${isPartial ? '≥' : ''}${text}`
+}
+
+/** 15s · 3m12s · 1h05m */
+export function fmtElapsed(ms: number | undefined): string {
+ if (ms === undefined) return 'n/a'
+
+ const s = Math.round(ms / 1000)
+
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
+}
+
+/** `claude-sonnet-5-5` → `Sonnet 5.5`; an unknown id is shown as it is. */
+export function modelName(model: string | undefined): string {
+ const match = model === undefined ? null : /^claude-(opus|sonnet|haiku)-(\d+)(?:-(\d+))?/.exec(model)
+
+ return model === undefined ? 'n/a' : match === null ? model : `${(match[1] as string).replace(/^./, c => c.toUpperCase())} ${match[2]}${match[3] !== undefined && match[3].length <= 2 ? `.${match[3]}` : ''}`
+}
+
+export { shortId }
diff --git a/plugins/ruflo-console/hooks/views/workflows.ts b/plugins/ruflo-console/hooks/views/workflows.ts
new file mode 100644
index 0000000000..79eca0de59
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/workflows.ts
@@ -0,0 +1,172 @@
+import type { RenderElement } from 'claude-code'
+
+import type { ActionSpec } from '../actions'
+import { fmtElapsed, fmtTokens, modelName, currentPhase, shortId, type AgentState, type WfAgent, type WfPhase, type WfRun } from '../data/workflows'
+import { pick, type WfUi } from '../data/workflows-nav'
+import { spawnAgent, stopAgent } from '../ops'
+import { button, clip, col, kv, row, rule, text, THEME, type Ctx } from './common'
+
+/** What the workflows view asks of the controller: a confirm-gated ruflo verb, or to name a transcript's path. */
+export type WorkflowsHooks = { ask: (spec: ActionSpec) => void; show: (path: string) => void }
+
+/** The runs as the integrator's reader returned them (`readWorkflowRuns`), with the swarm folded in by `allRuns`. */
+export type WorkflowsModel = { runs: readonly WfRun[]; root: string | null; capBytes: number; skipped: number; more: number }
+
+const SPIN = ['◐', '◓', '◑', '◒'] as const
+
+const MARK = (state: AgentState, nowMs: number): string => (state === 'done' ? '✔' : state === 'failed' ? '✖' : state === 'running' ? (SPIN[Math.floor(nowMs / 250) % 4] as string) : state === 'stale' ? '◌' : state === 'idle' ? '●' : '○')
+const COLOR = (state: AgentState): string | undefined => (state === 'done' ? THEME.ok : state === 'failed' ? THEME.bad : state === 'running' ? THEME.warn : state === 'idle' ? THEME.info : undefined)
+
+function phaseMark(phase: WfPhase, nowMs: number): { mark: string; color: string | undefined } {
+ if (phase.failed > 0) return { mark: '✖', color: THEME.bad }
+ if (phase.running > 0) return { mark: SPIN[Math.floor(nowMs / 250) % 4] as string, color: THEME.warn }
+ if (phase.total > 0 && phase.done === phase.total) return { mark: '✔', color: THEME.ok }
+
+ return { mark: '○', color: undefined }
+}
+
+const mb = (bytes: number): string => `${(bytes / 1_000_000).toFixed(1)} MB`
+
+/** The run header: its name and state, then agents running, done and failed, and the tokens the agents' records add up to. */
+function header(ctx: Ctx, run: WfRun, runs: readonly WfRun[], at: number): RenderElement[] {
+ const tone = run.state === 'failed' ? THEME.bad : run.running > 0 || run.state === 'active' ? THEME.warn : run.state === 'completed' ? THEME.ok : undefined
+ const counts = run.kind === 'ruflo-swarm' ? `${run.running} busy · ${run.idle} idle · ${run.done} stopped · ${run.failed} failed` : `${run.running} running · ${run.done} done · ${run.failed} failed`
+ const tokens = run.totalTokens === null ? 'tokens n/a' : `${fmtTokens(run.totalTokens, run.isTokensPartial)} tok`
+ const span = run.durationMs === undefined ? '' : ` · ${fmtElapsed(run.durationMs)}`
+ const tabs = runs.length > 1 ? runs.map((entry, i) => `${i === at ? '▸' : ' '}${i + 1} ${clip(entry.name, 18)}`).join(' ') : ''
+
+ return [
+ row(ctx, [ctx.kit.Text({ bold: true, children: `${clip(run.name, Math.max(8, ctx.columns - 24))} ` }), ctx.kit.Text({ ...(tone !== undefined && { color: tone }), children: run.state })]),
+ text(ctx, `${run.total} agents · ${counts} · ${tokens}${span}`, { dimColor: true }),
+ ...(tabs === '' ? [] : [text(ctx, `${tabs} [ ] switch run`, { dimColor: true })]),
+ ]
+}
+
+/** Left cell: `❯ ✔ Build 4/4`, the cursor row bold, the run's current phase marked ❯. */
+function phaseCell(ctx: Ctx, phase: WfPhase, index: number, flags: { isHere: boolean; isCurrent: boolean; width: number }): RenderElement {
+ const { mark, color } = phaseMark(phase, ctx.nowMs)
+ const count = `${phase.done}/${phase.total}`
+ const title = clip(`${index + 1} ${phase.title}`, Math.max(4, flags.width - count.length - 6))
+
+ return row(ctx, [
+ ctx.kit.Text({ ...(flags.isHere && { bold: true }), children: `${flags.isHere ? '▸' : ' '}${flags.isCurrent ? '❯' : ' '}` }),
+ ctx.kit.Text({ ...(color !== undefined && { color }), children: `${mark} ` }),
+ ctx.kit.Text({ ...(flags.isHere && { bold: true }), children: `${title.padEnd(flags.width - count.length - 6)} ` }),
+ ctx.kit.Text({ dimColor: true, children: count }),
+ ])
+}
+
+/** Right cell: status mark, label, model, worktree badge, tokens, elapsed. A narrow screen drops the model, then the badge. */
+function agentCell(ctx: Ctx, agent: WfAgent, isHere: boolean, width: number): RenderElement {
+ const tail = `${fmtTokens(agent.tokens, agent.isTokensPartial)} tok`.padStart(10) + fmtElapsed(agent.elapsedMs).padStart(7)
+ const model = agent.ruflo === undefined ? modelName(agent.model).padEnd(11) : ''
+ const badge = agent.hasWorktree ? 'worktree '.padEnd(10) : agent.ruflo === undefined ? ' '.repeat(10) : ''
+ const fixed = 3 + tail.length + (width >= 62 ? model.length : 0) + (width >= 74 ? badge.length : 0)
+ const label = clip(agent.label, Math.max(6, width - fixed - 1))
+
+ return row(ctx, [
+ ctx.kit.Text({ ...(COLOR(agent.state) !== undefined && { color: COLOR(agent.state) as string }), children: `${isHere ? '▸' : ' '}${MARK(agent.state, ctx.nowMs)} ` }),
+ ctx.kit.Text({ wrap: 'truncate-end', ...(isHere && { bold: true }), children: `${label.padEnd(Math.max(6, width - fixed))}` }),
+ ...(width >= 62 && model !== '' ? [ctx.kit.Text({ dimColor: true, children: model })] : []),
+ ...(width >= 74 && badge !== '' ? [ctx.kit.Text({ color: THEME.info, children: badge })] : []),
+ ctx.kit.Text({ dimColor: true, children: tail }),
+ ])
+}
+
+/** Everything about one agent that the two columns have no room for, and the verbs that apply to it. */
+function inspect(ctx: Ctx, run: WfRun, agent: WfAgent, hooks: WorkflowsHooks): RenderElement[] {
+ const rows: RenderElement[] = [rule(ctx, 'Inspect', agent.label)]
+
+ rows.push(kv(ctx, 'agent', `${agent.id} · phase ${agent.phase} · ${agent.state}`))
+
+ if (agent.ruflo !== undefined) {
+ const a = agent.ruflo
+
+ rows.push(kv(ctx, 'ruflo agent', `${a.type}${a.name !== undefined ? ` · ${a.name}` : ''} · ${a.status}`))
+ rows.push(kv(ctx, 'health / tasks', `${a.health === undefined ? 'n/a' : `${Math.round(a.health * 100)}%`} · ${a.taskCount ?? 'n/a'} tasks`))
+ rows.push(kv(ctx, 'model / tokens', 'n/a (ruflo records neither per agent)'))
+ rows.push(
+ row(ctx, [
+ button(ctx, 'wf-stop', 'Stop agent', () => { const spec = stopAgent(a); if (spec !== null) hooks.ask(spec) }, { hotkey: 'x' }),
+ button(ctx, 'wf-spawn', `Spawn another ${a.type}`, () => { const spec = spawnAgent(a.type, ctx.nowMs); if (spec !== null) hooks.ask(spec) }),
+ ]),
+ )
+
+ return rows
+ }
+
+ rows.push(kv(ctx, 'model', agent.model === undefined ? 'n/a' : `${modelName(agent.model)} (${agent.model})`))
+ rows.push(kv(ctx, 'tokens', `${fmtTokens(agent.tokens, agent.isTokensPartial)} context tokens of its latest request${agent.isTokensPartial === true ? ' (tail of the transcript only: a floor)' : ''}`))
+ rows.push(kv(ctx, 'elapsed', `${fmtElapsed(agent.elapsedMs)}${agent.startedMs === undefined ? '' : ` · started ${new Date(agent.startedMs).toISOString().slice(11, 19)}Z`}`))
+ rows.push(kv(ctx, 'worktree', agent.hasWorktree ? (agent.worktreePath ?? 'yes') : 'none'))
+ if (agent.toolCalls !== undefined) rows.push(kv(ctx, 'tool calls', `${agent.toolCalls}${agent.lastTool === undefined ? '' : ` · last ${agent.lastTool}`}`))
+ if (agent.resultPreview !== undefined) rows.push(text(ctx, `result: ${agent.resultPreview}`, { dimColor: true }))
+
+ rows.push(kv(ctx, 'transcript', agent.transcriptPath === undefined ? 'n/a' : clip(agent.transcriptPath, Math.max(20, ctx.columns - 14))))
+ if (agent.transcriptPath !== undefined) {
+ const path = agent.transcriptPath
+
+ rows.push(row(ctx, [button(ctx, 'wf-open', 'Open transcript', () => hooks.show(path), { hotkey: 'o' })]))
+ }
+
+ rows.push(text(ctx, run.kind === 'workflow' ? 'The console cannot stop a Claude Code workflow: stop it from Claude Code (its Workflows panel, or TaskStop).' : '', { dimColor: true }))
+
+ return rows
+}
+
+/**
+ * Swarm and workflow management in one page, drawn after Claude Code's /workflows panel: phases down the left with
+ * done/total and a ❯ on the current one, that phase's agents on the right, the run header above. Reads only; the one write
+ * is the ruflo agents' stop and spawn, each behind the confirm card.
+ */
+export function workflowsView(ctx: Ctx, model: WorkflowsModel | null, ui: WfUi, hooks: WorkflowsHooks): RenderElement {
+ const rows: RenderElement[] = [rule(ctx, 'Workflows', model === null ? '' : `${model.runs.length} runs · j/k move · h/l column · Enter inspect`)]
+
+ if (model === null) return col(ctx, [...rows, text(ctx, 'reading workflow runs…', { dimColor: true })], 'workflows')
+
+ const here = pick(ui, model.runs)
+
+ if (here.run === null) {
+ rows.push(text(ctx, model.root === null ? 'No Claude Code config directory is known here, so no workflow runs can be read.' : `No workflow runs for this project under ${clip(model.root, Math.max(20, ctx.columns - 30))}, and no ruflo swarm yet.`, { color: THEME.warn }))
+ rows.push(text(ctx, 'Claude Code writes a run folder when a Workflow script starts; ruflo agents appear once a swarm exists.', { dimColor: true }))
+
+ return col(ctx, rows, 'workflows')
+ }
+
+ rows.push(...header(ctx, here.run, model.runs, here.ui.run))
+
+ const run = here.run
+ const wide = ctx.columns >= 56
+ const left = wide ? Math.min(26, Math.max(18, Math.floor(ctx.columns / 3))) : ctx.columns
+ const current = currentPhase(run.phases)
+ const right = Math.max(20, ctx.columns - left - 3)
+ const phase = here.phase
+
+ rows.push(rule(ctx, 'Phases', phase === null ? '' : `${phase.title}${phase.detail === undefined ? '' : ` · ${clip(phase.detail, 40)}`}`))
+
+ const phases = run.phases.map((entry, i) => phaseCell(ctx, entry, i, { isHere: i === here.ui.phase && here.ui.column === 'phases', isCurrent: i === current, width: left }))
+ const agents = (phase?.agents ?? []).map((entry, i) => agentCell(ctx, entry, i === here.ui.agent && here.ui.column === 'agents', right))
+
+ if (run.phases.length === 0) rows.push(text(ctx, 'This run has no agents yet.', { dimColor: true }))
+ else if (wide) {
+ for (let i = 0; i < Math.min(14, Math.max(phases.length, agents.length)); i += 1) {
+ rows.push(row(ctx, [phases[i] ?? text(ctx, ' '.repeat(left)), ctx.kit.Text({ dimColor: true, children: ' │ ' }), agents[i] ?? text(ctx, ' ')], `wf-${i}`))
+ }
+ } else {
+ rows.push(...phases, ...agents)
+ }
+
+ if (Math.max(phases.length, agents.length) > 14 && wide) rows.push(text(ctx, `+${Math.max(phases.length, agents.length) - 14} more (j/k walks all of them)`, { dimColor: true }))
+ if (phase !== null && phase.agents.length === 0) rows.push(text(ctx, 'No agent has started in this phase yet.', { dimColor: true }))
+
+ if (here.ui.isInspecting && here.agent !== null) rows.push(...inspect(ctx, run, here.agent, hooks))
+
+ if (run.kind === 'workflow') {
+ rows.push(text(ctx, run.hasRecord ? 'Figures are from the run record Claude Code wrote when it finished.' : `Figures are derived from the journal and transcripts (read up to ${mb(model.capBytes)} each${model.skipped > 0 ? `; ${model.skipped} larger left unread, their tokens n/a` : ''}); ≥ marks a floor.`, { dimColor: true }))
+ }
+
+ if (model.more > 0) rows.push(text(ctx, `+${model.more} older runs not shown`, { dimColor: true }))
+ if (wide && !here.ui.isInspecting) rows.push(text(ctx, `${shortId(run.id)} · Enter inspects the agent · [ ] switches run`, { dimColor: true }))
+
+ return col(ctx, rows, 'workflows')
+}
diff --git a/plugins/ruflo-console/tests/fixtures/workflows.ts b/plugins/ruflo-console/tests/fixtures/workflows.ts
new file mode 100644
index 0000000000..4e0ecb96d4
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/workflows.ts
@@ -0,0 +1,55 @@
+/**
+ * Workflow run files with the SHAPE of a real Claude Code run (journal, agent meta, transcript, run record, script) and
+ * invented content. Timestamps are fixed so elapsed and staleness are exact.
+ */
+export const T0 = Date.parse('2026-10-06T01:30:00.000Z')
+const iso = (offsetS: number): string => new Date(T0 + offsetS * 1000).toISOString()
+
+export const started = (agentId: string, label: string, phase: string): string => JSON.stringify({ type: 'started', key: `v2:${agentId}`, agentId, label, phase })
+export const result = (agentId: string, value: unknown): string => JSON.stringify({ type: 'result', key: `v2:${agentId}`, agentId, result: value })
+
+export const journal = (...lines: string[]): string => [JSON.stringify({ type: 'launched' }), ...lines].join('\n') + '\n'
+
+export const meta = (description: string, phase: string, extra: Record<string, unknown> = {}): string => JSON.stringify({ agentType: 'workflow-subagent', description, workflowPhase: phase, spawnDepth: 1, requestShape: 'foreground', requestNonInteractive: false, ...extra })
+
+type Turn = { at: number; id: string; model?: string; input: number; write: number; read: number; output: number; tool?: string }
+
+/** Assistant lines the way streaming writes them: one message id appears on several lines. */
+export const transcript = (turns: readonly Turn[], opts: { userAt?: number } = {}): string => {
+ const lines = [JSON.stringify({ type: 'user', timestamp: iso(opts.userAt ?? 0), message: { role: 'user', content: 'task' } })]
+
+ for (const t of turns) {
+ const base = { type: 'assistant', timestamp: iso(t.at), message: { id: t.id, model: t.model ?? 'claude-sonnet-5-5', role: 'assistant', content: t.tool === undefined ? [{ type: 'text', text: 'ok' }] : [{ type: 'tool_use', id: `tu-${t.id}`, name: t.tool }], usage: { input_tokens: t.input, cache_creation_input_tokens: t.write, cache_read_input_tokens: t.read, output_tokens: t.output } } }
+
+ lines.push(JSON.stringify({ ...base, message: { ...base.message, usage: { ...base.message.usage, output_tokens: 3 } } }), JSON.stringify(base))
+ }
+
+ return lines.join('\n') + '\n'
+}
+
+export const record = (over: Record<string, unknown> = {}): string =>
+ JSON.stringify({
+ runId: 'wf_rec',
+ status: 'completed',
+ workflowName: 'demo-run',
+ startTime: T0,
+ durationMs: 90_000,
+ totalTokens: 400_000,
+ defaultModel: 'claude-opus-5-5',
+ phases: [{ title: 'Build', detail: 'one writer per feature' }, { title: 'Review' }],
+ workflowProgress: [
+ { type: 'workflow_phase', index: 1, title: 'Build' },
+ { type: 'workflow_agent', label: 'build:a', phaseTitle: 'Build', agentId: 'ra1', model: 'claude-sonnet-5-5', state: 'done', startedAt: T0, tokens: 181_212, toolCalls: 20, durationMs: 60_000, lastToolName: 'Bash' },
+ { type: 'workflow_agent', label: 'build:b', phaseTitle: 'Build', agentId: 'ra2', state: 'failed', startedAt: T0, tokens: 1_200, durationMs: 5_000 },
+ { type: 'workflow_agent', label: 'review:a', phaseTitle: 'Review', agentId: 'ra3', state: 'done', startedAt: T0 + 60_000, tokens: 90_000, durationMs: 30_000 },
+ ],
+ ...over,
+ })
+
+export const SCRIPT = `export const meta = {
+ name: 'demo-run',
+ description: 'x',
+ phases: [{ title: 'Build', detail: 'one writer per feature' }, { title: 'Tune' }, { title: 'Review', detail: 'adversarial' }],
+}
+const COMMON = 'phases: [{ title: "Not This" }]'
+`
diff --git a/plugins/ruflo-console/tests/workflows.spec.ts b/plugins/ruflo-console/tests/workflows.spec.ts
new file mode 100644
index 0000000000..366c03695b
--- /dev/null
+++ b/plugins/ruflo-console/tests/workflows.spec.ts
@@ -0,0 +1,368 @@
+/**
+ * The workflows view's data, keys and drawing under vitest (ADR-458): journals, metas and transcripts with real shapes and
+ * invented content, the reader against an in-memory disk, and the page through a recording kit.
+ * npx vitest run plugins/ruflo-console/tests/workflows.spec.ts
+ */
+import { describe, expect, it } from 'vitest'
+
+import { newState } from '../hooks/state'
+import type { ReadCache } from '../hooks/data/files'
+import { allRuns, newWfUi, pick, startOn, walk } from '../hooks/data/workflows-nav'
+import { readWorkflowRuns, slugOf, TRANSCRIPT_CAP, type WorkflowFs } from '../hooks/data/workflows-read'
+import { buildRun, currentPhase, fmtElapsed, fmtTokens, jsonLines, modelName, parseAgentMeta, parseJournal, parseRunRecord, parseScriptMeta, parseTranscript, STALE_MS, swarmRun, type RunInput } from '../hooks/data/workflows'
+import type { Ctx, Kit } from '../hooks/views/common'
+import { workflowsView } from '../hooks/views/workflows'
+import { journal, meta, record, result, SCRIPT, started, T0, transcript } from './fixtures/workflows'
+
+const NOW = T0 + 100_000
+
+type El = { kind: string; props: Record<string, unknown> }
+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 }) } as unknown as Kit
+
+function walkEls(node: unknown, out: El[] = []): El[] {
+ if (Array.isArray(node)) node.forEach(child => walkEls(child, out))
+ else if (typeof node === 'object' && node !== null) {
+ out.push(node as El)
+ walkEls((node as El).props?.children, out)
+ }
+
+ return out
+}
+
+const lines = (tree: unknown): string[] => {
+ const rows: string[] = []
+ const visit = (node: unknown): void => {
+ const el = node as El
+
+ if (el.kind === 'Box' && el.props.flexDirection === 'row') rows.push(walkEls(el.props.children).filter(n => n.kind === 'Text' && typeof n.props.children === 'string').map(n => n.props.children as string).join(''))
+ else if (el.kind === 'Box') (Array.isArray(el.props.children) ? el.props.children : [el.props.children]).forEach(visit)
+ else if (el.kind === 'Text' && typeof el.props.children === 'string') rows.push(el.props.children)
+ }
+
+ visit(tree)
+
+ return rows
+}
+
+const ctxOf = (columns: number): Ctx => ({ kit, state: newState({}), nowMs: NOW, columns, pictures: new Map(), act: {} as never })
+
+function liveInput(over: Partial<RunInput> = {}): RunInput {
+ return {
+ id: 'wf_live',
+ journal: journal(started('a1', 'build:memmap', 'Build'), started('a2', 'build:recall', 'Build'), result('a2', 'finished the recall view'), started('a3', 'tune:memmap', 'Tune')),
+ agents: new Map([
+ ['a1', { meta: meta('build:memmap', 'Build', { spawnedWithWorktree: true, worktreePath: '/w/a1' }), transcript: transcript([{ at: 5, id: 'm1', input: 2, write: 100_000, read: 20_000, output: 100, tool: 'Bash' }, { at: 40, id: 'm2', input: 2, write: 500, read: 125_000, output: 50 }]), isTail: false, path: '/d/agent-a1.jsonl' }],
+ ['a2', { meta: meta('build:recall', 'Build'), transcript: transcript([{ at: 3, id: 'n1', input: 1, write: 10, read: 10, output: 5 }, { at: 30, id: 'n2', input: 1, write: 10, read: 20, output: 9 }]), isTail: false, path: '/d/agent-a2.jsonl' }],
+ ]),
+ record: null,
+ script: SCRIPT,
+ nowMs: NOW,
+ ...over,
+ }
+}
+
+describe('parsers', () => {
+ it('journal: keeps launch order, merges results, ignores unknown events and a half-written line', () => {
+ const text = journal(started('a1', 'x', 'Build'), JSON.stringify({ type: 'progress', agentId: 'a1' }), result('a1', { branch: 'b' }), '{"type":"started","agentId":"a9","lab')
+ const parsed = parseJournal(text)
+
+ expect(parsed.isLaunched).toBe(true)
+ expect(parsed.agents).toEqual([{ agentId: 'a1', label: 'x', phase: 'Build', hasResult: true, resultPreview: 'structured result (1 fields)' }])
+ expect(parseJournal(null)).toEqual({ isLaunched: false, agents: [] })
+ })
+
+ it('meta: worktree flag and phase; garbage is an empty fact', () => {
+ expect(parseAgentMeta(meta('d', 'Build', { spawnedWithWorktree: true, worktreePath: '/w' }))).toMatchObject({ hasWorktree: true, worktreePath: '/w', phase: 'Build', description: 'd' })
+ expect(parseAgentMeta('not json')).toEqual({ hasWorktree: false })
+ expect(parseAgentMeta(null)).toEqual({ hasWorktree: false })
+ })
+
+ it('transcript: counts a streamed message once, takes the latest request, first and last time, model, tools', () => {
+ const facts = parseTranscript(transcript([{ at: 5, id: 'm1', input: 2, write: 100, read: 10, output: 8, tool: 'Bash' }, { at: 40, id: 'm2', input: 3, write: 5, read: 200, output: 7, model: 'claude-opus-5-5' }]))
+
+ expect(facts).toMatchObject({ tokens: 3 + 5 + 200 + 7, model: 'claude-opus-5-5', firstMs: T0, lastMs: T0 + 40_000, toolCalls: 2, lastTool: 'Bash', messages: 2 })
+ })
+
+ it('transcript tail: the cut first line is dropped, nothing throws', () => {
+ const full = transcript([{ at: 5, id: 'm1', input: 1, write: 1, read: 1, output: 1 }, { at: 9, id: 'm2', input: 2, write: 2, read: 2, output: 2 }])
+ const cut = full.slice(40)
+
+ expect(parseTranscript(cut, true).tokens).toBe(8)
+ expect(parseTranscript('', false)).toEqual({ toolCalls: 0, messages: 0 })
+ expect(jsonLines('{"a":1}\n{"b"')).toEqual([{ a: 1 }])
+ })
+
+ it('run record and script: phases, per-agent figures; the script is read as text, only its meta block', () => {
+ const rec = parseRunRecord(record())
+
+ expect(rec?.agents.map(a => [a.agentId, a.state, a.tokens])).toEqual([['ra1', 'done', 181_212], ['ra2', 'failed', 1200], ['ra3', 'done', 90_000]])
+ expect(rec?.phases[0]).toEqual({ title: 'Build', detail: 'one writer per feature' })
+ expect(parseRunRecord('{broken')).toBeNull()
+ expect(parseScriptMeta(SCRIPT)).toEqual({ name: 'demo-run', phases: [{ title: 'Build', detail: 'one writer per feature' }, { title: 'Tune' }, { title: 'Review', detail: 'adversarial' }] })
+ expect(parseScriptMeta(null)).toEqual({ phases: [] })
+ })
+
+ it('formats', () => {
+ expect(fmtTokens(145_400)).toBe('145.4k')
+ expect(fmtTokens(1_250_000)).toBe('1.3M')
+ expect(fmtTokens(812)).toBe('812')
+ expect(fmtTokens(undefined)).toBe('n/a')
+ expect(fmtTokens(5000, true)).toBe('≥5.0k')
+ expect(fmtElapsed(15_000)).toBe('15s')
+ expect(fmtElapsed(192_000)).toBe('3m12s')
+ expect(fmtElapsed(3_900_000)).toBe('1h05m')
+ expect(modelName('claude-sonnet-5-5')).toBe('Sonnet 5.5')
+ expect(modelName('claude-opus-5')).toBe('Opus 5')
+ expect(modelName('gpt-x')).toBe('gpt-x')
+ })
+})
+
+describe('buildRun', () => {
+ it('a live run: states from journal, tokens/time from transcripts, phases from the script, worktree badge from meta', () => {
+ const run = buildRun(liveInput())
+ const byLabel = Object.fromEntries(run.phases.flatMap(p => p.agents).map(a => [a.label, a]))
+
+ expect(run.phases.map(p => [p.title, p.done, p.total])).toEqual([['Build', 1, 2], ['Tune', 0, 1], ['Review', 0, 0]])
+ expect(byLabel['build:memmap']).toMatchObject({ state: 'running', hasWorktree: true, worktreePath: '/w/a1', model: 'claude-sonnet-5-5', tokens: 2 + 500 + 125_000 + 50, elapsedMs: 100_000 })
+ expect(byLabel['build:recall']).toMatchObject({ state: 'done', elapsedMs: 30_000, resultPreview: 'finished the recall view' })
+ expect(byLabel['tune:memmap']).toMatchObject({ state: 'running' })
+ expect(byLabel['tune:memmap']?.tokens).toBeUndefined()
+ expect(run).toMatchObject({ state: 'running', running: 2, done: 1, failed: 0, total: 3, hasRecord: false, isTokensPartial: true })
+ expect(run.totalTokens).toBe(125_552 + 40)
+ expect(currentPhase(run.phases)).toBe(0)
+ })
+
+ it('an agent with no result and no recent sign of life is stale, not running', () => {
+ const run = buildRun(liveInput({ nowMs: T0 + 40_000 + STALE_MS + 1, lastActivityMs: T0 + 40_000 }))
+
+ expect(run.phases[0]?.agents.find(a => a.label === 'build:memmap')?.state).toBe('stale')
+ expect(run.state).toBe('stalled')
+ })
+
+ it('a finished run: the record wins over any transcript, status and totals come from it', () => {
+ const run = buildRun({ id: 'wf_rec', journal: null, agents: new Map(), record: record(), script: null, nowMs: NOW })
+
+ expect(run).toMatchObject({ name: 'demo-run', state: 'completed', hasRecord: true, totalTokens: 400_000, durationMs: 90_000, running: 0, done: 2, failed: 1, total: 3 })
+ expect(run.phases.map(p => [p.title, p.done, p.failed, p.total])).toEqual([['Build', 1, 1, 2], ['Review', 1, 0, 1]])
+ expect(run.phases[0]?.agents[1]?.model).toBe('claude-opus-5-5')
+ expect(currentPhase(run.phases)).toBe(0)
+ })
+
+ it('a tail-read transcript makes tokens a floor and gives no start time', () => {
+ const run = buildRun(liveInput({ agents: new Map([['a1', { meta: null, transcript: transcript([{ at: 5, id: 'm1', input: 1, write: 1, read: 1, output: 1 }, { at: 9, id: 'm2', input: 1, write: 1, read: 1, output: 1 }]), isTail: true, path: '/p' }]]), journal: journal(started('a1', 'big', 'Build')) }))
+ const agent = run.phases[0]?.agents[0]
+
+ expect(agent).toMatchObject({ isTokensPartial: true })
+ expect(agent?.startedMs).toBeUndefined()
+ expect(agent?.elapsedMs).toBeUndefined()
+ })
+
+ it('an empty or phase-less journal still builds', () => {
+ expect(buildRun({ id: 'x', journal: journal(), agents: new Map(), record: null, script: null, nowMs: NOW })).toMatchObject({ total: 0, phases: [], state: 'finished', totalTokens: null })
+ expect(buildRun({ id: 'x', journal: '{"type":"started","agentId":"z","label":"l"}\n', agents: new Map(), record: null, script: null, nowMs: NOW }).phases[0]?.title).toBe('—')
+ })
+})
+
+describe('ruflo swarm as a run', () => {
+ const agents = [
+ { id: 'agent-1-aaaaaa', type: 'coder', status: 'busy', createdAtMs: NOW - 20_000 },
+ { id: 'agent-2-bbbbbb', type: 'coder', status: 'idle' },
+ { id: 'agent-3-cccccc', type: 'tester', status: 'stopped' },
+ ]
+ const swarm = { id: 'swarm-1', topology: 'hierarchical', status: 'running', agentIds: [] }
+
+ it('groups by agent type, never invents tokens or model', () => {
+ const run = swarmRun(swarm, agents, NOW)
+
+ expect(run).toMatchObject({ kind: 'ruflo-swarm', state: 'active', running: 1, idle: 1, done: 1, total: 3, totalTokens: null })
+ expect(run?.phases.map(p => [p.title, p.total])).toEqual([['coder', 2], ['tester', 1]])
+ expect(run?.phases[0]?.agents[0]).toMatchObject({ elapsedMs: 20_000, hasWorktree: false })
+ expect(run?.phases[0]?.agents[0]?.tokens).toBeUndefined()
+ expect(swarmRun(null, [], NOW)).toBeNull()
+ })
+
+ it('allRuns puts whatever is running first', () => {
+ const idle = buildRun({ id: 'wf_old', journal: null, agents: new Map(), record: record(), script: null, nowMs: NOW })
+
+ expect(allRuns([idle], swarm, agents, NOW).map(r => r.kind)).toEqual(['ruflo-swarm', 'workflow'])
+ expect(allRuns([idle], null, [], NOW).map(r => r.id)).toEqual(['wf_old'])
+ })
+})
+
+describe('keys', () => {
+ const runs = [buildRun(liveInput())]
+
+ it('j/k move in the focused column, h/l switch, Enter inspects, indexes never leave the list', () => {
+ let ui = startOn(newWfUi(), runs[0] ?? null)
+
+ expect(ui).toMatchObject({ phase: 0, column: 'phases' })
+ ui = walk(ui, runs, 'j')
+ expect(ui.phase).toBe(1)
+ ui = walk(walk(walk(walk(ui, runs, 'j'), runs, 'j'), runs, 'j'), runs, 'j')
+ expect(ui.phase).toBe(2)
+ ui = walk(walk(ui, runs, 'k'), runs, 'k')
+ expect(pick(ui, runs).phase?.title).toBe('Build')
+ ui = walk(ui, runs, 'l')
+ expect(ui.column).toBe('agents')
+ ui = walk(walk(ui, runs, 'j'), runs, 'j')
+ expect(ui.agent).toBe(1)
+ ui = walk(ui, runs, 'enter')
+ expect(ui.isInspecting).toBe(true)
+ expect(pick(ui, runs).agent?.label).toBe('build:recall')
+ expect(walk(ui, runs, 'escape').isInspecting).toBe(false)
+ expect(walk(walk(ui, runs, 'enter'), runs, 'h').column).toBe('phases')
+ })
+
+ it('l on an empty phase stays; Enter with nothing under the cursor does nothing; [ ] clamp', () => {
+ let ui = { ...newWfUi(), phase: 2 }
+
+ expect(walk(ui, runs, 'l').column).toBe('phases')
+ expect(walk(ui, runs, 'enter').isInspecting).toBe(false)
+ ui = walk(ui, runs, ']')
+ expect(ui.run).toBe(0)
+ expect(pick(newWfUi(), []).run).toBeNull()
+ expect(walk(newWfUi(), [], 'j')).toEqual(newWfUi())
+ })
+
+ it('a shrunk list pulls the cursor back', () => {
+ expect(pick({ ...newWfUi(), run: 5, phase: 9, agent: 9 }, runs).ui).toMatchObject({ run: 0, phase: 2, agent: 0 })
+ })
+})
+
+describe('reader', () => {
+ const root = '/home/u/.claude/projects/-work-proj'
+ const session = '11111111-2222-3333-4444-555555555555'
+ const runDir = `${root}/${session}/subagents/workflows/wf_live`
+
+ const memoryFs = (files: Record<string, string>, sizes: Record<string, number> = {}, mtime = 1_000): WorkflowFs => {
+ const under = (dir: string) => [...new Set(Object.keys({ ...files, ...sizes }).filter(p => p.startsWith(`${dir}/`)).map(p => p.slice(dir.length + 1).split('/')[0] as string))]
+
+ return {
+ read: async path => files[path] ?? Promise.reject(new Error('ENOENT')),
+ stat: async path => (files[path] !== undefined ? { mtimeMs: mtime, size: sizes[path] ?? files[path].length, kind: 'file' } : 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: mtime, size: sizes[`${dir}/${name}`] ?? files[`${dir}/${name}`]?.length }))
+ },
+ }
+ }
+
+ const base = (): Record<string, string> => ({
+ [`${runDir}/journal.jsonl`]: journal(started('a1', 'build:x', 'Build')),
+ [`${runDir}/agent-a1.meta.json`]: meta('build:x', 'Build', { spawnedWithWorktree: true }),
+ [`${runDir}/agent-a1.jsonl`]: transcript([{ at: 5, id: 'm1', input: 1, write: 1, read: 1, output: 1 }]),
+ [`${root}/${session}/workflows/scripts/demo-wf_live.js`]: SCRIPT,
+ })
+
+ const read = (fs: WorkflowFs) => readWorkflowRuns(fs, new Map() as ReadCache, { configDir: '/home/u/.claude', cwd: '/work/proj', nowMs: T0 + 10_000 })
+
+ it('the slug is the folder name Claude Code uses', () => {
+ expect(slugOf('/home/ruvultra/projects/ruflo')).toBe('-home-ruvultra-projects-ruflo')
+ })
+
+ it('finds a live run, its script phases and its agent figures', async () => {
+ const found = await read(memoryFs(base()))
+
+ expect(found.root).toBe(root)
+ expect(found.runs).toHaveLength(1)
+ expect(found.runs[0]?.name).toBe('demo-run')
+ expect(found.runs[0]?.phases.map(p => p.title)).toEqual(['Build', 'Tune', 'Review'])
+ expect(found.runs[0]?.phases[0]?.agents[0]).toMatchObject({ state: 'running', hasWorktree: true, tokens: 4, transcriptPath: `${runDir}/agent-a1.jsonl` })
+ })
+
+ it('a finished run is not transcript-read: its record is enough', async () => {
+ const files = { ...base(), [`${root}/${session}/workflows/wf_live.json`]: record() }
+ const found = await read(memoryFs(files))
+
+ expect(found.runs[0]).toMatchObject({ hasRecord: true, state: 'completed', totalTokens: 400_000 })
+ expect(found.skipped).toEqual([])
+ })
+
+ it('an oversized transcript is tail-read where the host can, else left unread and counted', async () => {
+ const big = { [`${runDir}/agent-a1.jsonl`]: TRANSCRIPT_CAP + 1 }
+ const files = base()
+ const plain = await read(memoryFs(files, big))
+
+ expect(plain.skipped).toEqual([`${runDir}/agent-a1.jsonl`])
+ expect(plain.runs[0]?.phases[0]?.agents[0]?.tokens).toBeUndefined()
+
+ const tail = await read({ ...memoryFs(files, big), readTail: async () => `cut-off-line\n${files[`${runDir}/agent-a1.jsonl`]}` })
+
+ expect(tail.skipped).toEqual([])
+ expect(tail.runs[0]?.phases[0]?.agents[0]).toMatchObject({ tokens: 4, isTokensPartial: true })
+ })
+
+ it('no config directory, no project folder: an honest empty answer', async () => {
+ expect((await readWorkflowRuns(memoryFs({}), new Map() as ReadCache, { configDir: null, cwd: '/x', nowMs: 0 })).runs).toEqual([])
+ expect((await read(memoryFs({}))).runs).toEqual([])
+ })
+
+ it('limits the runs shown and says how many more exist', async () => {
+ const files: Record<string, string> = {}
+
+ for (let i = 0; i < 8; i += 1) files[`${root}/${session}/subagents/workflows/wf_r${i}/journal.jsonl`] = journal()
+
+ const found = await readWorkflowRuns(memoryFs(files), new Map() as ReadCache, { configDir: '/home/u/.claude', cwd: '/work/proj', nowMs: 0, maxRuns: 3 })
+
+ expect(found.runs).toHaveLength(3)
+ expect(found.more).toBe(5)
+ })
+})
+
+describe('view', () => {
+ const hooks = { ask: () => undefined, show: () => undefined }
+ const live = buildRun(liveInput())
+ const model = (runs = [live]) => ({ runs, root: '/r', capBytes: TRANSCRIPT_CAP, skipped: 0, more: 0 })
+
+ it('draws phases left with done/total and the current marker, agents right with mark, model, worktree, tokens, time', () => {
+ const out = lines(workflowsView(ctxOf(110), model(), startOn(newWfUi(), live), hooks))
+ const text = out.join('\n')
+
+ expect(text).toContain('demo-run')
+ expect(text).toContain('3 agents · 2 running · 1 done · 0 failed')
+ expect(out.find(l => l.includes('1 Build'))).toMatch(/❯.*1 Build\s+1\/2.*│.*build:memmap\s+Sonnet 5\.5\s+worktree\s+125\.6k tok\s+1m40s/)
+ expect(out.find(l => l.includes('2 Tune'))).toMatch(/2 Tune\s+0\/1/)
+ expect(text).toContain('derived from the journal and transcripts')
+ })
+
+ it('narrow screens drop the model and badge instead of overflowing', () => {
+ const out = lines(workflowsView(ctxOf(50), model(), startOn(newWfUi(), live), hooks))
+
+ expect(out.join('\n')).not.toContain('Sonnet 5.5')
+ expect(out.join('\n')).toContain('1 Build')
+ })
+
+ it('inspect shows the transcript path and open fires the hook; a workflow cannot be stopped from here', () => {
+ const shown: string[] = []
+ const ui = { ...startOn(newWfUi(), live), column: 'agents' as const, isInspecting: true }
+ const tree = workflowsView(ctxOf(110), model(), ui, { ask: () => undefined, show: path => shown.push(path) })
+ const buttons = walkEls(tree).filter(n => n.kind === 'Button')
+
+ expect(lines(tree).join('\n')).toContain('/d/agent-a1.jsonl')
+ expect(lines(tree).join('\n')).toContain('cannot stop a Claude Code workflow')
+ expect(buttons.map(b => b.props.label)).toEqual(['Open transcript'])
+ ;(buttons[0]?.props.onPress as () => void)()
+ expect(shown).toEqual(['/d/agent-a1.jsonl'])
+ })
+
+ it('a ruflo agent offers stop and spawn through the confirm hook with fixed argv', () => {
+ const swarm = swarmRun({ id: 's', topology: 'hierarchical', status: 'running', agentIds: [] }, [{ id: 'agent-9-zzzzzz', type: 'coder', status: 'busy' }], NOW) as NonNullable<ReturnType<typeof swarmRun>>
+ const asked: string[][] = []
+ const ui = { ...newWfUi(), column: 'agents' as const, isInspecting: true }
+ const tree = workflowsView(ctxOf(110), model([swarm]), ui, { ask: spec => asked.push([...spec.args]), show: () => undefined })
+ const buttons = walkEls(tree).filter(n => n.kind === 'Button')
+
+ expect(buttons.map(b => b.props.label)).toEqual(['Stop agent', 'Spawn another coder'])
+ buttons.forEach(b => (b.props.onPress as () => void)())
+ expect(asked[0]).toEqual(['agent', 'stop', 'agent-9-zzzzzz'])
+ expect(asked[1]?.slice(0, 4)).toEqual(['agent', 'spawn', '--type', 'coder'])
+ expect(lines(tree).join('\n')).toContain('n/a (ruflo records neither per agent)')
+ })
+
+ it('empty and loading states are honest', () => {
+ expect(lines(workflowsView(ctxOf(100), null, newWfUi(), hooks)).join('\n')).toContain('reading workflow runs')
+ expect(lines(workflowsView(ctxOf(100), { ...model([]), runs: [] }, newWfUi(), hooks)).join('\n')).toContain('No workflow runs for this project')
+ expect(lines(workflowsView(ctxOf(100), { ...model([]), runs: [], root: null }, newWfUi(), hooks)).join('\n')).toContain('No Claude Code config directory')
+ })
+})
diff --git a/v3/docs/adr/ADR-458-swarm-workflow-management-ui.md b/v3/docs/adr/ADR-458-swarm-workflow-management-ui.md
new file mode 100644
index 0000000000..9c38a7cf05
--- /dev/null
+++ b/v3/docs/adr/ADR-458-swarm-workflow-management-ui.md
@@ -0,0 +1,89 @@
+# ADR 458: Swarm and workflow management page (`workflows`)
+
+Status: Accepted
+
+Date: 2026-10-05
+
+Builds on: ADR-404 (ruflo as a mod), ADR-444 (Claude controls the console); related ADR-453 (confirm-gated verbs)
+
+## 1. Context
+
+The console has a Swarm page (ruflo's agents) and nothing for the other swarm a person runs most: Claude Code's own
+`Workflow` runs. Claude Code shows those in a `/workflows` panel (phases down the left with done/total and a marker on the
+current one, that phase's agents on the right with status, label, model, `worktree`, tokens, elapsed). That panel is only
+visible while the run is in the foreground. The console can show the same thing from the files Claude Code writes, next to
+the ruflo swarm, so one page manages both.
+
+Schemas were read from real runs (Claude Code 2.1.287), not assumed:
+
+| File | Shape |
+|---|---|
+| `<session>/subagents/workflows/<runId>/journal.jsonl` | `{type:'launched'}`, `{type:'started',key,agentId,label,phase}`, `{type:'result',key,agentId,result}` |
+| `.../agent-<id>.meta.json` | `description`, `workflowPhase`, `agentType`, and `spawnedWithWorktree` + `worktreePath` only for worktree agents |
+| `.../agent-<id>.jsonl` | transcript; every line has `timestamp`; `assistant` lines carry `message.{id,model,usage}`; one message id repeats across streamed lines |
+| `<session>/workflows/<runId>.json` | written when the run ends: `status`, `phases[]`, `durationMs`, `startTime`, `totalTokens`, `workflowProgress[]` (per agent: `state`, `model`, `tokens`, `durationMs`, `startedAt`, `toolCalls`) |
+| `<session>/workflows/scripts/<name>-<runId>.js` | the script; `meta.phases` names the phases (a live run has no `.json` yet) |
+
+## 2. Decision
+
+Add a read-only view `workflows`, built from pure parts:
+
+- `hooks/data/workflows.ts`: parsers (journal, meta, transcript, run record, script meta), `buildRun`, `swarmRun`, formatters.
+- `hooks/data/workflows-read.ts`: the only disk code. Finds the newest 6 runs of this project (`<configDir>/projects/<slug>/...`),
+ at most 60 agents each.
+- `hooks/data/workflows-nav.ts`: cursor state and the key reducer. `j/k` move in the focused column, `h/l` switch column,
+ `Enter` inspects, `Esc` closes, `[` `]` switch run.
+- `hooks/views/workflows.ts`: the page.
+
+Source precedence per agent: the run record where it exists (a finished run), else journal + meta + transcript. A run with a
+record never has its transcripts read. A started agent with no result and no activity for 15 minutes is shown as stale
+(`◌`), because a crashed run leaves the same files as a live one; it is not shown as running and not as failed. "Failed" is
+only ever what the run record says.
+
+The ruflo swarm is a second run in the same layout (`swarmRun`): phases are the agent types (the only grouping the store has),
+a stopped agent counts as done, an idle one as ready. ruflo records no model, tokens or worktree per agent, so those read n/a.
+
+Tokens: the run record's own figure where present, else the context tokens of the agent's latest request (input + cache
+read + cache write + output, each streamed message counted once). Measured against the record on a real run it is within
+about 1% (180,391 to 181,549 against 181,212), so it is a derivation, labelled as one in the page footer.
+
+Bounds: a transcript over `TRANSCRIPT_CAP` (3 MB; the engine refuses 4 MiB) is tail-read (`TAIL_BYTES`, 400 KB) where the host
+supplies `fs.readTail`, giving tokens as a floor (`>=`) and no start time; otherwise it is left unread and its tokens read
+n/a. The cap and the number of unread transcripts are printed in the page.
+
+Actions: ruflo agents get `Stop agent` and `Spawn another <type>`, which are `stopAgent` and `spawnAgent` from `ops.ts` (fixed
+argv) handed to the existing confirm card through `hooks.ask`. A workflow agent gets `Open transcript`, which names its path
+(`hooks.show`). The console cannot stop a Claude Code workflow and the page says so.
+
+No file in the console's existing registries is edited by this change; the wiring is in section 5.
+
+## 3. Consequences
+
+- One page for both swarms, from files already on disk; no new probe, no network, no secrets. A result is shown only as the
+ first 160 characters of the string the journal already holds (a structured result as a field count), in the inspect panel.
+- A live run's figures are derived and say so; a finished run's are Claude Code's own.
+- `stale` is a heuristic with a stated threshold, not a fact. The page never reports a failure it cannot read.
+- Reading cost: measured 72 ms for 6 real runs including one live run (this one), on the 2026-10-05 host. A finished run costs
+ its record plus up to 60 tiny meta files.
+
+## 4. Test and benchmark plan
+
+`plugins/ruflo-console/tests/workflows.spec.ts` (27 tests) with fixtures that copy the shape of a real run and none of its
+content: parsers (unknown events, a half-written line, a cut tail), streamed-message dedupe, live vs finished vs stale vs
+tail-read runs, the ruflo swarm run, key movement and clamping, the reader against an in-memory disk (oversize, tail,
+limits, empty), and the page through a recording kit (columns, narrow width, inspect, buttons and their argv, empty states).
+Benchmark: `readWorkflowRuns` over the real `~/.claude/projects/-home-ruvultra-projects-ruflo` tree (72 ms, 6 runs, 0 skipped).
+Re-run it if `MAX_RUNS` or the transcript cap changes.
+
+## 5. Integrator wiring
+
+- `state.ts`: `ViewId` `'workflows'`; `VIEWS` entry `{ id: 'workflows', key: <free key>, label: 'Workflows', short: 'Wfl', icon: '🧬', blurb: 'swarm and workflow runs: phases, agents, models, tokens, time', rows: 30 }`; menu: SWARM group, observe, next to `swarm`.
+- State: `workflows: { model: WorkflowsModel | null; ui: WfUi }` (`newWfUi()`), the model refreshed only while the view is open.
+- Refresh: `readWorkflowRuns(fs, cache, { configDir, cwd, nowMs })`, then `{ runs: allRuns(found.runs, snap.swarm, snap.agents, now), root, capBytes, skipped: found.skipped.length, more }`; pass `fs.readTail` if the host has one.
+- Keys while the view is in front: `j k h l [ ]` and Enter/Esc map to `walk(ui, runs, key)`; after a run switch or a first open call `startOn`.
+- Render: `workflowsView(ctx, model, ui, { ask: spec => <existing confirm path>, show: path => toast/result row })`.
+
+## 6. Rollback
+
+Delete the four files and remove the registry entries; nothing else reads them. The page is read-only apart from the two
+ruflo verbs, which are the ones the Swarm page already offers.