🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(console): Workflows replay, compare, export and saved views (ADR-461)
ruvef867aa200cb
diff --git a/plugins/ruflo-console/hooks/data/wf-compare.ts b/plugins/ruflo-console/hooks/data/wf-compare.tsnew file mode 100644index 0000000000..d04420c542--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-compare.ts@@ -0,0 +1,124 @@+/**+ * Two runs of the same workflow, side by side (ADR-461). Pure: agents are matched by phase and label (the Nth agent of a+ * label within a phase pairs with the Nth in the other run), and each pair is marked+ * = the same ~ changed: a different final state or model, tokens off by TOKEN_DELTA or more, or time off by TIME_DELTA or more+ * + only in B - only in A+ * A figure either run did not record is n/a and never counts as a change: the comparison says what the files say.+ */+import type { WfAgent, WfRun } from './workflows'++/** Tokens and time are "changed" past these relative differences; a smaller move is run-to-run noise. */+export const TOKEN_DELTA = 0.1+export const TIME_DELTA = 0.25++export type Mark = '=' | '~' | '+' | '-'++/** `diff` is B minus A and `ratio` is diff over A; both are absent where either side is unknown (or A is zero for the ratio). */+export type Delta = { a?: number; b?: number; diff?: number; ratio?: number }++export type AgentDiff = {+ key: string+ label: string+ phase: string+ mark: Mark+ a?: WfAgent+ b?: WfAgent+ tokens: Delta+ time: Delta+ /** `done → failed`, or null when the state is the same (or one side is absent). */+ stateChange: string | null+ modelChange: string | null+ /** Whether both agents reported a result and the two differ; null where either has none. */+ resultsDiffer: boolean | null+}++export type Comparison = {+ ok: true+ a: WfRun+ b: WfRun+ rows: AgentDiff[]+ totals: { agents: Delta; done: Delta; failed: Delta; tokens: Delta; time: Delta }+ counts: { same: number; changed: number; added: number; removed: number }+ /** Tokens are a floor on either side, or a run was derived from transcripts rather than a record. */+ notes: string[]+}++export type NotComparable = { ok: false; why: string }++const delta = (a: number | undefined, b: number | undefined): Delta => {+ const both = a !== undefined && b !== undefined++ return { ...(a !== undefined && { a }), ...(b !== undefined && { b }), ...(both && { diff: b - a }), ...(both && a !== 0 && { ratio: (b - a) / a }) }+}++/** Runs other than `run` that carry its workflow name, newest first as the list holds them: what it can be compared with. */+export const otherRunsOf = (run: WfRun, runs: readonly WfRun[]): WfRun[] => (run.kind !== 'workflow' ? [] : runs.filter(entry => entry.kind === 'workflow' && entry.id !== run.id && entry.name === run.name))++const keyed = (run: WfRun): Map<string, WfAgent> => {+ const seen = new Map<string, number>()+ const out = new Map<string, WfAgent>()++ for (const phase of run.phases) {+ for (const agent of phase.agents) {+ const base = `${agent.phase}\u0000${agent.label}`+ const nth = (seen.get(base) ?? 0) + 1++ seen.set(base, nth)+ out.set(`${base}\u0000${nth}`, agent)+ }+ }++ return out+}++const isOff = (d: Delta, limit: number): boolean => d.ratio !== undefined && Math.abs(d.ratio) >= limit++function pair(key: string, a: WfAgent | undefined, b: WfAgent | undefined): AgentDiff {+ const tokens = delta(a?.tokens, b?.tokens)+ const time = delta(a?.elapsedMs, b?.elapsedMs)+ const stateChange = a !== undefined && b !== undefined && a.state !== b.state ? `${a.state} → ${b.state}` : null+ const modelChange = a !== undefined && b !== undefined && a.model !== undefined && b.model !== undefined && a.model !== b.model ? `${a.model} → ${b.model}` : null+ const resultsDiffer = a?.resultPreview !== undefined && b?.resultPreview !== undefined ? a.resultPreview !== b.resultPreview : null+ const mark: Mark = a === undefined ? '+' : b === undefined ? '-' : stateChange !== null || modelChange !== null || isOff(tokens, TOKEN_DELTA) || isOff(time, TIME_DELTA) ? '~' : '='+ const at = (a ?? b) as WfAgent++ return { key, label: at.label, phase: at.phase, mark, ...(a !== undefined && { a }), ...(b !== undefined && { b }), tokens, time, stateChange, modelChange, resultsDiffer }+}++export function compareRuns(a: WfRun, b: WfRun): Comparison | NotComparable {+ if (a.kind !== 'workflow' || b.kind !== 'workflow') return { ok: false, why: 'only Claude Code workflow runs compare: the ruflo swarm is one live roster, not a run' }+ if (a.id === b.id) return { ok: false, why: 'that is the same run' }+ if (a.name !== b.name) return { ok: false, why: `different workflows: "${a.name}" and "${b.name}"` }++ const left = keyed(a)+ const right = keyed(b)+ const rows = [...left.entries()].map(([key, agent]) => pair(key, agent, right.get(key)))++ for (const [key, agent] of right) if (!left.has(key)) rows.push(pair(key, undefined, agent))++ const count = (mark: Mark): number => rows.filter(row => row.mark === mark).length+ const notes: string[] = []++ if (a.isTokensPartial || b.isTokensPartial) notes.push('tokens marked ≥ are a floor (a long transcript was only read from its end), so a token difference may be larger than it looks')+ if (!a.hasRecord || !b.hasRecord) notes.push(`${!a.hasRecord && !b.hasRecord ? 'both runs are' : `run ${a.hasRecord ? 'B' : 'A'} is`} derived from journal and transcripts, not a finished run record: figures can still move`)+ if (rows.some(row => row.resultsDiffer === true)) notes.push('result text differs between the two (it always can; only the agents\' own words are compared, not their meaning)')++ return {+ ok: true,+ a,+ b,+ rows,+ totals: { agents: delta(a.total, b.total), done: delta(a.done, b.done), failed: delta(a.failed, b.failed), tokens: delta(a.totalTokens ?? undefined, b.totalTokens ?? undefined), time: delta(a.durationMs, b.durationMs) },+ counts: { same: count('='), changed: count('~'), added: count('+'), removed: count('-') },+ notes,+ }+}++/** `+12%` · `-3%` · `n/a`; a ratio over 999% reads `>+999%`. */+export function fmtRatio(d: Delta): string {+ if (d.ratio === undefined) return d.diff === 0 ? '0%' : 'n/a'++ const percent = Math.round(d.ratio * 100)++ return Math.abs(percent) > 999 ? `${percent > 0 ? '>+' : '<-'}999%` : `${percent > 0 ? '+' : ''}${percent}%`+}diff --git a/plugins/ruflo-console/hooks/data/wf-export.ts b/plugins/ruflo-console/hooks/data/wf-export.tsnew file mode 100644index 0000000000..88ac47077a--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-export.ts@@ -0,0 +1,99 @@+/**+ * A run summary as markdown (ADR-461): phases, agents, results and, where a figure exists, tokens, time and cost. Pure.+ * Every string that came from a file passes `cleanText` (control characters out, credential shapes masked) and has table+ * characters escaped, so a label cannot break a row and a token in a result cannot reach the summary. A figure nobody+ * recorded reads n/a: the console holds no per-run cost, so cost is shown only when the caller hands one over with its source.+ */+import type { ActionSpec } from '../actions'+import { newFileArgv } from './wf-file'+import { cleanText } from './wf-clean'+import { fmtElapsed, fmtTokens, modelName, type WfAgent, type WfRun } from './workflows'++/** A summary over this is cut at a line break and says so at the end: a run with thousands of agents does not make a megabyte file. */+export const MAX_EXPORT_BYTES = 200_000++export type ExportCost = { usd: number | null; /** Where the figure comes from, in words ("cost ledger, Claude Code logs"). */ source: string }++/** Table cell text: cleaned, one line, `|` escaped. */+const cell = (value: string | undefined, max = 80): string => (value === undefined || value === '' ? 'n/a' : cleanText(value).replace(/\s+/g, ' ').replace(/[|\\`]/g, ch => `\\${ch}`).slice(0, max))+const line = (value: string): string => cleanText(value).replace(/\s+/g, ' ')+/** UTF-8 size of a text, from the platform's own encoder. */+const BYTES = (text: string): number => new TextEncoder().encode(text).length+const when = (ms: number | undefined): string => (ms === undefined || !Number.isFinite(ms) ? 'n/a' : new Date(ms).toISOString())++function agentRows(agents: readonly WfAgent[]): string[] {+ return [+ '| Agent | State | Model | Tokens | Time | Tools |',+ '| --- | --- | --- | --- | --- | --- |',+ ...agents.map(agent => `| ${cell(agent.label)} | ${agent.state} | ${agent.model === undefined ? 'n/a' : cell(modelName(agent.model), 30)} | ${fmtTokens(agent.tokens, agent.isTokensPartial)} | ${fmtElapsed(agent.elapsedMs)} | ${agent.toolCalls ?? 'n/a'} |`),+ ]+}++export function runMarkdown(run: WfRun, options: { nowMs: number; cost?: ExportCost | null }): string {+ const cost = options.cost+ const out: string[] = [+ `# Workflow run: ${line(run.name)}`,+ '',+ `Exported ${when(options.nowMs)} from the ruflo console. Read-only: nothing here changes the run.`,+ '',+ '| | |',+ '| --- | --- |',+ `| Run | ${cell(run.id)} |`,+ `| State | ${run.state} |`,+ `| Started | ${when(run.startedMs)} |`,+ `| Duration | ${fmtElapsed(run.durationMs)} |`,+ `| Agents | ${run.total} (${run.done} done, ${run.failed} failed, ${run.running} running) |`,+ `| Tokens | ${run.totalTokens === null ? 'n/a' : `${fmtTokens(run.totalTokens, run.isTokensPartial)} (the sum of each agent's context at its latest request)`} |`,+ `| Cost | ${cost === undefined || cost === null || cost.usd === null ? 'n/a (no cost source for this run)' : `$${cost.usd.toFixed(2)} (${cell(cost.source, 60)})`} |`,+ '',+ ]++ for (const [index, phase] of run.phases.entries()) {+ out.push(`## ${index + 1}. ${line(phase.title)}`, '', `${phase.done}/${phase.total} done${phase.failed > 0 ? `, ${phase.failed} failed` : ''}${phase.detail === undefined ? '' : ` · ${line(phase.detail)}`}`, '')+ out.push(...(phase.agents.length === 0 ? ['No agent started in this phase.'] : agentRows(phase.agents)), '')+ }++ const results = run.phases.flatMap(phase => phase.agents).filter(agent => agent.resultPreview !== undefined)++ if (results.length > 0) {+ out.push('## Results', '')++ for (const agent of results) out.push(`- **${cell(agent.label, 60)}** (${agent.state}): ${line(agent.resultPreview ?? '')}`)++ out.push('', 'Results are the first 160 characters of what each agent reported, with anything shaped like a key or token masked.', '')+ }++ out.push('## Provenance', '', run.hasRecord ? 'Figures are from the run record Claude Code wrote when the run finished.' : 'Figures are derived from the journal and transcripts of a run that has no finished record; they can still move.', '')++ return capped(out.join('\n'))+}++function capped(text: string): string {+ if (BYTES(text) <= MAX_EXPORT_BYTES) return `${text.trimEnd()}\n`++ let head = text.slice(0, MAX_EXPORT_BYTES - 200)++ // The cap is in bytes: shrink until multi-byte text fits too.+ while (BYTES(head) > MAX_EXPORT_BYTES - 200) head = head.slice(0, Math.floor(head.length * 0.9))++ return `${head.slice(0, Math.max(0, head.lastIndexOf('\n'))).trimEnd()}\n\n> Cut here: this summary is capped at ${MAX_EXPORT_BYTES / 1000} kB. The run itself is unchanged.\n`+}++/** The confirm-gated write of a summary: the card shows the path and size, the argv is fixed and the text goes in on stdin. */+export function exportSpec(path: string, markdown: string, label: string, hasDir: boolean): ActionSpec {+ return {+ label: `write run summary: ${label}`,+ args: [],+ argv: newFileArgv(path, hasDir),+ stdin: markdown,+ expect: `a new file at ${path}`,+ declared: 'write',+ shows: `write ${path} (${BYTES(markdown)} bytes; never overwrites)`,+ note: 'writes one new markdown file inside the project or the scratchpad; a file that already exists makes it fail instead of replacing it (a missing folder is made with GNU install, which macOS lacks)',+ timeoutMs: 10_000,+ verifyLocal: async host => (await host.fs.stat(path).catch(() => undefined)) !== undefined,+ }+}++/** A file name for a run's summary: its name and id with anything unsafe turned into a dash. */+export const exportName = (run: WfRun): string => `${`${run.name}-${run.id}`.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 90) || 'run'}.md`diff --git a/plugins/ruflo-console/hooks/data/wf-file.ts b/plugins/ruflo-console/hooks/data/wf-file.tsnew file mode 100644index 0000000000..c5dcfc5512--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-file.ts@@ -0,0 +1,88 @@+/**+ * The two files the Workflows page may write (ADR-461): a run summary the person asks for (markdown), and the page's own+ * saved views. The host's `fs` is read-only, so a write is a fixed-argv command with the content on stdin and no shell: `dd+ * of=<path>` where the folder exists (`conv=excl` makes it fail rather than replace a file), else GNU `install -D`, which makes the+ * folders first. The path is one argv element, never part of a script.+ *+ * A path is accepted only if, after normalising, it sits under an allowed root (the project, or the scratchpad where one is known)+ * with no `..`, no link on the way down to it and, for a summary, no file already there to overwrite.+ */+import type { ReaderFs } from './files'++export type Roots = { cwd: string; /** The session scratchpad, when the host tells the console where it is. */ scratch?: string | null }+export type PathCheck = { ok: true; path: string } | { ok: false; why: string }++/** Where a run summary goes by default, under the project's console folder. */+export const EXPORT_DIR = '.claude-flow/console/exports'++const NAME = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,99}\.md$/+const MAX_PATH = 300++const trimRoot = (root: string): string => root.replace(/\/+$/, '')++/** The normalised absolute path of a markdown file the person named, or why it cannot be written. Lexical only: see `checkNoLinks` for the disk half. */+export function resolveExportPath(input: string, roots: Roots): PathCheck {+ const raw = input.trim()++ if (raw === '') return { ok: false, why: 'give a file name ending in .md' }+ if (raw.length > MAX_PATH) return { ok: false, why: `a path over ${MAX_PATH} characters is refused` }+ // eslint-disable-next-line no-control-regex+ if (/[\u0000-\u001f\u007f-\u009f\\]/.test(raw)) return { ok: false, why: 'a path with control characters or a backslash is refused' }+ if (raw.startsWith('~')) return { ok: false, why: 'write the path out: ~ is not expanded here' }+ if (raw.split('/').includes('..')) return { ok: false, why: 'a path with .. is refused: name the file inside the project or the scratchpad' }++ const base = trimRoot(roots.cwd)++ if (base === '' || !base.startsWith('/')) return { ok: false, why: 'no project folder is known, so a relative path cannot be placed' }++ const absolute = raw.startsWith('/') ? raw : `${base}/${raw}`+ const parts = absolute.split('/').filter(part => part !== '' && part !== '.')+ const path = `/${parts.join('/')}`+ const name = parts[parts.length - 1] ?? ''+ const inside = [roots.cwd, roots.scratch ?? ''].map(trimRoot).filter(root => root.startsWith('/') && root.length > 1).find(root => path.startsWith(`${root}/`))++ if (!NAME.test(name)) return { ok: false, why: 'the file name must be letters, digits, dots, dashes, underscores or spaces, and end in .md' }+ if (inside === undefined) return { ok: false, why: `outside the project${roots.scratch === undefined || roots.scratch === null ? '' : ' and the scratchpad'}: only paths under ${trimRoot(roots.cwd)}${roots.scratch === undefined || roots.scratch === null ? '' : ` or ${trimRoot(roots.scratch)}`} are written` }++ return { ok: true, path }+}++/**+ * The disk half of the check: no folder on the way from the root down to the file is a link (a link could lead out of the root), and+ * no file is already there. A path that does not exist yet is fine; `stat` refusing is "missing".+ */+export async function checkNoLinks(fs: Pick<ReaderFs, 'stat'>, path: string, roots: Roots, options: { allowExisting?: boolean } = {}): Promise<PathCheck> {+ const root = [roots.cwd, roots.scratch ?? ''].map(trimRoot).find(entry => entry !== '' && path.startsWith(`${entry}/`))++ if (root === undefined) return { ok: false, why: 'outside the allowed folders' }++ const parts = path.slice(root.length + 1).split('/')+ let at = root++ for (const [index, part] of parts.entries()) {+ at = `${at}/${part}`++ const stat = await fs.stat(at).catch(() => undefined)++ if (stat === undefined) return { ok: true, path }+ if (stat.isLink === true) return { ok: false, why: `${at.slice(root.length)} is a link: it could lead outside the folder, so it is not written through` }+ if (index < parts.length - 1 && stat.kind !== undefined && stat.kind !== 'dir' && stat.kind !== 'directory') return { ok: false, why: `${at.slice(root.length)} is not a folder` }+ if (index === parts.length - 1 && options.allowExisting !== true) return { ok: false, why: `${at.slice(root.length)} already exists: the console does not overwrite a file; pick another name` }+ }++ return { ok: true, path }+}++/** A new file, content on stdin: `dd` with `conv=excl` where the folder is there (it fails if the file appeared meanwhile), `install -D` (GNU: makes the folders; not on macOS) where it is not. */+export const newFileArgv = (path: string, hasDir: boolean): readonly string[] => (hasDir ? ['dd', `of=${path}`, 'conv=excl', 'status=none'] : INSTALL(path))++/** The page's own state file, content on stdin: replaced in place where the folder is there, created (with its folders) where it is not. A torn write is a corrupt file, which the reader tolerates. */+export const replaceFileArgv = (path: string, hasDir: boolean): readonly string[] => (hasDir ? ['dd', `of=${path}`, 'status=none'] : INSTALL(path))++const INSTALL = (path: string): readonly string[] => ['install', '-D', '-m', '0644', '/dev/stdin', '--', path]++/** The folder a path sits in. */+export const dirOf = (path: string): string => path.slice(0, Math.max(1, path.lastIndexOf('/')))++/** Removes the one state file; nothing else. */+export const removeFileArgv = (path: string): readonly string[] => ['rm', '-f', '--', path]diff --git a/plugins/ruflo-console/hooks/data/wf-replay.ts b/plugins/ruflo-console/hooks/data/wf-replay.tsnew file mode 100644index 0000000000..e70e7e7738--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-replay.ts@@ -0,0 +1,199 @@+/**+ * Replay of a finished workflow run (ADR-461). Pure: it takes the `WfRun` the page already holds and re-derives the board at+ * every step, so a scrub can move back and forth and always lands on the same board.+ *+ * What a step is. The only moments a run records are the ones its agents carry: when each started (`startedMs`) and, for an+ * agent that finished or failed, how long it took (`elapsedMs`). Those two make the events, `start` and `end`, in time order+ * (an end before a start at the same instant, so a hand-off between phases never shows both running). The journal itself has+ * no timestamps, so nothing finer than that exists and none is invented:+ * - an agent without a start time, or one that ended but has no span, is not placed on the timeline (`untimed`) and is left+ * off the replayed board, with the count said by the view;+ * - tokens are known only at the end (a run record stores the final figure; a transcript's running total is not kept), so a+ * running agent shows n/a tokens rather than a guessed share;+ * - the last step is the real board, agent for agent.+ */+import { groupPhases, type WfAgent, type WfRun } from './workflows'++export type ReplayEvent = { atMs: number; agentId: string; kind: 'start' | 'end'; phase: string; label: string }++export type Timeline = {+ events: ReplayEvent[]+ /** First and last event time; both 0 for an empty timeline. */+ t0: number+ t1: number+ /** Agents left off the replay for want of a start time, or of a span for a finished one. */+ untimed: string[]+ /** Why there is nothing to replay, or null. */+ why: string | null+}++/** Speeds a replay plays at, as multiples of the run's own clock: a 20 minute run at 64x takes about 19 seconds. */+export const SPEEDS: readonly number[] = [1, 4, 16, 64, 256]++const ENDED = (agent: WfAgent): boolean => agent.state === 'done' || agent.state === 'failed'++export function buildTimeline(run: WfRun): Timeline {+ const empty = (why: string): Timeline => ({ events: [], t0: 0, t1: 0, untimed: [], why })++ if (run.kind !== 'workflow') return empty('the ruflo swarm has no run history to replay: ruflo records no start or end per agent')++ const events: ReplayEvent[] = []+ const untimed: string[] = []++ for (const phase of run.phases) {+ for (const agent of phase.agents) {+ if (agent.startedMs === undefined || (ENDED(agent) && agent.elapsedMs === undefined)) {+ untimed.push(agent.id)+ continue+ }++ events.push({ atMs: agent.startedMs, agentId: agent.id, kind: 'start', phase: agent.phase, label: agent.label })+ if (ENDED(agent) && agent.elapsedMs !== undefined) events.push({ atMs: agent.startedMs + agent.elapsedMs, agentId: agent.id, kind: 'end', phase: agent.phase, label: agent.label })+ }+ }++ if (events.length === 0) return { ...empty(run.total === 0 ? 'this run has no agents yet' : 'no agent of this run has a start time, so there is no order to replay'), untimed }++ events.sort((a, b) => a.atMs - b.atMs || (a.kind === b.kind ? 0 : a.kind === 'end' ? -1 : 1) || (a.agentId < b.agentId ? -1 : a.agentId > b.agentId ? 1 : 0))++ return { events, t0: (events[0] as ReplayEvent).atMs, t1: (events[events.length - 1] as ReplayEvent).atMs, untimed, why: null }+}++/** Time since the first event at the moment a step has been reached (step 0 is before any event). */+export const offsetOf = (tl: Timeline, step: number): number => (step <= 0 || tl.events.length === 0 ? 0 : (tl.events[Math.min(step, tl.events.length) - 1] as ReplayEvent).atMs - tl.t0)++/** Steps at which an agent of a phase not seen before starts: where "next phase" and "previous phase" land. */+export function phaseSteps(tl: Timeline): number[] {+ const seen = new Set<string>()+ const out: number[] = []++ for (const [index, event] of tl.events.entries()) {+ if (event.kind === 'start' && !seen.has(event.phase)) {+ seen.add(event.phase)+ out.push(index + 1)+ }+ }++ return out+}++const BARE = (agent: WfAgent): WfAgent => {+ const { tokens: _t, isTokensPartial: _p, elapsedMs: _e, startedMs: _s, resultPreview: _r, toolCalls: _c, lastTool: _l, ...rest } = agent++ return rest+}++/** The run as it stood after `step` events: the same shape the page draws, so the same board draws it. */+export function boardAt(run: WfRun, tl: Timeline, step: number): WfRun {+ const at = Math.max(0, Math.min(tl.events.length, Math.floor(step)))+ const started = new Set<string>()+ const ended = new Set<string>()++ for (const event of tl.events.slice(0, at)) (event.kind === 'start' ? started : ended).add(event.agentId)++ const skip = new Set(tl.untimed)+ const nowMs = tl.t0 + offsetOf(tl, at)+ const isLast = at === tl.events.length+ const agents: WfAgent[] = run.phases.flatMap(phase => phase.agents).filter(agent => !skip.has(agent.id)).map(agent => {+ if (isLast || ended.has(agent.id)) return agent+ if (!started.has(agent.id)) return { ...BARE(agent), state: 'queued' as const }++ return { ...BARE(agent), state: 'running' as const, ...(agent.startedMs !== undefined && { startedMs: agent.startedMs, elapsedMs: Math.max(0, nowMs - agent.startedMs) }) }+ })+ const phases = groupPhases(agents, run.phases.map(phase => ({ title: phase.title, ...(phase.detail !== undefined && { detail: phase.detail }) })))+ const count = (state: WfAgent['state']): number => agents.filter(agent => agent.state === state).length+ const known = agents.filter(agent => agent.tokens !== undefined)+ const isReal = isLast && skip.size === 0+ const unsure = agents.some(agent => agent.tokens === undefined || agent.isTokensPartial === true) || skip.size > 0++ return {+ ...run,+ phases,+ running: count('running'),+ done: count('done'),+ failed: count('failed'),+ idle: 0,+ total: agents.length,+ state: isLast ? run.state : 'running',+ // The last step is the real run, whose own total counts agents whose files are gone; every earlier step can only add up what its agents show.+ totalTokens: isReal ? run.totalTokens : known.length === 0 ? null : known.reduce((sum, agent) => sum + (agent.tokens ?? 0), 0),+ isTokensPartial: isReal ? run.isTokensPartial : unsure,+ durationMs: isLast && run.durationMs !== undefined ? run.durationMs : Math.max(0, nowMs - tl.t0),+ }+}++/** Where a replay is. While `playFromMs` is set the step follows the wall clock from `baseMs` at `speed`; otherwise `step` is exact. */+export type ReplayUi = { step: number; speed: number; /** Wall-clock moment play began, or null when paused. */ playFromMs: number | null; /** Time since the first event when play began. */ baseMs: number }++export const newReplay = (): ReplayUi => ({ step: 0, speed: 16, playFromMs: null, baseMs: 0 })++/** The step the replay is at right now: a playing one counts the events its clock has passed, and stops at the end. */+export function stepNow(ui: ReplayUi, tl: Timeline, nowMs: number): number {+ const n = tl.events.length++ if (ui.playFromMs === null) return Math.max(0, Math.min(n, ui.step))++ const clock = ui.baseMs + Math.max(0, nowMs - ui.playFromMs) * ui.speed+ let step = Math.max(0, Math.min(n, ui.step))++ while (step < n && offsetOf(tl, step + 1) <= clock) step += 1++ return step+}++export const isPlaying = (ui: ReplayUi, tl: Timeline, nowMs: number): boolean => ui.playFromMs !== null && stepNow(ui, tl, nowMs) < tl.events.length++export type ReplayCommand = 'next' | 'prev' | 'first' | 'last' | 'next-phase' | 'prev-phase' | 'play' | 'faster' | 'slower'++/** One command applied to a replay. A manual move pauses it; `play` toggles (and restarts from the top when it is at the end). */+export function stepReplay(ui: ReplayUi, tl: Timeline, command: ReplayCommand, nowMs: number): ReplayUi {+ const n = tl.events.length+ const here = stepNow(ui, tl, nowMs)+ const settled: ReplayUi = { ...ui, step: here, playFromMs: null, baseMs: offsetOf(tl, here) }+ const go = (step: number): ReplayUi => ({ ...settled, step: Math.max(0, Math.min(n, step)), baseMs: offsetOf(tl, step) })+ const starts = phaseSteps(tl)+ const speedAt = SPEEDS.indexOf(ui.speed)++ switch (command) {+ case 'next':+ return go(here + 1)+ case 'prev':+ return go(here - 1)+ case 'first':+ return go(0)+ case 'last':+ return go(n)+ case 'next-phase':+ return go(starts.find(step => step > here) ?? n)+ case 'prev-phase':+ return go([...starts].reverse().find(step => step < here) ?? 0)+ case 'play':+ if (ui.playFromMs !== null && here < n) return settled++ return n === 0 ? settled : { ...settled, step: here >= n ? 0 : here, baseMs: offsetOf(tl, here >= n ? 0 : here), playFromMs: nowMs }+ case 'faster':+ case 'slower': {+ const speed = SPEEDS[Math.max(0, Math.min(SPEEDS.length - 1, (speedAt < 0 ? 2 : speedAt) + (command === 'faster' ? 1 : -1)))] as number++ // A playing replay keeps its place and carries on at the new speed.+ return ui.playFromMs === null ? { ...ui, speed } : { ...settled, speed, playFromMs: nowMs }+ }+ }+}++/** Jumps to a place along the run: `fraction` 0 is the first event's moment, 1 the last. Lands on the last step at or before it. */+export function jumpReplay(ui: ReplayUi, tl: Timeline, fraction: number): ReplayUi {+ const clock = (tl.t1 - tl.t0) * Math.max(0, Math.min(1, Number.isFinite(fraction) ? fraction : 0))+ let step = 0++ while (step < tl.events.length && offsetOf(tl, step + 1) <= clock) step += 1++ return { ...ui, step, playFromMs: null, baseMs: offsetOf(tl, step) }+}++/** What happened at a step, in a line: `+0:42 wire started (Wire)`; step 0 says nothing has happened yet. */+export function describeStep(tl: Timeline, step: number): string {+ const event = tl.events[step - 1]++ return event === undefined ? 'before the first agent started' : `${event.label} ${event.kind === 'start' ? 'started' : 'ended'} (${event.phase})`+}diff --git a/plugins/ruflo-console/hooks/data/wf-saved.ts b/plugins/ruflo-console/hooks/data/wf-saved.tsnew file mode 100644index 0000000000..0655bd9a49--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-saved.ts@@ -0,0 +1,156 @@+/**+ * What the Workflows page remembers across restarts (ADR-461): where the cursor was (by run, phase and agent NAME, not by index,+ * so a new run in the list does not move it), the filters and the search a feature set, and the runs the person pinned.+ * Lives in one small file, `.claude-flow/console/wf-views.json`, schema-versioned. Pure: `decodeSaved` never throws and never+ * trusts the file (a corrupt or hand-edited one comes back as defaults with the problem named, and a file from a NEWER version is+ * left alone: `isForeign`), every string is cleaned and masked on the way in and the way out, and every list is capped.+ */+import { cleanText } from './wf-clean'+import type { WfUi } from './workflows-nav'+import type { WfRun } from './workflows'++export const SAVED_VERSION = 1+export const SAVED_FILE = '.claude-flow/console/wf-views.json'+/** A saved file over this is not read (and the page says so): it holds a cursor, a few filters and 20 pins, so it never gets near. */+export const SAVED_MAX_BYTES = 64_000+export const MAX_PINS = 20+export const MAX_FILTERS = 8+const TEXT_MAX = 80++export type Drill = { runId?: string; runName?: string; phase?: string; agent?: string; column: 'phases' | 'agents'; isInspecting: boolean; tab: string }+export type Pin = { runId: string; name: string; pinnedAtMs: number }+export type Saved = { version: number; savedAtMs: number; drill: Drill | null; filters: Record<string, string>; search: string; pins: Pin[] }++export const emptySaved = (): Saved => ({ version: SAVED_VERSION, savedAtMs: 0, drill: null, filters: {}, search: '', pins: [] })++const RUN_ID = /^[A-Za-z0-9_-]{1,60}$/+const KEY = /^[a-z][a-z0-9-]{0,23}$/+const TAB = /^[a-z][a-z0-9-]{1,31}$/++const asRecord = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)+const word = (value: unknown, max = TEXT_MAX): string | undefined => {+ const clean = typeof value === 'string' ? cleanText(value).trim().slice(0, max) : ''++ return clean === '' ? undefined : clean+}++export type Decoded = { saved: Saved; /** Why the file was not used whole, or null. */ problem: string | null; /** A file from a newer console: read as defaults, never written over. */ isForeign: boolean }++export function decodeSaved(text: string | null): Decoded {+ if (text === null) return { saved: emptySaved(), problem: null, isForeign: false }++ let parsed: unknown++ try {+ parsed = JSON.parse(text)+ } catch {+ return { saved: emptySaved(), problem: 'the saved views file is not valid JSON, so it is ignored and will be replaced on the next change', isForeign: false }+ }++ const root = asRecord(parsed)++ if (root === null) return { saved: emptySaved(), problem: 'the saved views file is not an object, so it is ignored and will be replaced on the next change', isForeign: false }+ if (root.version !== SAVED_VERSION) return { saved: emptySaved(), problem: typeof root.version === 'number' && root.version > SAVED_VERSION ? `the saved views file is from a newer console (version ${root.version}): left alone, nothing is read from it or written to it` : 'the saved views file has an unknown version, so it is ignored and will be replaced on the next change', isForeign: typeof root.version === 'number' && root.version > SAVED_VERSION }++ const drillRaw = asRecord(root.drill)+ const runId = typeof drillRaw?.runId === 'string' && RUN_ID.test(drillRaw.runId) ? drillRaw.runId : undefined+ const runName = word(drillRaw?.runName)+ const phase = word(drillRaw?.phase)+ const agent = word(drillRaw?.agent)+ const tab = typeof drillRaw?.tab === 'string' && TAB.test(drillRaw.tab) ? drillRaw.tab : 'detail'+ const drill: Drill | null = drillRaw === null || (runId === undefined && runName === undefined) ? null : { column: drillRaw.column === 'agents' ? 'agents' : 'phases', isInspecting: drillRaw.isInspecting === true, tab, ...(runId !== undefined && { runId }), ...(runName !== undefined && { runName }), ...(phase !== undefined && { phase }), ...(agent !== undefined && { agent }) }+ const filters: Record<string, string> = {}++ for (const [key, value] of Object.entries(asRecord(root.filters) ?? {}).slice(0, MAX_FILTERS)) {+ const clean = word(value)++ if (KEY.test(key) && clean !== undefined) filters[key] = clean+ }++ const pins: Pin[] = []++ for (const entry of (Array.isArray(root.pins) ? root.pins : []).slice(0, MAX_PINS * 2)) {+ const pin = asRecord(entry)+ const id = typeof pin?.runId === 'string' && RUN_ID.test(pin.runId) ? pin.runId : undefined+ const name = word(pin?.name)++ if (id !== undefined && name !== undefined && !pins.some(held => held.runId === id) && pins.length < MAX_PINS) pins.push({ runId: id, name, pinnedAtMs: typeof pin?.pinnedAtMs === 'number' && Number.isFinite(pin.pinnedAtMs) && pin.pinnedAtMs >= 0 ? pin.pinnedAtMs : 0 })+ }++ return { saved: { version: SAVED_VERSION, savedAtMs: typeof root.savedAtMs === 'number' && Number.isFinite(root.savedAtMs) ? root.savedAtMs : 0, drill, filters, search: word(root.search) ?? '', pins }, problem: null, isForeign: false }+}++/** The file's text: what `decodeSaved` would accept, built from the (already clean) held value, passed through the decoder's own rules once more. */+export function encodeSaved(saved: Saved, nowMs: number): string {+ const { saved: clean } = decodeSaved(JSON.stringify({ ...saved, version: SAVED_VERSION }))++ return `${JSON.stringify({ ...clean, savedAtMs: nowMs }, null, 1)}\n`+}++export const sameDrill = (a: Drill | null, b: Drill | null): boolean => JSON.stringify(a) === JSON.stringify(b)++/** Where the cursor is, by names. Null where there is no run to stand on. */+export function captureDrill(ui: WfUi, runs: readonly WfRun[], tab: string): Drill | null {+ const run = runs[Math.max(0, Math.min(runs.length - 1, ui.run))]++ if (run === undefined) return null++ const phase = run.phases[Math.max(0, Math.min(run.phases.length - 1, ui.phase))]+ const agent = phase?.agents[Math.max(0, Math.min(phase.agents.length - 1, ui.agent))]+ const id = RUN_ID.test(run.id) ? run.id : undefined+ const name = word(run.name)+ const title = word(phase?.title)+ const label = word(agent?.label)++ return { column: ui.column, isInspecting: ui.isInspecting && agent !== undefined, tab: TAB.test(tab) ? tab : 'detail', ...(id !== undefined && { runId: id }), ...(name !== undefined && { runName: name }), ...(title !== undefined && { phase: title }), ...(label !== undefined && { agent: label }) }+}++export type Restored = { ui: WfUi; tab: string; /** `exact` found the run by id; `name` the newest run of the same workflow; `gone` neither (the cursor is left where it is). */ found: 'exact' | 'name' | 'gone' }++/** The cursor a saved drill stands for in `runs` (phase and agent by title and label, falling back to the first), or null for nothing to restore. */+export function restoreDrill(drill: Drill | null, runs: readonly WfRun[], at: WfUi): Restored | null {+ if (drill === null) return null++ const byId = drill.runId === undefined ? -1 : runs.findIndex(run => run.id === drill.runId)+ const byName = byId >= 0 || drill.runName === undefined ? -1 : runs.findIndex(run => run.name === drill.runName)+ const index = byId >= 0 ? byId : byName++ if (index < 0) return { ui: at, tab: 'detail', found: 'gone' }++ const run = runs[index] as WfRun+ const phase = Math.max(0, drill.phase === undefined ? 0 : run.phases.findIndex(entry => entry.title === drill.phase))+ const agent = Math.max(0, drill.agent === undefined ? 0 : (run.phases[phase]?.agents.findIndex(entry => entry.label === drill.agent) ?? 0))+ const isInspecting = drill.isInspecting && (run.phases[phase]?.agents.length ?? 0) > 0++ return { ui: { run: index, phase, agent, column: drill.column === 'agents' && (run.phases[phase]?.agents.length ?? 0) > 0 ? 'agents' : 'phases', isInspecting }, tab: isInspecting ? drill.tab : 'detail', found: byId >= 0 ? 'exact' : 'name' }+}++export const isPinned = (saved: Saved, runId: string): boolean => saved.pins.some(pin => pin.runId === runId)++/** Pins the run, or unpins it when it is pinned; a full list refuses a new pin (the oldest is not silently dropped) and says so. */+export function togglePin(saved: Saved, run: WfRun, nowMs: number): { saved: Saved; said: string } {+ if (isPinned(saved, run.id)) return { saved: { ...saved, pins: saved.pins.filter(pin => pin.runId !== run.id) }, said: `unpinned ${word(run.name, 40) ?? run.id}` }+ if (!RUN_ID.test(run.id)) return { saved, said: 'this run has no id that can be saved' }+ if (saved.pins.length >= MAX_PINS) return { saved, said: `${MAX_PINS} runs are pinned already: unpin one first` }++ return { saved: { ...saved, pins: [...saved.pins, { runId: run.id, name: word(run.name) ?? run.id, pinnedAtMs: nowMs }] }, said: `pinned ${word(run.name, 40) ?? run.id}` }+}++/** Each pin with where its run now is in the list (null when the run is no longer among the runs read). */+export const pinsIn = (saved: Saved, runs: readonly WfRun[]): { pin: Pin; index: number | null; run: WfRun | null }[] => saved.pins.map(pin => {+ const index = runs.findIndex(run => run.id === pin.runId)++ return { pin, index: index < 0 ? null : index, run: index < 0 ? null : (runs[index] as WfRun) }+})++/** A filter set to a value, or removed with an empty one; keys and values are held to the file's own rules. */+export function setFilter(saved: Saved, key: string, value: string): Saved {+ if (!KEY.test(key)) return saved++ const { [key]: _gone, ...rest } = saved.filters+ const clean = word(value)++ return clean === undefined ? { ...saved, filters: rest } : Object.keys(rest).length >= MAX_FILTERS ? saved : { ...saved, filters: { ...rest, [key]: clean } }+}++export const setSearch = (saved: Saved, value: string): Saved => ({ ...saved, search: word(value) ?? '' })diff --git a/plugins/ruflo-console/hooks/views/wf-compare.ts b/plugins/ruflo-console/hooks/views/wf-compare.tsnew file mode 100644index 0000000000..9195acc7bb--- /dev/null+++ b/plugins/ruflo-console/hooks/views/wf-compare.ts@@ -0,0 +1,106 @@+/**+ * Compare on the Workflows page (ADR-461): a board slot that sets the picked run beside another run of the same workflow+ * name, agent by agent (data/wf-compare.ts). Registered by importing views/wf-replay.ts.+ */+import type { RenderElement } from 'claude-code'++import { compareRuns, fmtRatio, otherRunsOf, TIME_DELTA, TOKEN_DELTA, type AgentDiff, type Comparison, type Mark } from '../data/wf-compare'+import { fmtElapsed, fmtTokens, shortId, type WfAgent, type WfRun } from '../data/workflows'+import { button, clip, row, text, THEME, type Ctx } from './common'+import { fold, redraw } from './wf-fold'+import { registerSlot, type SlotEnv } from './wf-slots'++const against = new Map<string, string>()+const changedOnly = new Set<string>()+const ROWS_MAX = 20++/** For tests. */+export const resetCompare = (): void => (against.clear(), changedOnly.clear())++/** The run B for A: the one the person stepped to if it is still in the list, else the newest other run of the same workflow. */+export function partnerOf(run: WfRun, runs: readonly WfRun[]): WfRun | null {+ const others = otherRunsOf(run, runs)++ return others.find(other => other.id === against.get(run.id)) ?? others[0] ?? null+}++/** Steps to the next (or previous) other run of the same workflow; a test and the buttons share it. */+export function stepPartner(run: WfRun, runs: readonly WfRun[], by: 1 | -1): void {+ const others = otherRunsOf(run, runs)++ if (others.length === 0) return++ const at = Math.max(0, others.findIndex(other => other.id === partnerOf(run, runs)?.id))++ against.set(run.id, (others[(at + by + others.length) % others.length] as WfRun).id)+}++const MARK_COLOR: Record<Mark, string | undefined> = { '=': undefined, '~': THEME.warn, '+': THEME.ok, '-': THEME.bad }++const cellOf = (agent: WfAgent | undefined): string => (agent === undefined ? '—' : `${agent.state === 'done' ? '✔' : agent.state === 'failed' ? '✖' : agent.state === 'running' ? '◐' : '○'} ${fmtTokens(agent.tokens, agent.isTokensPartial)} ${fmtElapsed(agent.elapsedMs)}`)++function diffRow(ctx: Ctx, diff: AgentDiff): RenderElement {+ const label = clip(diff.label, Math.max(8, Math.min(28, Math.floor(ctx.columns / 3))))+ const change = [diff.stateChange, diff.modelChange, diff.tokens.ratio === undefined ? null : `tok ${fmtRatio(diff.tokens)}`, diff.time.ratio === undefined ? null : `time ${fmtRatio(diff.time)}`, diff.resultsDiffer === true ? 'result differs' : null].filter(entry => entry !== null).join(' · ')+ const color = MARK_COLOR[diff.mark]++ return text(ctx, ` ${diff.mark} ${label.padEnd(Math.max(8, Math.min(28, Math.floor(ctx.columns / 3))))} A ${cellOf(diff.a).padEnd(20)} B ${cellOf(diff.b).padEnd(20)} ${change}`, color === undefined ? {} : { color })+}++function totalsRows(ctx: Ctx, c: Comparison): RenderElement[] {+ const line = (name: string, a: string, b: string, ratio?: string): RenderElement => text(ctx, ` ${name.padEnd(9)} A ${a.padEnd(14)} B ${b.padEnd(14)}${ratio === undefined ? '' : ` ${ratio}`}`)++ return [+ line('state', c.a.state, c.b.state),+ line('agents', `${c.a.total} (${c.a.done} ok, ${c.a.failed} failed)`, `${c.b.total} (${c.b.done} ok, ${c.b.failed} failed)`),+ line('tokens', c.a.totalTokens === null ? 'n/a' : fmtTokens(c.a.totalTokens, c.a.isTokensPartial), c.b.totalTokens === null ? 'n/a' : fmtTokens(c.b.totalTokens, c.b.isTokensPartial), fmtRatio(c.totals.tokens)),+ line('time', fmtElapsed(c.a.durationMs), fmtElapsed(c.b.durationMs), fmtRatio(c.totals.time)),+ ]+}++export function compareBody(env: SlotEnv, run: WfRun): RenderElement[] {+ const { ctx, runs } = env+ const other = partnerOf(run, runs)++ if (other === null) return [text(ctx, ` No other run of "${clip(run.name, 40)}" has been read: a run of the same workflow name is needed to compare. Runs read: ${runs.filter(entry => entry.kind === 'workflow').length}.`, { dimColor: true })]++ const result = compareRuns(run, other)++ if (!result.ok) return [text(ctx, ` ${result.why}`, { color: THEME.warn })]++ const isOnly = changedOnly.has(run.id)+ const shown = result.rows.filter(entry => !isOnly || entry.mark !== '=')+ const total = otherRunsOf(run, runs).length+ const flip = (): void => {+ if (isOnly) changedOnly.delete(run.id)+ else changedOnly.add(run.id)+ redraw(ctx)+ }++ return [+ row(ctx, [text(ctx, ` A ${shortId(run.id)}`, { bold: true }), text(ctx, ' vs '), text(ctx, `B ${shortId(other.id)}`, { bold: true }), text(ctx, total > 1 ? ` (${total} other runs of this workflow)` : '', { dimColor: true })], 'wf-cmp-ids'),+ row(ctx, [...(total > 1 ? [button(ctx, 'wf-cmp-prev', '◂ other run', () => (stepPartner(run, runs, -1), redraw(ctx))), button(ctx, 'wf-cmp-next', 'other run ▸', () => (stepPartner(run, runs, 1), redraw(ctx)))] : []), button(ctx, 'wf-cmp-only', isOnly ? 'show all agents' : 'changed only', flip)], 'wf-cmp-controls'),+ ...totalsRows(ctx, result),+ text(ctx, ` ${result.counts.same} same · ${result.counts.changed} changed · ${result.counts.added} only in B (+) · ${result.counts.removed} only in A (-) ~ = tokens off by ${TOKEN_DELTA * 100}% or time by ${TIME_DELTA * 100}% or a state/model change`, { dimColor: true }),+ ...shown.slice(0, ROWS_MAX).map(entry => diffRow(ctx, entry)),+ ...(shown.length > ROWS_MAX ? [text(ctx, ` +${shown.length - ROWS_MAX} more agents not drawn`, { dimColor: true })] : shown.length === 0 ? [text(ctx, ' No agent differs by those thresholds.', { dimColor: true })] : []),+ ...result.notes.map(note => text(ctx, ` ${note}`, { dimColor: true })),+ ]+}++registerSlot({+ kind: 'board',+ id: 'compare',+ title: 'Compare runs',+ order: 50,+ render: env => {+ const run = env.run++ if (run === null) return []+ if (run.kind !== 'workflow') return [text(env.ctx, ' Compare is for Claude Code workflow runs, which can be run again: the ruflo swarm is one live roster.', { dimColor: true })]++ const total = otherRunsOf(run, env.runs).length++ return fold(env.ctx, 'compare', total === 0 ? 'no other run of this workflow has been read' : `${total} other run${total === 1 ? '' : 's'} of "${clip(run.name, 30)}": agents, tokens, time and results side by side`, () => compareBody(env, run))+ },+})diff --git a/plugins/ruflo-console/hooks/views/wf-export.ts b/plugins/ruflo-console/hooks/views/wf-export.tsnew file mode 100644index 0000000000..c0491c7a4d--- /dev/null+++ b/plugins/ruflo-console/hooks/views/wf-export.ts@@ -0,0 +1,94 @@+/**+ * Export on the Workflows page (ADR-461): a board slot that writes the picked run's summary as markdown to a path the person+ * names inside the project (or the scratchpad, once `setExportRoots` told it where that is). The path is checked+ * (data/wf-file.ts: no `..`, no link on the way, nothing overwritten), the text is masked (data/wf-export.ts), and the write goes+ * through the confirm card as a fixed argv. Registered by importing views/wf-replay.ts.+ */+import type { RenderElement } from 'claude-code'++import { exportName, exportSpec, runMarkdown, type ExportCost } from '../data/wf-export'+import { checkNoLinks, dirOf, EXPORT_DIR, resolveExportPath, type Roots } from '../data/wf-file'+import { button, clip, row, text, THEME } from './common'+import { fold, redraw } from './wf-fold'+import { registerSlot, type SlotEnv } from './wf-slots'+import type { WfRun } from '../data/workflows'++type StatFs = Parameters<typeof checkNoLinks>[0]++let scratch: string | null = null+/** The stat the link check needs. A slot is handed no host, so the wiring supplies it once (`setExportFs(host.fs)`); until then no path can be checked and every export is refused. */+let fsOf: StatFs | null = null+let costOf: (run: WfRun) => ExportCost | null = () => null+const said = new Map<string, { ok: boolean; text: string }>()++export const setExportFs = (fs: StatFs | null): void => void (fsOf = fs)++/** The scratchpad folder a summary may also be written under, where the host tells the console (never guessed). */+export const setExportRoots = (scratchDir: string | null): void => void (scratch = scratchDir)++/** Where a per-run cost comes from, if anywhere: without one the summary says n/a. */+export const setExportCostSource = (source: (run: WfRun) => ExportCost | null): void => void (costOf = source)++/** For tests. */+export const resetExport = (): void => (said.clear(), (scratch = null), (fsOf = null), (costOf = () => null))++export const rootsOf = (cwd: string): Roots => ({ cwd, scratch })+export const defaultPathOf = (cwd: string, run: WfRun): string => `${cwd.replace(/\/+$/, '')}/${EXPORT_DIR}/${exportName(run)}`++/** Checks the path and, if it passes, asks the runner for the write. Resolves with what to tell the person; never throws. */+export async function requestExport(env: Pick<SlotEnv, 'ctx' | 'nowMs'>, run: WfRun, input: string, fs: StatFs | null): Promise<{ ok: boolean; text: string }> {+ const roots = rootsOf(env.ctx.state.cwd)+ const wanted = resolveExportPath(input, roots)++ if (!wanted.ok) return { ok: false, text: wanted.why }++ if (fs === null) return { ok: false, text: 'the host\'s file reader is not wired to this page, so a path cannot be checked: nothing is written' }++ const clear = await checkNoLinks(fs, wanted.path, roots)++ if (!clear.ok) return { ok: false, text: clear.why }++ const markdown = runMarkdown(run, { nowMs: env.nowMs, cost: costOf(run) })++ const hasDir = (await fs.stat(dirOf(clear.path)).catch(() => undefined)) !== undefined++ env.ctx.act.workflows.ask(exportSpec(clear.path, markdown, clip(run.name, 40), hasDir), 'that summary cannot be written')++ return { ok: true, text: `asked: confirm below to write ${clear.path}` }+}++export function exportBody(env: SlotEnv, run: WfRun, fs: StatFs | null): RenderElement[] {+ const { ctx } = env+ const note = said.get(run.id)+ const go = (input: string): void => {+ void requestExport(env, run, input, fs).then(result => {+ said.set(run.id, result)+ redraw(ctx)+ })+ }+ const roots = rootsOf(ctx.state.cwd)++ return [+ text(ctx, ` Writes a markdown summary: phases, agents, tokens, time, results (cost: n/a unless a source is wired). Credentials and control characters are masked.`, { dimColor: true }),+ text(ctx, ` Allowed: under ${clip(roots.cwd, 40)}${roots.scratch === null ? '' : ` or ${clip(roots.scratch, 40)}`} · name ends in .md · no .. · never overwrites · you confirm first`, { dimColor: true }),+ ctx.kit.Input === undefined ? text(ctx, ' This surface has no text field: use the default path button.', { dimColor: true }) : ctx.kit.Input({ key: 'wf-export-path', label: 'path', placeholder: `${EXPORT_DIR}/${exportName(run)}`, submitLabel: 'export', onSubmit: value => go(value) }),+ row(ctx, [button(ctx, 'wf-export-default', 'Export to the default path', () => go(defaultPathOf(ctx.state.cwd, run)))], 'wf-export-controls'),+ ...(note === undefined ? [] : [text(ctx, ` ${note.text}`, note.ok ? { color: THEME.ok } : { color: THEME.warn })]),+ ]+}++registerSlot({+ kind: 'board',+ id: 'export',+ title: 'Export run summary',+ order: 60,+ render: env => {+ const run = env.run++ if (run === null) return []+ if (run.kind !== 'workflow') return [text(env.ctx, ' Export is for Claude Code workflow runs.', { dimColor: true })]++ return fold(env.ctx, 'export', `${EXPORT_DIR}/${clip(exportName(run), 40)} (default)`, () => exportBody(env, run, fsOf))+ },+})+diff --git a/plugins/ruflo-console/hooks/views/wf-fold.ts b/plugins/ruflo-console/hooks/views/wf-fold.tsnew file mode 100644index 0000000000..5cd5473f54--- /dev/null+++ b/plugins/ruflo-console/hooks/views/wf-fold.ts@@ -0,0 +1,31 @@+/**+ * The fold every replay-family board slot (ADR-461) opens with: the page already draws the slot's rule, so the body is one+ * line and a button while it is closed (the page stays short), the full body once opened. Kept per slot id for the session.+ */+import type { RenderElement } from 'claude-code'++import { button, row, text, type Ctx } from './common'++const open = new Set<string>()++export const isFolded = (id: string): boolean => !open.has(id)++/** For tests. */+export const resetFolds = (): void => open.clear()++/** The closed line and its button, or the opened body under a "close" button. `redraw` runs after the flip. */+export function fold(ctx: Ctx, id: string, summary: string, body: () => RenderElement[]): RenderElement[] {+ const isOpen = open.has(id)+ const flip = (): void => {+ if (isOpen) open.delete(id)+ else open.add(id)+ ctx.act.workflows.setUi({})+ }++ return isOpen+ ? [row(ctx, [button(ctx, `wf-${id}-fold`, '▾ close', flip), text(ctx, ` ${summary}`, { dimColor: true })], `wf-${id}-head`), ...body()]+ : [row(ctx, [button(ctx, `wf-${id}-fold`, '▸ open', flip), text(ctx, ` ${summary}`, { dimColor: true })], `wf-${id}-head`)]+}++/** Asks the page to draw again (merging an empty change into the cursor invalidates the frame). */+export const redraw = (ctx: Ctx): void => ctx.act.workflows.setUi({})diff --git a/plugins/ruflo-console/hooks/views/wf-replay.ts b/plugins/ruflo-console/hooks/views/wf-replay.tsnew file mode 100644index 0000000000..21b983202f--- /dev/null+++ b/plugins/ruflo-console/hooks/views/wf-replay.ts@@ -0,0 +1,144 @@+/**+ * Replay on the Workflows page (ADR-461): a board slot that scrubs the picked run back and forth through its agents' start and end+ * moments and draws the board as it stood at each step (data/wf-replay.ts). Importing this module registers it AND the three+ * other slots of the feature (compare, export, saved views), so the merge owner adds one line to views/wf-register.ts:+ *+ * import './wf-replay'+ *+ * The console reads runs; it cannot rewind or message one, so this replays what the files say happened and nothing else.+ */+import type { RenderElement } from 'claude-code'++import { boardAt, buildTimeline, describeStep, isPlaying, newReplay, offsetOf, SPEEDS, stepNow, stepReplay, type ReplayCommand, type ReplayUi, type Timeline } from '../data/wf-replay'+import { fmtElapsed, fmtTokens, type WfAgent, type WfRun } from '../data/workflows'+import { button, clip, row, text, THEME, type Ctx } from './common'+import { fold, redraw } from './wf-fold'+import { registerSlot, type SlotEnv } from './wf-slots'+import './wf-compare'+import './wf-export'+import './wf-saved'++const replays = new Map<string, ReplayUi>()+const timelines = new Map<string, { sig: string; tl: Timeline }>()+const MAX_RUNS_KEPT = 12++/** The timeline of a run, rebuilt only when the run's own figures changed (a live run grows; a finished one never does). */+export function timelineOf(run: WfRun): Timeline {+ const sig = `${run.state}|${run.total}|${run.done}|${run.failed}|${run.running}|${run.durationMs ?? ''}`+ const kept = timelines.get(run.id)++ if (kept?.sig === sig) return kept.tl++ const tl = buildTimeline(run)++ timelines.delete(run.id)+ timelines.set(run.id, { sig, tl })+ if (timelines.size > MAX_RUNS_KEPT) timelines.delete(timelines.keys().next().value as string)++ return tl+}++export const replayOf = (runId: string): ReplayUi => replays.get(runId) ?? newReplay()++/** Applies one command to a run's replay and keeps the result. Exported so the buttons and a test share it. */+export function applyReplay(run: WfRun, command: ReplayCommand, nowMs: number): ReplayUi {+ const next = stepReplay(replayOf(run.id), timelineOf(run), command, nowMs)++ replays.delete(run.id)+ replays.set(run.id, next)+ if (replays.size > MAX_RUNS_KEPT) replays.delete(replays.keys().next().value as string)++ return next+}++/** For tests. */+export const resetReplays = (): void => (replays.clear(), timelines.clear())++const MARK: Record<WfAgent['state'], string> = { done: '✔', failed: '✖', running: '◐', stale: '◌', idle: '●', queued: '○' }+const COLOR = (state: WfAgent['state']): string | undefined => (state === 'done' ? THEME.ok : state === 'failed' ? THEME.bad : state === 'running' ? THEME.warn : undefined)++const clock = (ms: number): string => `+${fmtElapsed(ms)}`++function bar(fraction: number, width: number): string {+ const filled = Math.round(Math.max(0, Math.min(1, fraction)) * width)++ return `${'█'.repeat(filled)}${'░'.repeat(width - filled)}`+}++/** The replayed board in rows: each phase with its counts, its agents beneath, capped so a frame never scales with the run. */+function boardRows(ctx: Ctx, board: WfRun): RenderElement[] {+ const rows: RenderElement[] = []+ const budget = 22+ let used = 0++ for (const phase of board.phases) {+ if (used >= budget) break++ const mark = phase.failed > 0 ? '✖' : phase.total > 0 && phase.done === phase.total ? '✔' : phase.running > 0 ? '◐' : '○'++ rows.push(text(ctx, ` ${mark} ${phase.title} ${phase.done}/${phase.total}${phase.running > 0 ? ` · ${phase.running} running` : ''}`, { bold: true, ...(phase.failed > 0 ? { color: THEME.bad } : {}) }))+ used += 1++ for (const agent of phase.agents) {+ if (used >= budget) break++ const color = COLOR(agent.state)++ rows.push(text(ctx, ` ${MARK[agent.state]} ${clip(agent.label, Math.max(8, ctx.columns - 34)).padEnd(Math.max(8, Math.min(30, ctx.columns - 34)))} ${agent.state.padEnd(7)} ${fmtTokens(agent.tokens, agent.isTokensPartial).padStart(8)} ${fmtElapsed(agent.elapsedMs).padStart(7)}`, color === undefined ? { dimColor: agent.state === 'queued' } : { color }))+ used += 1+ }+ }++ const hidden = board.phases.reduce((sum, phase) => sum + 1 + phase.agents.length, 0) - used++ if (hidden > 0) rows.push(text(ctx, ` +${hidden} more rows not drawn (the export holds all of them)`, { dimColor: true }))++ return rows+}++export function replayBody(env: SlotEnv, run: WfRun): RenderElement[] {+ const { ctx, nowMs } = env+ const tl = timelineOf(run)++ if (tl.why !== null) return [text(ctx, ` ${tl.why}`, { dimColor: true })]++ const ui = replayOf(run.id)+ const step = stepNow(ui, tl, nowMs)+ const n = tl.events.length+ const playing = isPlaying(ui, tl, nowMs)+ const board = boardAt(run, tl, step)+ const go = (command: ReplayCommand) => () => {+ applyReplay(run, command, Date.now())+ redraw(ctx)+ }+ const span = tl.t1 - tl.t0++ return [+ text(ctx, ` step ${step}/${n} · ${clock(offsetOf(tl, step))} of ${clock(span)} · ${ui.speed}x · ${playing ? '▶ playing' : step >= n ? '■ at the end' : '⏸ paused'}`),+ text(ctx, ` ${bar(span === 0 ? (step >= n ? 1 : 0) : offsetOf(tl, step) / span, Math.max(10, Math.min(48, ctx.columns - 6)))}`, { dimColor: true }),+ text(ctx, ` ▸ ${clip(describeStep(tl, step), Math.max(10, ctx.columns - 6))}`, { color: THEME.info }),+ row(ctx, [button(ctx, 'wf-rp-first', '⏮', go('first')), button(ctx, 'wf-rp-pphase', '◂◂ phase', go('prev-phase')), button(ctx, 'wf-rp-prev', '◂ step', go('prev')), button(ctx, 'wf-rp-play', playing ? '⏸ pause' : '▶ play', go('play'), { primary: true }), button(ctx, 'wf-rp-next', 'step ▸', go('next')), button(ctx, 'wf-rp-nphase', 'phase ▸▸', go('next-phase')), button(ctx, 'wf-rp-last', '⏭', go('last'))], 'wf-rp-controls'),+ row(ctx, [text(ctx, ' speed '), button(ctx, 'wf-rp-slower', '−', go('slower')), text(ctx, ` ${ui.speed}x `), button(ctx, 'wf-rp-faster', '+', go('faster')), text(ctx, ` of ${SPEEDS.join(' · ')}`, { dimColor: true })], 'wf-rp-speed'),+ ...boardRows(ctx, board),+ ...(tl.untimed.length > 0 ? [text(ctx, ` ${tl.untimed.length} agent${tl.untimed.length === 1 ? '' : 's'} left off: no start time (or no span) in the run's files, so there is no moment to place ${tl.untimed.length === 1 ? 'it' : 'them'} at`, { color: THEME.warn })] : []),+ text(ctx, step >= n ? ' This is the run\'s real final board.' : ' Tokens show n/a until an agent ends: only its final figure is recorded. A running agent\'s time is measured to this step.', { dimColor: true }),+ text(ctx, ' The console reads and replays the files; it cannot rewind, stop or message a Claude Code workflow.', { dimColor: true }),+ ]+}++registerSlot({+ kind: 'board',+ id: 'replay',+ title: 'Replay',+ order: 40,+ render: env => {+ const run = env.run++ if (run === null) return []+ if (run.kind !== 'workflow') return [text(env.ctx, ' Replay is for Claude Code workflow runs: the ruflo swarm is a live roster with no history to step through.', { dimColor: true })]++ const tl = timelineOf(run)++ return fold(env.ctx, 'replay', tl.why ?? `${tl.events.length} moments in ${fmtElapsed(tl.t1 - tl.t0)}: scrub back and forth, jump by phase, play at up to ${SPEEDS[SPEEDS.length - 1]}x`, () => replayBody(env, run))+ },+})diff --git a/plugins/ruflo-console/hooks/views/wf-saved.ts b/plugins/ruflo-console/hooks/views/wf-saved.tsnew file mode 100644index 0000000000..927414c172--- /dev/null+++ b/plugins/ruflo-console/hooks/views/wf-saved.ts@@ -0,0 +1,61 @@+/**+ * Saved views and pins on the Workflows page (ADR-461): a board slot that says what the page remembers (cursor, filters, search,+ * pinned runs), pins or unpins the picked run, jumps to a pinned run, and forgets the saved file (behind the confirm card). The+ * reading and writing is hooks/wf-saved-live.ts; registered by importing views/wf-replay.ts.+ */+import type { RenderElement } from 'claude-code'++import { MAX_PINS, SAVED_FILE, SAVED_MAX_BYTES, isPinned, pinsIn, togglePin } from '../data/wf-saved'+import { currentPhase, type WfRun } from '../data/workflows'+import { forgetSpec, savedFor, updateSaved } from '../wf-saved-live'+import { ago, button, clip, row, text, THEME } from './common'+import { fold, redraw } from './wf-fold'+import { registerSlot, type SlotEnv } from './wf-slots'++export function savedBody(env: SlotEnv, run: WfRun | null): RenderElement[] {+ const { ctx, runs, nowMs } = env+ const cwd = ctx.state.cwd+ const own = savedFor(cwd)+ const pins = pinsIn(own.saved, runs)+ const filters = Object.entries(own.saved.filters).map(([key, value]) => `${key}=${clip(value, 24)}`).join(' · ')+ const pin = (): void => {+ if (run === null) return++ const next = togglePin(own.saved, run, Date.now())++ updateSaved(cwd, () => next.saved, next.said)+ redraw(ctx)+ }++ return [+ text(ctx, ` File ${SAVED_FILE} (≤ ${SAVED_MAX_BYTES / 1000} kB, versioned) · ${own.saved.savedAtMs === 0 ? 'not saved yet' : `saved ${ago(own.saved.savedAtMs, nowMs)}`}${own.isDirty ? ' · change waiting to be written' : ''}`, { dimColor: true }),+ text(ctx, ` Remembers the cursor (run, phase, agent by name), filters and search, and pins. Written by the console itself, only there; forgetting asks first.`, { dimColor: true }),+ ...(own.problem === null ? [] : [text(ctx, ` ${own.problem}`, { color: THEME.warn })]),+ ...(own.error === null ? [] : [text(ctx, ` The last write failed (${clip(own.error, 60)}): the change is kept and tried again.`, { color: THEME.warn })]),+ ...(own.restored === null ? [] : [text(ctx, own.restored === 'exact' ? ' The cursor was put back where you left it.' : own.restored === 'name' ? ' That run is gone: the cursor went to the newest run of the same workflow.' : ' The run you left on is no longer among the runs read: the cursor is where it was.', { dimColor: true })]),+ text(ctx, ` search: ${own.saved.search === '' ? 'none' : `"${clip(own.saved.search, 40)}"`} · filters: ${filters === '' ? 'none' : filters}`, { dimColor: true }),+ row(ctx, [+ ...(run === null ? [] : [button(ctx, 'wf-saved-pin', isPinned(own.saved, run.id) ? 'Unpin this run' : 'Pin this run', pin)]),+ button(ctx, 'wf-saved-forget', 'Forget saved views', () => ctx.act.workflows.ask(forgetSpec(cwd))),+ ], 'wf-saved-controls'),+ ...(own.said === null ? [] : [text(ctx, ` ${own.said}`, { color: THEME.info })]),+ ...(pins.length === 0 ? [text(ctx, ` No pinned runs (up to ${MAX_PINS}).`, { dimColor: true })] : pins.map(entry => (entry.index === null || entry.run === null ? text(ctx, ` ◌ ${clip(entry.pin.name, 40)} · not among the runs read now`, { dimColor: true }) : row(ctx, [button(ctx, `wf-saved-go-${entry.index}`, `▸ ${clip(entry.pin.name, 28)}`, () => jump(env, entry.index as number, entry.run as WfRun)), text(ctx, ` ${entry.run.state} · ${entry.run.done}/${entry.run.total} agents`, { dimColor: true })], `wf-saved-pin-${entry.index}`)))),+ ]+}++/** Puts the cursor on a run, on the phase it is in. */+function jump(env: SlotEnv, index: number, run: WfRun): void {+ env.ctx.act.workflows.setUi({ run: index, phase: currentPhase(run.phases) ?? 0, agent: 0, column: 'phases', isInspecting: false })+}++registerSlot({+ kind: 'board',+ id: 'saved',+ title: 'Saved views and pins',+ order: 70,+ render: env => {+ const own = savedFor(env.ctx.state.cwd)++ return fold(env.ctx, 'saved', `${own.saved.pins.length} pinned · the cursor is remembered across restarts`, () => savedBody(env, env.run))+ },+})diff --git a/plugins/ruflo-console/hooks/wf-saved-live.ts b/plugins/ruflo-console/hooks/wf-saved-live.tsnew file mode 100644index 0000000000..933b15463e--- /dev/null+++ b/plugins/ruflo-console/hooks/wf-saved-live.ts@@ -0,0 +1,172 @@+/**+ * The Workflows page's saved views, live (ADR-461): reads `.claude-flow/console/wf-views.json` once per project, puts the+ * cursor back where it was when the runs have been read, and writes the file again when the cursor, a pin, a filter or the search+ * changed (at most once every SAVE_GAP_MS, one write at a time). The data rules are in data/wf-saved.ts; this holds the one+ * copy per project and the reads and writes, with the host's `fs` and `run` passed in so a test supplies its own.+ *+ * The write is the console's own state file: a fixed-argv `dd` or `install -D` (no shell; the text is stdin), about 1 kB, only under+ * `.claude-flow/console/` of the project, and the page says where the file is. Forgetting it goes through the confirm card.+ */+import type { ActionSpec } from './actions'+import { decodeSaved, emptySaved, encodeSaved, captureDrill, restoreDrill, sameDrill, SAVED_FILE, SAVED_MAX_BYTES, type Saved } from './data/wf-saved'+import { dirOf, removeFileArgv, replaceFileArgv } from './data/wf-file'+import { readBounded } from './data/files'+import type { Host } from './host'+import type { State } from './state'+import { workflowsModelOf } from './wf-live'+import { DETAIL_TAB, slotsFor } from './views/wf-slots'++export const SAVE_GAP_MS = 2000++export type SavedHost = Pick<Host, 'fs' | 'run'>++export type HeldSaved = {+ saved: Saved+ problem: string | null+ isForeign: boolean+ isLoaded: boolean+ isRestored: boolean+ isDirty: boolean+ /** Off after the file was forgotten: the cursor is not saved again until something is pinned or set. */+ isAuto: boolean+ isWriting: boolean+ lastWriteMs: number+ /** Why the last write failed, or null. */+ error: string | null+ /** How the cursor was found when it was put back, for the page to say. */+ restored: 'exact' | 'name' | 'gone' | null+ /** The last thing a pin or forget did, in words. */+ said: string | null+}++const held = new Map<string, HeldSaved>()++const fresh = (): HeldSaved => ({ saved: emptySaved(), problem: null, isForeign: false, isLoaded: false, isRestored: false, isDirty: false, isAuto: true, isWriting: false, lastWriteMs: 0, error: null, restored: null, said: null })++export const savedFor = (cwd: string): HeldSaved => {+ const own = held.get(cwd) ?? fresh()++ held.set(cwd, own)++ return own+}++export const savedPathOf = (cwd: string): string => `${cwd.replace(/\/+$/, '')}/${SAVED_FILE}`++/** Changes the held views (a pin, a filter, the search) and marks them to be written. A file from a newer console is never changed. */+export function updateSaved(cwd: string, change: (saved: Saved) => Saved, said?: string): void {+ const own = savedFor(cwd)++ if (own.isForeign) return++ own.saved = change(own.saved)+ own.isDirty = true+ own.isAuto = true+ if (said !== undefined) own.said = said+}++/** For tests: forgets everything held. */+export const resetSavedLive = (): void => held.clear()++async function load(state: State, host: SavedHost, own: HeldSaved): Promise<void> {+ own.isLoaded = true++ const read = await readBounded(host.fs, state.cache, savedPathOf(state.cwd), SAVED_MAX_BYTES, true)++ if (read.text === null && read.reason === 'too-large') {+ own.problem = `the saved views file is over ${SAVED_MAX_BYTES / 1000} kB, so it is not read and will be replaced on the next change`+ return+ }++ const decoded = decodeSaved(read.text)++ own.saved = decoded.saved+ own.problem = decoded.problem+ own.isForeign = decoded.isForeign+}++/**+ * One pass, called while the Workflows page is the one in front, after its read: loads the file the first time, puts the cursor back+ * once there are runs to put it on, notes a cursor that moved, and writes when something changed. Never throws.+ */+export async function syncSavedViews(state: State, host: SavedHost, nowMs: number = Date.now()): Promise<void> {+ try {+ const own = savedFor(state.cwd)++ if (!own.isLoaded) await load(state, host, own)++ const runs = workflowsModelOf(state, nowMs)?.runs ?? []++ if (runs.length === 0) return++ if (!own.isRestored) {+ own.isRestored = true++ const back = restoreDrill(own.saved.drill, runs, state.wf.ui)++ if (back !== null) {+ own.restored = back.found+ if (back.found !== 'gone') {+ state.wf.ui = back.ui+ state.wf.tab = back.tab === DETAIL_TAB || slotsFor('tab').some(slot => slot.id === back.tab) ? back.tab : DETAIL_TAB+ }+ }++ return+ }++ const drill = captureDrill(state.wf.ui, runs, state.wf.tab)++ if (own.isAuto && !own.isForeign && !sameDrill(drill, own.saved.drill)) {+ own.saved = { ...own.saved, drill }+ own.isDirty = true+ }++ if (!own.isDirty || own.isForeign || own.isWriting || nowMs - own.lastWriteMs < SAVE_GAP_MS) return++ own.isWriting = true+ own.lastWriteMs = nowMs++ try {+ const path = savedPathOf(state.cwd)+ const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined+ const result = await host.run(replaceFileArgv(path, hasDir), 10_000, encodeSaved(own.saved, nowMs))++ own.error = result.exitCode === 0 ? null : `the write exited ${result.exitCode}`+ if (result.exitCode === 0) own.isDirty = false+ } catch (error) {+ own.error = error instanceof Error ? error.message.slice(0, 80) : 'the write was refused'+ } finally {+ own.isWriting = false+ }+ } catch {+ // Saved views are a convenience: a failure here must never reach the page.+ }+}++/** The confirm-gated removal of the saved views file; once it ran the held copy is emptied and the cursor is not saved again until a pin or filter is set. */+export function forgetSpec(cwd: string): ActionSpec {+ const path = savedPathOf(cwd)++ return {+ label: 'forget saved Workflows views',+ args: [],+ argv: removeFileArgv(path),+ expect: `${path} removed`,+ declared: 'delete',+ shows: `rm -f -- ${path}`,+ note: 'deletes the console\'s own saved cursor, filters and pins for this project; runs and their files are not touched',+ timeoutMs: 10_000,+ onOutput: () => {+ const own = savedFor(cwd)++ own.saved = emptySaved()+ own.isDirty = false+ own.isAuto = false+ own.problem = null+ own.restored = null+ own.said = 'saved views forgotten'+ },+ verifyLocal: async host => (await host.fs.stat(path).catch(() => undefined)) === undefined,+ }+}diff --git a/plugins/ruflo-console/tests/fixtures/wf-runs.ts b/plugins/ruflo-console/tests/fixtures/wf-runs.tsnew file mode 100644index 0000000000..b0e7df9541--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/wf-runs.ts@@ -0,0 +1,28 @@+/** Finished runs for the replay, compare, export and saved-views specs: built through the real `buildRun` from a run record. */+import { buildRun, type WfRun } from '../../hooks/data/workflows'+import { T0 } from './workflows'++export type RecAgent = { id: string; label: string; phase: string; state?: string; at?: number; tokens?: number; ms?: number; model?: string }++/** `at` and `ms` are seconds from T0; an agent given neither has no start time or span. */+export function runOf(id: string, agents: readonly RecAgent[], over: Record<string, unknown> = {}, name = 'demo-run'): WfRun {+ const record = {+ runId: id,+ status: 'completed',+ workflowName: name,+ startTime: T0,+ durationMs: 90_000,+ phases: [{ title: 'Build' }, { title: 'Review' }],+ workflowProgress: agents.map(a => ({ type: 'workflow_agent', label: a.label, phaseTitle: a.phase, agentId: a.id, state: a.state ?? 'done', ...(a.at !== undefined && { startedAt: T0 + a.at * 1000 }), ...(a.tokens !== undefined && { tokens: a.tokens }), ...(a.ms !== undefined && { durationMs: a.ms * 1000 }), ...(a.model !== undefined && { model: a.model }) })),+ ...over,+ }++ return buildRun({ id, journal: null, agents: new Map(), record: JSON.stringify(record), script: null, nowMs: T0 + 600_000 })+}++/** build:a runs 0-60s, build:b fails at 5s, review:a runs 60-90s. */+export const BASE: readonly RecAgent[] = [+ { id: 'ra1', label: 'build:a', phase: 'Build', at: 0, ms: 60, tokens: 180_000 },+ { id: 'ra2', label: 'build:b', phase: 'Build', state: 'failed', at: 0, ms: 5, tokens: 1200 },+ { id: 'ra3', label: 'review:a', phase: 'Review', at: 60, ms: 30, tokens: 90_000 },+]diff --git a/plugins/ruflo-console/tests/wf-compare.spec.ts b/plugins/ruflo-console/tests/wf-compare.spec.tsnew file mode 100644index 0000000000..59dca273b7--- /dev/null+++ b/plugins/ruflo-console/tests/wf-compare.spec.ts@@ -0,0 +1,108 @@+/**+ * Two runs of one workflow side by side (ADR-461): matching, marks and the thresholds that make a difference a change. Run with+ * npx vitest run plugins/ruflo-console/tests/wf-compare.spec.ts --testTimeout=30000+ */+import { describe, expect, it } from 'vitest'++import { compareRuns, fmtRatio, otherRunsOf, TIME_DELTA, TOKEN_DELTA, type Comparison } from '../hooks/data/wf-compare'+import { BASE, runOf, type RecAgent } from './fixtures/wf-runs'++const ok = (c: ReturnType<typeof compareRuns>): Comparison => {+ if (!c.ok) throw new Error(c.why)++ return c+}+const marks = (c: Comparison): Record<string, string> => Object.fromEntries(c.rows.map(r => [r.label, r.mark]))+const tweak = (patch: Partial<RecAgent> & { id: string }): RecAgent[] => BASE.map(a => (a.id === patch.id ? { ...a, ...patch } : a))++describe('which runs compare', () => {+ it('offers only other workflow runs with the same name', () => {+ const a = runOf('wf_a', BASE)+ const b = runOf('wf_b', BASE)+ const other = runOf('wf_c', BASE, {}, 'another')++ expect(otherRunsOf(a, [a, b, other]).map(r => r.id)).toEqual(['wf_b'])+ expect(compareRuns(a, other)).toMatchObject({ ok: false, why: expect.stringMatching(/different workflows/) })+ expect(compareRuns(a, a)).toMatchObject({ ok: false })+ })+})++describe('marks', () => {+ it('= for identical runs, with totals', () => {+ const c = ok(compareRuns(runOf('wf_a', BASE), runOf('wf_b', BASE)))++ expect(Object.values(marks(c))).toEqual(['=', '=', '='])+ expect(c.counts).toEqual({ same: 3, changed: 0, added: 0, removed: 0 })+ expect(c.totals.agents).toMatchObject({ a: 3, b: 3, diff: 0 })+ })++ it('+ for an agent only in B and - for one only in A', () => {+ const b = runOf('wf_b', [...BASE.filter(a => a.id !== 'ra3'), { id: 'rb9', label: 'extra', phase: 'Review', at: 70, ms: 5, tokens: 10 }])+ const c = ok(compareRuns(runOf('wf_a', BASE), b))++ expect(marks(c)).toMatchObject({ 'review:a': '-', extra: '+' })+ expect(c.counts).toMatchObject({ added: 1, removed: 1 })+ })++ it('~ on a state change or a model change', () => {+ const c = ok(compareRuns(runOf('wf_a', BASE), runOf('wf_b', tweak({ id: 'ra1', state: 'failed' }))))++ expect(c.rows.find(r => r.label === 'build:a')).toMatchObject({ mark: '~', stateChange: 'done → failed' })++ const m = ok(compareRuns(runOf('wf_a', tweak({ id: 'ra1', model: 'claude-opus-5-5' })), runOf('wf_b', tweak({ id: 'ra1', model: 'claude-sonnet-5-5' }))))++ expect(m.rows[0]).toMatchObject({ mark: '~', modelChange: 'claude-opus-5-5 → claude-sonnet-5-5' })+ })++ it('treats tokens as changed from exactly TOKEN_DELTA, not below it', () => {+ const at = (tokens: number) => ok(compareRuns(runOf('wf_a', BASE), runOf('wf_b', tweak({ id: 'ra1', tokens })))).rows[0]?.mark++ expect(TOKEN_DELTA).toBe(0.1)+ expect(at(180_000 * 1.1)).toBe('~')+ expect(at(180_000 * 1.099)).toBe('=')+ expect(at(180_000 * 0.9)).toBe('~')+ })++ it('treats time as changed from exactly TIME_DELTA, not below it', () => {+ const at = (ms: number) => ok(compareRuns(runOf('wf_a', BASE), runOf('wf_b', tweak({ id: 'ra1', ms })))).rows[0]?.mark++ expect(TIME_DELTA).toBe(0.25)+ expect(at(75)).toBe('~')+ expect(at(74.9)).toBe('=')+ })++ it('never counts an unknown figure as a change', () => {+ const noTokens = BASE.map(a => (a.id === 'ra1' ? { id: a.id, label: a.label, phase: a.phase, at: a.at, ms: a.ms } : a))+ const c = ok(compareRuns(runOf('wf_a', BASE), runOf('wf_b', noTokens)))+ const row = c.rows.find(r => r.label === 'build:a')++ expect(row?.mark).toBe('=')+ expect(row?.tokens.diff).toBeUndefined()+ expect(fmtRatio(row?.tokens ?? {})).toBe('n/a')+ })++ it('pairs agents of one label by order, so a repeated label does not collapse', () => {+ const twice = (t2: number): RecAgent[] => [{ id: 'q1', label: 'w', phase: 'Build', at: 0, ms: 10, tokens: 100 }, { id: 'q2', label: 'w', phase: 'Build', at: 0, ms: 10, tokens: t2 }]+ const c = ok(compareRuns(runOf('wf_a', twice(100)), runOf('wf_b', twice(500))))++ expect(c.rows.map(r => r.mark)).toEqual(['=', '~'])+ })++ it('notes a floor and a run with no record, and a differing result', () => {+ const a = runOf('wf_a', BASE)+ const b = { ...runOf('wf_b', BASE), hasRecord: false, isTokensPartial: true }+ const c = ok(compareRuns(a, b))++ expect(c.notes.join(' ')).toMatch(/floor/)+ expect(c.notes.join(' ')).toMatch(/run B is derived/)+ })+})++describe('fmtRatio', () => {+ it('reads a percent with a sign and caps the extremes', () => {+ expect(fmtRatio({ ratio: 0.1234 })).toBe('+12%')+ expect(fmtRatio({ ratio: -0.5 })).toBe('-50%')+ expect(fmtRatio({ ratio: 50 })).toBe('>+999%')+ expect(fmtRatio({ diff: 0 })).toBe('0%')+ })+})diff --git a/plugins/ruflo-console/tests/wf-export.spec.ts b/plugins/ruflo-console/tests/wf-export.spec.tsnew file mode 100644index 0000000000..d34700aaed--- /dev/null+++ b/plugins/ruflo-console/tests/wf-export.spec.ts@@ -0,0 +1,132 @@+/**+ * Export of a run summary (ADR-461): the markdown (masked, escaped, capped), the path rules, and the fixed-argv write.+ * Run with npx vitest run plugins/ruflo-console/tests/wf-export.spec.ts --testTimeout=30000+ */+import { describe, expect, it } from 'vitest'++import { exportName, exportSpec, MAX_EXPORT_BYTES, runMarkdown } from '../hooks/data/wf-export'+import { checkNoLinks, newFileArgv, removeFileArgv, replaceFileArgv, resolveExportPath } from '../hooks/data/wf-file'+import { BASE, runOf } from './fixtures/wf-runs'++const KEY = 'sk-abcdefghijklmnopqrstuvwx'+const ROOTS = { cwd: '/work/proj', scratch: '/home/u/.cache/claude-code/tmp/s1' }++describe('the markdown', () => {+ it('holds the phases, agents, tokens, time and a provenance line, with cost n/a by default', () => {+ const md = runMarkdown(runOf('wf_a', BASE), { nowMs: Date.parse('2026-10-06T02:00:00Z') })++ expect(md).toMatch(/^# Workflow run: demo-run/)+ expect(md).toMatch(/## 1\. Build/)+ expect(md).toMatch(/## 2\. Review/)+ expect(md).toMatch(/\| build:a \| done \| n\/a \| 180\.0k \| 1m00s \| n\/a \|/)+ expect(md).toMatch(/\| Cost \| n\/a \(no cost source for this run\) \|/)+ expect(md).toMatch(/run record Claude Code wrote/)+ })++ it('shows a cost only with its source', () => {+ const md = runMarkdown(runOf('wf_a', BASE), { nowMs: 0, cost: { usd: 1.234, source: 'cost ledger' } })++ expect(md).toMatch(/\$1\.23 \(cost ledger\)/)+ expect(runMarkdown(runOf('wf_a', BASE), { nowMs: 0, cost: { usd: null, source: 'x' } })).toMatch(/n\/a/)+ })++ it('masks credentials and strips control characters and escapes table characters in every free-text field', () => {+ const run = runOf('wf_a', [{ id: 'z1', label: `bad|label ${KEY} \u001b[31mred`, phase: 'Build', at: 0, ms: 1, tokens: 5 }], { workflowName: `name ${KEY}` }, `name ${KEY}`)+ const withResult = { ...run, phases: run.phases.map(p => ({ ...p, agents: p.agents.map(a => ({ ...a, resultPreview: `token=${KEY} and Bearer abcdefghijklmnop\nnext` })) })) }+ const md = runMarkdown(withResult, { nowMs: 0 })++ expect(md).not.toContain(KEY)+ expect(md).not.toContain('abcdefghijklmnop')+ // eslint-disable-next-line no-control-regex+ expect(/[\u0000-\u0008\u000b-\u001f\u007f]/.test(md)).toBe(false)+ expect(md).toContain('bad\\|label')+ expect(md).toContain('‹masked›')+ })++ it('is capped, and says where it was cut', () => {+ const many = Array.from({ length: 3000 }, (_, i) => ({ id: `m${i}`, label: `agent number ${i} with a long enough label to fill the file quickly`, phase: 'Build', at: i, ms: 1, tokens: i }))+ const md = runMarkdown(runOf('wf_big', many), { nowMs: 0 })++ expect(new TextEncoder().encode(md).length).toBeLessThanOrEqual(MAX_EXPORT_BYTES)+ expect(md).toMatch(/Cut here: this summary is capped/)+ })++ it('names the file from the run, safely', () => {+ expect(exportName(runOf('wf_a', BASE, {}, '../../etc/pass wd'))).toBe('etc-pass-wd-wf_a.md')+ })+})++describe('the path', () => {+ const ok = (p: string) => resolveExportPath(p, ROOTS)++ it('accepts a relative path inside the project and an absolute one in the scratchpad', () => {+ expect(ok('out/run.md')).toEqual({ ok: true, path: '/work/proj/out/run.md' })+ expect(ok('./a//b/run.md')).toEqual({ ok: true, path: '/work/proj/a/b/run.md' })+ expect(ok('/home/u/.cache/claude-code/tmp/s1/run.md')).toMatchObject({ ok: true })+ })++ it('refuses traversal, other roots, other extensions, control characters, ~ and a lookalike prefix', () => {+ for (const bad of ['../x.md', 'a/../../x.md', '/etc/x.md', '/work/proj2/x.md', '/work/proj/../etc/x.md', 'x.txt', 'x.md\u0000', 'x\u001b.md', '~/x.md', 'a\\b.md', '', ' ', '.md', '/work/proj/-x/.md', `${'a/'.repeat(200)}x.md`]) {+ expect(ok(bad), JSON.stringify(bad)).toMatchObject({ ok: false })+ }+ })++ it('refuses the scratchpad when none is known', () => {+ expect(resolveExportPath('/home/u/x.md', { cwd: '/work/proj' })).toMatchObject({ ok: false })+ })++ it('refuses a link on the way down and a file already there; a missing path is fine', async () => {+ const stat = (table: Record<string, { isLink?: boolean; kind?: string }>) => async (path: string) => table[path] ?? Promise.reject(new Error('ENOENT'))++ expect(await checkNoLinks({ stat: stat({}) }, '/work/proj/out/run.md', ROOTS)).toMatchObject({ ok: true })+ expect(await checkNoLinks({ stat: stat({ '/work/proj/out': { isLink: true } }) }, '/work/proj/out/run.md', ROOTS)).toMatchObject({ ok: false, why: expect.stringMatching(/is a link/) })+ expect(await checkNoLinks({ stat: stat({ '/work/proj/out': { kind: 'file' } }) }, '/work/proj/out/run.md', ROOTS)).toMatchObject({ ok: false, why: expect.stringMatching(/not a folder/) })+ expect(await checkNoLinks({ stat: stat({ '/work/proj/out': { kind: 'dir' }, '/work/proj/out/run.md': { kind: 'file' } }) }, '/work/proj/out/run.md', ROOTS)).toMatchObject({ ok: false, why: expect.stringMatching(/already exists/) })+ expect(await checkNoLinks({ stat: stat({ '/work/proj/out/run.md': { kind: 'file' } }) }, '/work/proj/out/run.md', ROOTS, { allowExisting: true })).toMatchObject({ ok: true })+ expect(await checkNoLinks({ stat: stat({}) }, '/elsewhere/run.md', ROOTS)).toMatchObject({ ok: false })+ })+})++describe('the write', () => {+ it('is a command with no shell: the path is one element, whatever it says', () => {+ const evil = '/work/proj/a b;$(rm -rf ~)`x`.md'++ expect(newFileArgv(evil, true)).toEqual(['dd', `of=${evil}`, 'conv=excl', 'status=none'])+ expect(newFileArgv(evil, false)).toEqual(['install', '-D', '-m', '0644', '/dev/stdin', '--', evil])+ expect(replaceFileArgv(evil, true)).toEqual(['dd', `of=${evil}`, 'status=none'])+ expect(replaceFileArgv(evil, false)).toEqual(newFileArgv(evil, false))+ expect(removeFileArgv(evil)).toEqual(['rm', '-f', '--', evil])+ for (const argv of [newFileArgv(evil, true), newFileArgv(evil, false), replaceFileArgv(evil, true), removeFileArgv(evil)]) expect(argv.some(part => part === 'sh' || part === 'bash' || part === '-c')).toBe(false)+ })++ it('a new file never replaces one: dd refuses an existing file (conv=excl) on a real disk', async () => {+ const { mkdtempSync, readFileSync, rmSync } = await import('node:fs')+ const { spawnSync } = await import('node:child_process')+ const { tmpdir } = await import('node:os')+ const dir = mkdtempSync(`${tmpdir()}/wf-export-`)+ const file = `${dir}/a b;$(x).md`++ try {+ const first = spawnSync(...(args => [args[0] as string, args.slice(1) as string[], { input: 'one\n' }] as const)(newFileArgv(file, true)))++ expect(first.status).toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('one\n')++ const second = spawnSync(...(args => [args[0] as string, args.slice(1) as string[], { input: 'two\n' }] as const)(newFileArgv(file, true)))++ expect(second.status).not.toBe(0)+ expect(readFileSync(file, 'utf8')).toBe('one\n')+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ })++ it('is a confirm-gated spec: argv, text on stdin, declared write, verified on disk', async () => {+ const spec = exportSpec('/work/proj/o.md', '# hi\n', 'demo', true)++ expect(spec).toMatchObject({ argv: newFileArgv('/work/proj/o.md', true), stdin: '# hi\n', declared: 'write', args: [] })+ expect(spec.shows).toMatch(/never overwrites/)+ expect(await spec.verifyLocal?.({ fs: { stat: async () => ({ size: 1 }) } } as never)).toBe(true)+ expect(await spec.verifyLocal?.({ fs: { stat: async () => Promise.reject(new Error('x')) } } as never)).toBe(false)+ })+})diff --git a/plugins/ruflo-console/tests/wf-replay-views.spec.ts b/plugins/ruflo-console/tests/wf-replay-views.spec.tsnew file mode 100644index 0000000000..4216f89115--- /dev/null+++ b/plugins/ruflo-console/tests/wf-replay-views.spec.ts@@ -0,0 +1,240 @@+/**+ * The replay family on the Workflows page (ADR-461): its four board slots register without taking a hotkey, fold shut by default, and+ * work through the page's own buttons. A recording kit and an in-memory host; no engine. Run with+ * npx vitest run plugins/ruflo-console/tests/wf-replay-views.spec.ts --testTimeout=30000+ */+import { beforeEach, describe, expect, it } from 'vitest'++import type { ActionSpec } from '../hooks/actions'+import { swarmRun } from '../hooks/data/workflows'+import { newState } from '../hooks/state'+import type { Host } from '../hooks/host'+import { workflowsActions } from '../hooks/wf-actions'+import { resetSavedLive, savedFor } from '../hooks/wf-saved-live'+import type { Actions, Ctx, Kit } from '../hooks/views/common'+import { resetCompare } from '../hooks/views/wf-compare'+import { resetExport, setExportFs } from '../hooks/views/wf-export'+import { resetFolds } from '../hooks/views/wf-fold'+import { resetReplays } from '../hooks/views/wf-replay'+import { workflowsPage } from '../hooks/views/wf-page'+import { slotsFor } from '../hooks/views/wf-slots'+import { BASE, runOf } from './fixtures/wf-runs'+import { T0 } from './fixtures/workflows'++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 }), Input: (props: Record<string, unknown>): El => ({ kind: 'Input', props }) } as unknown as Kit++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+}++const words = (tree: unknown): string => flat(tree).flatMap(el => (el.kind === 'Text' && typeof el.props.children === 'string' ? [el.props.children as string] : el.kind === 'Button' && typeof el.props.label === 'string' ? [el.props.label] : [])).join('\n')+const press = (tree: unknown, key: string): void => {+ const found = flat(tree).find(el => el.kind === 'Button' && el.props.key === key)++ if (found === undefined) throw new Error(`no button ${key}`)+ ;(found.props.onPress as () => void)()+}+const inputOf = (tree: unknown): El | undefined => flat(tree).find(el => el.kind === 'Input')+const tick = (): Promise<void> => new Promise(resolve => setTimeout(resolve, 0))++const NOW = T0 + 600_000+const a = runOf('wf_a', BASE)+const b = runOf('wf_b', BASE.map(x => (x.id === 'ra1' ? { ...x, tokens: 250_000 } : x)))+const asked: (ActionSpec | null)[] = []+// the folders on the way exist; one file in them is taken+const stat = async (path: string) => (path === '/work/proj/.claude-flow/console/exports/taken.md' ? { size: 1, kind: 'file' } : path.startsWith('/work/proj/.claude-flow') && !path.endsWith('.md') ? { kind: 'dir' } : Promise.reject(new Error('ENOENT')))++function world(columns = 100) {+ const state = newState({})++ state.view = 'workflows'+ state.cwd = '/work/proj'+ state.wf.read = { runs: [a, b], root: '/x', capBytes: 1, skipped: 0, more: 0 }++ const host = { invalidate: () => undefined } as unknown as Host+ const runner = { ask: (spec: ActionSpec | null) => void asked.push(spec) }+ const act = { workflows: workflowsActions(state, host, runner as never) } as unknown as Actions+ const ctx: Ctx = { kit, state, nowMs: NOW, columns, pictures: new Map(), act }++ return { state, page: () => workflowsPage(ctx) }+}++beforeEach(() => {+ asked.length = 0+ resetFolds()+ resetReplays()+ resetCompare()+ resetExport()+ resetSavedLive()+ setExportFs({ stat })+})++describe('registration', () => {+ it('adds four board slots after the board, takes no hotkey and no other kind of slot', () => {+ world().page()++ expect(slotsFor('board').map(s => s.id)).toEqual(['replay', 'compare', 'export', 'saved'])+ expect(slotsFor('key')).toHaveLength(0)+ expect(slotsFor('action')).toHaveLength(0)+ expect(slotsFor('tab')).toHaveLength(0)+ })++ it('every slot is folded shut with a one-line summary until opened, and a narrow page still draws', () => {+ const w = world(46)+ const text = words(w.page())++ expect(text).toMatch(/Replay/)+ expect(text).toMatch(/moments in/)+ expect(text).toMatch(/1 other run of "demo-run"/)+ expect(text).not.toMatch(/step 0\//)+ })+})++describe('replay', () => {+ it('opens, steps forward and back, and the board follows the step', () => {+ const w = world()++ press(w.page(), 'wf-replay-fold')+ expect(words(w.page())).toMatch(/step 0\/6/)+ press(w.page(), 'wf-rp-next')+ press(w.page(), 'wf-rp-next')+ expect(words(w.page())).toMatch(/step 2\/6/)+ expect(words(w.page())).toMatch(/2 running/)+ press(w.page(), 'wf-rp-last')+ expect(words(w.page())).toMatch(/real final board/)+ press(w.page(), 'wf-rp-prev')+ expect(words(w.page())).toMatch(/step 5\/6/)+ press(w.page(), 'wf-rp-first')+ expect(words(w.page())).toMatch(/step 0\/6/)+ press(w.page(), 'wf-rp-faster')+ expect(words(w.page())).toMatch(/64x/)+ })++ it('says the console cannot rewind or message a run', () => {+ const w = world()++ press(w.page(), 'wf-replay-fold')+ expect(words(w.page())).toMatch(/cannot rewind, stop or message a Claude Code workflow/)+ })++ it('has nothing to replay for the ruflo swarm, and says so', () => {+ const w = world()++ w.state.wf.read = { runs: [], root: '/x', capBytes: 1, skipped: 0, more: 0 }+ w.state.snapshot = { swarm: null, agents: [{ id: 'a1', type: 'coder', status: 'busy' }] } as never+ expect(swarmRun(null, [{ id: 'a1', type: 'coder', status: 'busy' } as never], NOW)).not.toBeNull()+ expect(words(w.page())).toMatch(/live roster with no history/)+ })+})++describe('compare', () => {+ it('sets the run beside its twin, with the changed agent marked and a way to hide the rest', () => {+ const w = world()++ press(w.page(), 'wf-compare-fold')++ const text = words(w.page())++ expect(text).toMatch(/ A \w+[\s\S]*vs[\s\S]*B \w+/)+ expect(text).toMatch(/~ build:a/)+ expect(text).toMatch(/= review:a/)+ expect(text).toMatch(/1 changed/)+ press(w.page(), 'wf-cmp-only')+ expect(words(w.page())).not.toMatch(/= review:a/)+ expect(words(w.page())).toMatch(/~ build:a/)+ })+})++describe('export', () => {+ it('asks for a confirm-gated write at the default path, with the text on stdin', async () => {+ const w = world()++ press(w.page(), 'wf-export-fold')+ press(w.page(), 'wf-export-default')+ await tick()++ const spec = asked[0]++ expect(spec?.argv).toEqual(['dd', 'of=/work/proj/.claude-flow/console/exports/demo-run-wf_a.md', 'conv=excl', 'status=none'])+ expect(spec?.stdin).toMatch(/^# Workflow run: demo-run/)+ expect(spec?.declared).toBe('write')+ expect(words(w.page())).toMatch(/confirm below to write/)+ })++ it('refuses a path with .., outside the project, or already taken, and asks nothing', async () => {+ const w = world()++ press(w.page(), 'wf-export-fold')++ for (const [path, why] of [['../x.md', /\.\./], ['/etc/x.md', /outside the project/], ['.claude-flow/console/exports/taken.md', /already exists/]] as const) {+ ;(inputOf(w.page())?.props.onSubmit as (v: string) => void)(path)+ await tick()+ expect(words(w.page())).toMatch(why)+ }++ expect(asked).toHaveLength(0)+ })++ it('writes nothing when the host reader is not wired, since a link could not be ruled out', async () => {+ const w = world()++ setExportFs(null)+ press(w.page(), 'wf-export-fold')+ press(w.page(), 'wf-export-default')+ await tick()+ expect(asked).toHaveLength(0)+ expect(words(w.page())).toMatch(/not wired/)+ })++ it('never lets a credential in a label reach the spec', async () => {+ const w = world()+ const secret = 'sk-abcdefghijklmnopqrstuvwx'++ w.state.wf.read = { runs: [runOf('wf_s', [{ id: 's1', label: `go ${secret}`, phase: 'Build', at: 0, ms: 1 }])], root: '/x', capBytes: 1, skipped: 0, more: 0 }+ press(w.page(), 'wf-export-fold')+ press(w.page(), 'wf-export-default')+ await tick()+ expect(asked[0]?.stdin).not.toContain(secret)+ expect(JSON.stringify(asked[0])).not.toContain(secret)+ })+})++describe('saved views', () => {+ it('pins and unpins the run, lists the pin with a jump button, and shows where the file is', () => {+ const w = world()++ press(w.page(), 'wf-saved-fold')+ expect(words(w.page())).toMatch(/\.claude-flow\/console\/wf-views\.json/)+ press(w.page(), 'wf-saved-pin')+ expect(savedFor('/work/proj').saved.pins.map(p => p.runId)).toEqual(['wf_a'])+ expect(words(w.page())).toMatch(/Unpin this run/)+ press(w.page(), 'wf-saved-go-0')+ expect(w.state.wf.ui.run).toBe(0)+ press(w.page(), 'wf-saved-pin')+ expect(savedFor('/work/proj').saved.pins).toEqual([])+ })++ it('forgets only through the confirm card', () => {+ const w = world()++ press(w.page(), 'wf-saved-fold')+ press(w.page(), 'wf-saved-forget')+ expect(asked[0]).toMatchObject({ argv: ['rm', '-f', '--', '/work/proj/.claude-flow/console/wf-views.json'], declared: 'delete' })+ })++ it('says a pinned run that is no longer read is not among the runs', () => {+ const w = world()++ savedFor('/work/proj').saved.pins.push({ runId: 'wf_gone', name: 'old run', pinnedAtMs: 1 })+ press(w.page(), 'wf-saved-fold')+ expect(words(w.page())).toMatch(/old run · not among the runs read now/)+ })+})diff --git a/plugins/ruflo-console/tests/wf-replay.spec.ts b/plugins/ruflo-console/tests/wf-replay.spec.tsnew file mode 100644index 0000000000..d78915ed5e--- /dev/null+++ b/plugins/ruflo-console/tests/wf-replay.spec.ts@@ -0,0 +1,179 @@+/**+ * Replay of a finished run (ADR-461): the timeline from the agents' own start and end moments, the board re-derived at every step,+ * and the cursor (step, jump, phase, play, speed). Pure and fast. Run with+ * npx vitest run plugins/ruflo-console/tests/wf-replay.spec.ts --testTimeout=30000+ */+import { describe, expect, it } from 'vitest'++import { boardAt, buildTimeline, describeStep, isPlaying, jumpReplay, newReplay, offsetOf, phaseSteps, SPEEDS, stepNow, stepReplay } from '../hooks/data/wf-replay'+import { swarmRun } from '../hooks/data/workflows'+import { BASE, runOf } from './fixtures/wf-runs'++const run = runOf('wf_a', BASE)+const tl = buildTimeline(run)+const NOW = 5_000_000++describe('timeline', () => {+ it('orders start and end moments, an end before a start at the same instant', () => {+ expect(tl.why).toBeNull()+ expect(tl.events.map(e => `${e.kind}:${e.label}`)).toEqual(['start:build:a', 'start:build:b', 'end:build:b', 'end:build:a', 'start:review:a', 'end:review:a'])+ expect(tl.t1 - tl.t0).toBe(90_000)+ })++ it('leaves out an agent with no start time, or a finished one with no span, and counts it', () => {+ const whole = runOf('wf_odd', [...BASE, { id: 'x1', label: 'nostart', phase: 'Build' }, { id: 'x2', label: 'nospan', phase: 'Build', at: 3 }])+ // buildRun always derives a span for an agent that has a start; a hand-made agent without one is the case being tested.+ const odd = { ...whole, phases: whole.phases.map(p => ({ ...p, agents: p.agents.map(a => (a.id === 'x2' ? { ...a, elapsedMs: undefined } : a)) })) }+ const t = buildTimeline(odd)++ expect(t.untimed.sort()).toEqual(['x1', 'x2'])+ expect(t.events).toHaveLength(6)+ expect(boardAt(odd, t, 6).total).toBe(3)+ })++ it('says why there is nothing to replay: the swarm, an empty run, a run with no times', () => {+ const swarm = swarmRun(null, [{ id: 'a1', type: 'coder', status: 'busy' } as never], NOW)++ expect(buildTimeline(swarm as never).why).toMatch(/swarm/)+ expect(buildTimeline(runOf('wf_e', [])).why).toMatch(/no agents/)+ expect(buildTimeline(runOf('wf_n', [{ id: 'n1', label: 'n', phase: 'Build' }])).why).toMatch(/no order to replay/)+ })+})++describe('the board at a step', () => {+ it('starts with every agent queued and no tokens', () => {+ const b = boardAt(run, tl, 0)++ expect(b.phases.flatMap(p => p.agents).every(a => a.state === 'queued' && a.tokens === undefined)).toBe(true)+ expect(b.running).toBe(0)+ expect(b.totalTokens).toBeNull()+ expect(b.state).toBe('running')+ })++ it('shows a running agent with time measured to the step and tokens n/a, then its final figures once it ends', () => {+ const mid = boardAt(run, tl, 2)+ const a = mid.phases[0]?.agents.find(x => x.label === 'build:a')++ expect(mid.running).toBe(2)+ expect(a).toMatchObject({ state: 'running', elapsedMs: 0 })+ expect(a?.tokens).toBeUndefined()++ const after = boardAt(run, tl, 3)++ expect(after.failed).toBe(1)+ expect(after.totalTokens).toBe(1200)+ expect(after.phases[0]?.agents.find(x => x.label === 'build:b')).toMatchObject({ state: 'failed', tokens: 1200 })+ expect(boardAt(run, tl, 5).phases[1]?.agents[0]).toMatchObject({ state: 'running', elapsedMs: 0 })+ expect(boardAt(run, tl, 5).phases[0]?.agents.find(x => x.label === 'build:a')).toMatchObject({ state: 'done', tokens: 180_000 })+ })++ it('ends on the real board: same states, counts, totals and state', () => {+ const last = boardAt(run, tl, tl.events.length)++ expect(last.phases.map(p => p.agents.map(a => [a.id, a.state]))).toEqual(run.phases.map(p => p.agents.map(a => [a.id, a.state])))+ expect(last).toMatchObject({ done: run.done, failed: run.failed, running: 0, total: run.total, totalTokens: run.totalTokens, state: run.state, durationMs: run.durationMs })+ })++ it('is the same board whichever way the cursor arrived (forward, back, jump)', () => {+ const direct = JSON.stringify(boardAt(run, tl, 3))+ let ui = newReplay()++ for (const c of ['last', 'first', 'next', 'next', 'next', 'next', 'prev'] as const) ui = stepReplay(ui, tl, c, NOW)++ expect(stepNow(ui, tl, NOW)).toBe(3)+ expect(JSON.stringify(boardAt(run, tl, stepNow(ui, tl, NOW)))).toBe(direct)+ expect(JSON.stringify(boardAt(run, tl, 3))).toBe(direct)+ })++ it('clamps a step outside the run', () => {+ expect(boardAt(run, tl, -4).done).toBe(0)+ expect(boardAt(run, tl, 99).done).toBe(run.done)+ })+})++describe('the cursor', () => {+ it('steps, clamps at both ends and describes where it is', () => {+ let ui = stepReplay(newReplay(), tl, 'prev', NOW)++ expect(stepNow(ui, tl, NOW)).toBe(0)+ expect(describeStep(tl, 0)).toMatch(/before the first/)+ ui = stepReplay(ui, tl, 'next', NOW)+ expect(describeStep(tl, 1)).toBe('build:a started (Build)')+ for (let i = 0; i < 20; i += 1) ui = stepReplay(ui, tl, 'next', NOW)+ expect(stepNow(ui, tl, NOW)).toBe(6)+ expect(describeStep(tl, 6)).toBe('review:a ended (Review)')+ })++ it('jumps by phase: the step where the next phase first starts, back to the start', () => {+ expect(phaseSteps(tl)).toEqual([1, 5])+ let ui = stepReplay(newReplay(), tl, 'next-phase', NOW)++ expect(stepNow(ui, tl, NOW)).toBe(1)+ ui = stepReplay(ui, tl, 'next-phase', NOW)+ expect(stepNow(ui, tl, NOW)).toBe(5)+ ui = stepReplay(ui, tl, 'next-phase', NOW)+ expect(stepNow(ui, tl, NOW)).toBe(6)+ ui = stepReplay(stepReplay(ui, tl, 'prev-phase', NOW), tl, 'prev-phase', NOW)+ expect(stepNow(ui, tl, NOW)).toBe(1)+ expect(stepNow(stepReplay(ui, tl, 'prev-phase', NOW), tl, NOW)).toBe(0)+ })++ it('jumps along the run by fraction, landing on the last step at or before it', () => {+ expect(stepNow(jumpReplay(newReplay(), tl, 0), tl, NOW)).toBe(2) // both start at +0+ expect(stepNow(jumpReplay(newReplay(), tl, 0.5), tl, NOW)).toBe(3) // +5s is before +45s; +60s is after+ expect(stepNow(jumpReplay(newReplay(), tl, 1), tl, NOW)).toBe(6)+ expect(stepNow(jumpReplay(newReplay(), tl, Number.NaN), tl, NOW)).toBe(2)+ })++ it('plays on the wall clock at its speed and stops at the end', () => {+ const base = { ...newReplay(), speed: 4 }+ const playing = stepReplay(base, tl, 'play', NOW)++ expect(playing.playFromMs).toBe(NOW)+ // the two agents that start at +0 have started the moment the clock does+ expect(stepNow(playing, tl, NOW)).toBe(2)+ // 2s of wall clock at 4x is 8s of run time: past the +5s end of build:b (steps 1..3)+ expect(stepNow(playing, tl, NOW + 2000)).toBe(3)+ expect(isPlaying(playing, tl, NOW + 2000)).toBe(true)+ // 30s at 4x is 120s: everything has happened+ expect(stepNow(playing, tl, NOW + 30_000)).toBe(6)+ expect(isPlaying(playing, tl, NOW + 30_000)).toBe(false)+ })++ it('pauses where it is, and play at the end starts again from the top', () => {+ const playing = stepReplay({ ...newReplay(), speed: 4 }, tl, 'play', NOW)+ const paused = stepReplay(playing, tl, 'play', NOW + 2000)++ expect(paused.playFromMs).toBeNull()+ expect(stepNow(paused, tl, NOW + 99_000)).toBe(3)++ const end = stepReplay(newReplay(), tl, 'last', NOW)+ const again = stepReplay(end, tl, 'play', NOW)++ expect(stepNow(again, tl, NOW)).toBe(2) // from the top: the +0 starts are at once+ expect(again.step).toBe(0)+ expect(again.playFromMs).toBe(NOW)+ })++ it('a manual step while playing pauses it', () => {+ const playing = stepReplay(newReplay(), tl, 'play', NOW)++ expect(stepReplay(playing, tl, 'next', NOW + 1).playFromMs).toBeNull()+ })++ it('changes speed within the offered speeds only, and keeps its place while playing', () => {+ let ui = newReplay()++ for (let i = 0; i < 10; i += 1) ui = stepReplay(ui, tl, 'faster', NOW)+ expect(ui.speed).toBe(SPEEDS[SPEEDS.length - 1])+ for (let i = 0; i < 10; i += 1) ui = stepReplay(ui, tl, 'slower', NOW)+ expect(ui.speed).toBe(SPEEDS[0])++ const playing = stepReplay({ ...newReplay(), speed: 4 }, tl, 'play', NOW)+ const quicker = stepReplay(playing, tl, 'faster', NOW + 2000)++ expect(quicker.speed).toBe(16)+ expect(stepNow(quicker, tl, NOW + 2000)).toBe(3)+ expect(offsetOf(tl, 3)).toBe(5000)+ })+})diff --git a/plugins/ruflo-console/tests/wf-saved.spec.ts b/plugins/ruflo-console/tests/wf-saved.spec.tsnew file mode 100644index 0000000000..9ea6e6d7f1--- /dev/null+++ b/plugins/ruflo-console/tests/wf-saved.spec.ts@@ -0,0 +1,257 @@+/**+ * Saved views and pins (ADR-461): the file's schema and how it survives corruption, the cursor by name, pins, and the live+ * load/restore/write with the host faked. Run with+ * npx vitest run plugins/ruflo-console/tests/wf-saved.spec.ts --testTimeout=30000+ */+import { beforeEach, describe, expect, it } from 'vitest'++import { captureDrill, decodeSaved, emptySaved, encodeSaved, isPinned, MAX_FILTERS, MAX_PINS, pinsIn, restoreDrill, SAVED_MAX_BYTES, SAVED_VERSION, setFilter, setSearch, togglePin } from '../hooks/data/wf-saved'+import { newWfUi } from '../hooks/data/workflows-nav'+import { newState } from '../hooks/state'+import { forgetSpec, resetSavedLive, SAVE_GAP_MS, savedFor, savedPathOf, syncSavedViews, updateSaved } from '../hooks/wf-saved-live'+import { BASE, runOf } from './fixtures/wf-runs'++const KEY = 'sk-abcdefghijklmnopqrstuvwx'+const a = runOf('wf_a', BASE)+const b = runOf('wf_b', BASE)+const other = runOf('wf_o', BASE, {}, 'other-flow')++describe('decode', () => {+ it('reads defaults for no file, and names the problem for bad ones', () => {+ expect(decodeSaved(null)).toEqual({ saved: emptySaved(), problem: null, isForeign: false })+ expect(decodeSaved('{not json')).toMatchObject({ saved: emptySaved(), problem: expect.stringMatching(/not valid JSON/), isForeign: false })+ expect(decodeSaved('[1,2]').problem).toMatch(/not an object/)+ expect(decodeSaved('null').problem).toMatch(/not an object/)+ expect(decodeSaved(JSON.stringify({ version: 'x' })).problem).toMatch(/unknown version/)+ })++ it('leaves a file from a newer console alone', () => {+ const d = decodeSaved(JSON.stringify({ version: SAVED_VERSION + 1, drill: { runId: 'wf_a' } }))++ expect(d.isForeign).toBe(true)+ expect(d.saved).toEqual(emptySaved())+ expect(d.problem).toMatch(/newer console/)+ })++ it('keeps only valid fields, cleaned and capped', () => {+ const d = decodeSaved(+ JSON.stringify({+ version: 1,+ savedAtMs: 5,+ drill: { runId: '../bad id', runName: `n ${KEY}\u001b[2J`, phase: 'ab '.repeat(200), agent: 7, column: 'sideways', isInspecting: 'yes', tab: 'Bad Tab!' },+ filters: { state: 'failed', 'Bad Key': 'x', ok: 'y '.repeat(300), n: 4 },+ search: `find ${KEY}`,+ pins: [{ runId: 'wf_a', name: 'a', pinnedAtMs: 1 }, { runId: 'wf_a', name: 'dup' }, { runId: 'no good', name: 'n' }, { runId: 'wf_c' }, 'x'],+ }),+ )++ expect(d.problem).toBeNull()+ expect(d.saved.drill).toEqual({ runName: expect.not.stringContaining(KEY), phase: 'ab '.repeat(200).slice(0, 80), column: 'phases', isInspecting: false, tab: 'detail' })+ expect(JSON.stringify(d.saved)).not.toContain(KEY)+ // eslint-disable-next-line no-control-regex+ expect(/[\u0000-\u001f]/.test(JSON.stringify(d.saved))).toBe(false)+ expect(Object.keys(d.saved.filters).sort()).toEqual(['ok', 'state'])+ expect(d.saved.filters.ok).toHaveLength(80)+ expect(d.saved.pins).toEqual([{ runId: 'wf_a', name: 'a', pinnedAtMs: 1 }])+ })++ it('caps pins and filters', () => {+ const pins = Array.from({ length: 60 }, (_, i) => ({ runId: `wf_${i}`, name: `n${i}` }))+ const filters = Object.fromEntries(Array.from({ length: 30 }, (_, i) => [`f${i}`, 'v']))+ const d = decodeSaved(JSON.stringify({ version: 1, pins, filters }))++ expect(d.saved.pins).toHaveLength(MAX_PINS)+ expect(Object.keys(d.saved.filters)).toHaveLength(MAX_FILTERS)+ })++ it('round-trips what it encodes, and a corrupt tail loses nothing it did not have', () => {+ const saved = { ...emptySaved(), drill: captureDrill({ ...newWfUi(), phase: 1, agent: 0, column: 'agents', isInspecting: true }, [a], 'detail'), filters: { state: 'failed' }, search: 'review', pins: [{ runId: 'wf_a', name: 'demo-run', pinnedAtMs: 9 }] }+ const text = encodeSaved(saved, 1234)++ expect(text.length).toBeLessThan(SAVED_MAX_BYTES)+ expect(decodeSaved(text).saved).toEqual({ ...saved, savedAtMs: 1234 })+ expect(decodeSaved(text.slice(0, text.length - 12)).problem).toMatch(/not valid JSON/)+ })+})++describe('the cursor by name', () => {+ const ui = { ...newWfUi(), phase: 1, agent: 0, column: 'agents' as const, isInspecting: true }++ it('captures names, not indexes', () => {+ expect(captureDrill(ui, [a, b], 'detail')).toMatchObject({ runId: 'wf_a', runName: 'demo-run', phase: 'Review', agent: 'review:a', column: 'agents', isInspecting: true })+ expect(captureDrill(ui, [], 'detail')).toBeNull()+ })++ it('puts the cursor back on the same run even when the list shifted', () => {+ const drill = captureDrill(ui, [a, b], 'detail')+ const back = restoreDrill(drill, [other, b, a], newWfUi())++ expect(back).toMatchObject({ found: 'exact', ui: { run: 2, phase: 1, agent: 0, column: 'agents', isInspecting: true } })+ })++ it('falls to the newest run of the same name when the run is gone, and leaves the cursor when neither exists', () => {+ const drill = captureDrill(ui, [a], 'detail')++ expect(restoreDrill(drill, [other, b], newWfUi())).toMatchObject({ found: 'name', ui: { run: 1, phase: 1 } })+ expect(restoreDrill(drill, [other], { ...newWfUi(), run: 0 })).toMatchObject({ found: 'gone', ui: newWfUi() })+ expect(restoreDrill(null, [a], newWfUi())).toBeNull()+ })++ it('does not restore an inspector onto a phase or agent that is not there', () => {+ const drill = { ...captureDrill(ui, [a], 'detail'), phase: 'Gone', agent: 'nobody' }+ const back = restoreDrill(drill as never, [a], newWfUi())++ expect(back?.ui.phase).toBe(0)+ expect(back?.ui.agent).toBe(0)+ })+})++describe('pins and filters', () => {+ it('toggles a pin, refuses past the cap without dropping one, and lists where each run now is', () => {+ let s = emptySaved()++ s = togglePin(s, a, 7).saved+ expect(isPinned(s, 'wf_a')).toBe(true)+ expect(pinsIn(s, [b, a])).toMatchObject([{ index: 1, run: { id: 'wf_a' } }])+ expect(pinsIn(s, [b])).toMatchObject([{ index: null, run: null }])+ s = togglePin(s, a, 8).saved+ expect(s.pins).toEqual([])++ for (let i = 0; i < MAX_PINS; i += 1) s = togglePin(s, runOf(`wf_${i}`, BASE), i).saved++ const full = togglePin(s, runOf('wf_new', BASE), 99)++ expect(full.saved.pins).toHaveLength(MAX_PINS)+ expect(full.said).toMatch(/pinned already/)+ expect(full.saved.pins.some(p => p.runId === 'wf_0')).toBe(true)+ })++ it('sets and clears a filter and the search, under the file\'s rules', () => {+ let s = setFilter(emptySaved(), 'state', 'failed')++ expect(s.filters).toEqual({ state: 'failed' })+ expect(setFilter(s, 'Bad Key', 'x')).toEqual(s)+ expect(setFilter(s, 'state', '').filters).toEqual({})+ expect(setSearch(s, ` q ${KEY}`).search).not.toContain(KEY)+ for (let i = 0; i < 20; i += 1) s = setFilter(s, `f${i}`, 'v')+ expect(Object.keys(s.filters)).toHaveLength(MAX_FILTERS)+ })+})++describe('live: load, restore, write', () => {+ const CWD = '/work/proj'+ const PATH = savedPathOf(CWD)++ function world(files: Record<string, string> = {}) {+ const writes: { argv: readonly string[]; stdin: string | undefined }[] = []+ let exit = 0+ const fs = {+ read: async (path: string) => files[path] ?? Promise.reject(new Error('ENOENT')),+ stat: async (path: string) => (files[path] === undefined ? Promise.reject(new Error('ENOENT')) : { mtimeMs: 1, size: files[path].length, kind: 'file' }),+ list: async () => [],+ }+ const host = { fs, run: async (argv: readonly string[], _t: number, stdin?: string) => (writes.push({ argv, stdin }), { exitCode: exit, stdout: '', stderr: '' }) } as never+ const state = newState()++ state.cwd = CWD+ state.view = 'workflows'+ state.wf.read = { runs: [a, b], root: '/x', capBytes: 1, skipped: 0, more: 0 }++ return { writes, host, state, files, fail: () => void (exit = 1) }+ }++ beforeEach(() => resetSavedLive())++ it('puts the cursor back from the file once, then writes a move after the gap', async () => {+ const w = world({ [PATH]: encodeSaved({ ...emptySaved(), drill: captureDrill({ ...newWfUi(), run: 1, phase: 1 }, [a, b], 'detail') }, 1) })++ await syncSavedViews(w.state, w.host, 10_000)+ expect(w.state.wf.ui).toMatchObject({ run: 1, phase: 1 })+ expect(savedFor(CWD).restored).toBe('exact')+ expect(w.writes).toHaveLength(0)++ await syncSavedViews(w.state, w.host, 10_100)+ expect(w.writes).toHaveLength(0) // nothing moved++ w.state.wf.ui = { ...w.state.wf.ui, run: 0, phase: 0 }+ await syncSavedViews(w.state, w.host, 10_200)+ expect(w.writes).toHaveLength(1)+ expect(w.writes[0]?.argv).toEqual(['install', '-D', '-m', '0644', '/dev/stdin', '--', PATH]) // no folder yet+ expect(decodeSaved(w.writes[0]?.stdin ?? '').saved.drill).toMatchObject({ runId: 'wf_a', phase: 'Build' })++ w.files[`${CWD}/.claude-flow/console`] = ''+ w.state.wf.ui = { ...w.state.wf.ui, phase: 1 }+ await syncSavedViews(w.state, w.host, 10_200 + SAVE_GAP_MS - 1)+ expect(w.writes).toHaveLength(1) // inside the gap+ await syncSavedViews(w.state, w.host, 10_200 + SAVE_GAP_MS)+ expect(w.writes).toHaveLength(2)+ expect(w.writes[1]?.argv).toEqual(['dd', `of=${PATH}`, 'status=none']) // the folder exists now+ })++ it('never writes over a file from a newer console, nor changes it', async () => {+ const w = world({ [PATH]: JSON.stringify({ version: 99 }) })++ await syncSavedViews(w.state, w.host, 1000)+ w.state.wf.ui = { ...w.state.wf.ui, phase: 1 }+ updateSaved(CWD, s => setSearch(s, 'x'))+ await syncSavedViews(w.state, w.host, 99_000)+ expect(w.writes).toHaveLength(0)+ expect(savedFor(CWD).isForeign).toBe(true)+ expect(savedFor(CWD).saved.search).toBe('')+ })++ it('survives a corrupt file, and a file too large to read, replacing them on the next change', async () => {+ const bad = world({ [PATH]: '{{{' })++ await syncSavedViews(bad.state, bad.host, 1000)+ expect(savedFor(CWD).problem).toMatch(/not valid JSON/)+ await syncSavedViews(bad.state, bad.host, 2000)+ expect(bad.writes.length).toBe(1)++ resetSavedLive()++ const huge = world({ [PATH]: ' '.repeat(SAVED_MAX_BYTES + 10) })++ await syncSavedViews(huge.state, huge.host, 1000)+ expect(savedFor(CWD).problem).toMatch(/over 64 kB/)+ })++ it('keeps a change when the write fails, and retries it after the gap', async () => {+ const w = world()++ await syncSavedViews(w.state, w.host, 1000)+ w.fail()+ w.state.wf.ui = { ...w.state.wf.ui, phase: 1 }+ await syncSavedViews(w.state, w.host, 5000)+ expect(savedFor(CWD)).toMatchObject({ isDirty: true, error: expect.stringMatching(/exited 1/) })+ await syncSavedViews(w.state, w.host, 5000 + SAVE_GAP_MS)+ expect(w.writes).toHaveLength(2)+ })++ it('does not touch the page when the host throws', async () => {+ const w = world()+ const boom = { fs: { read: async () => { throw new Error('x') }, stat: async () => { throw new Error('x') }, list: async () => [] }, run: async () => { throw new Error('refused') } } as never++ await expect(syncSavedViews(w.state, boom, 1000)).resolves.toBeUndefined()+ await expect(syncSavedViews(w.state, boom, 9000)).resolves.toBeUndefined()+ })++ it('forgetting is a confirm-gated delete of that one file, then stops auto-saving until something is pinned', async () => {+ const w = world()++ await syncSavedViews(w.state, w.host, 1000)+ updateSaved(CWD, s => togglePin(s, a, 1).saved)++ const spec = forgetSpec(CWD)++ expect(spec).toMatchObject({ argv: ['rm', '-f', '--', PATH], declared: 'delete' })+ spec.onOutput?.('')+ expect(savedFor(CWD).saved).toEqual(emptySaved())+ w.state.wf.ui = { ...w.state.wf.ui, phase: 1 }+ await syncSavedViews(w.state, w.host, 50_000)+ expect(w.writes).toHaveLength(0)+ updateSaved(CWD, s => togglePin(s, b, 2).saved)+ await syncSavedViews(w.state, w.host, 60_000)+ expect(w.writes).toHaveLength(1)+ })+})diff --git a/v3/docs/adr/ADR-461-workflows-replay-compare-export-saved-views.md b/v3/docs/adr/ADR-461-workflows-replay-compare-export-saved-views.mdnew file mode 100644index 0000000000..35aa98aa05--- /dev/null+++ b/v3/docs/adr/ADR-461-workflows-replay-compare-export-saved-views.md@@ -0,0 +1,92 @@+# ADR 461: Workflows page - replay, compare, export and saved views++Status: Accepted++Date: 2026-10-05++Builds on: ADR-458 (the page and its data), ADR-464 (wiring and the slot seams), ADR-453 (confirm-gated verbs)++## 1. Context++The Workflows page shows a run as it is now. People also want to see how a finished run went (what ran when), to set one run beside+another of the same workflow, to keep a summary outside the console, and to find the page where they left it. All four have to use only+what the run folders hold, and none may reach into the shared page files (ADR-464's seams exist for this).++What the files hold limits the design. A run's journal has **no timestamps**. The only moments a run records are each agent's `startedAt`+and, for an agent that ended, its `durationMs` (a run record), or the first and last timestamps of its transcript. Tokens are recorded+once, at the end. There is no per-run cost anywhere in the files. The host's `fs` is read-only, the console may spawn only fixed argv, and+smoke step 8 forbids `sh -c` in the hooks.++## 2. Decision++Four features, each a pure `data/` module with a thin board slot over it, all registered by one import (`views/wf-replay.ts` imports the+other three), so the merge owner adds one line to `views/wf-register.ts`. Each slot is a board slot folded shut by default (one line and an+open button), so the page stays short. No hotkey is taken: the slots register no key, action or tab slot.++**Replay** (`data/wf-replay.ts`, `views/wf-replay.ts`). The timeline is the agents' own start and end moments, ordered by time (an end before+a start at the same instant). A step is one event; `boardAt(run, timeline, step)` re-derives the whole board from the run's agents with+`groupPhases`, so the replayed board is the page's own shape and step N is the same board however the cursor reached it. The last step is+the real board (same states, counts, totals). Not invented: a running agent shows tokens n/a (its final figure is not known mid-run) and its+time is measured to the step; an agent with no start time, or one that ended without a span, is left off and counted on the page; the ruflo+swarm has no history and says so. The cursor is step, jump (to a fraction, to the next or previous phase start), play/pause and a speed of+1, 4, 16, 64 or 256 times. Play is derived from the wall clock at render (`stepNow`), so it needs no timer and cannot run on while paused;+it advances when the page draws (each refresh tick or interaction), which the page says.++**Compare** (`data/wf-compare.ts`, `views/wf-compare.ts`). Only runs with the same workflow name compare. Agents pair by phase and label (the+Nth of a label pairs with the Nth). Marks: `=` same, `~` changed (state or model differs, tokens differ by at least 10%, time by at least+25%), `+` only in B, `-` only in A. A figure either side lacks is n/a and never a change. Totals, counts and notes (a token floor, a run with+no record, differing result text) are shown. The thresholds are exported constants with boundary tests.++**Export** (`data/wf-export.ts`, `data/wf-file.ts`, `views/wf-export.ts`). A markdown summary: phases, agents, tokens, time, results,+provenance; cost only when a source is wired (`setExportCostSource`), else `n/a`. Every free-text field goes through `cleanText` (control+characters out, credential shapes masked) and has table characters escaped; output is capped at 200 kB with a visible cut line. The path must+resolve under the project or the scratchpad (`setExportRoots`), with no `..`, no backslash, no control character, a `.md` name, no link on+the way down (stat per component) and no file already there. The write is a confirm-card `ActionSpec` (`declared: 'write'`): fixed argv+`dd of=<path> conv=excl status=none` (no shell; `conv=excl` fails rather than replace) where the folder exists, else GNU+`install -D -m 0644 /dev/stdin -- <path>`; the text is stdin. Without a wired host reader (`setExportFs`) nothing is written, since a link+could not be ruled out.++**Saved views and pins** (`data/wf-saved.ts`, `wf-saved-live.ts`, `views/wf-saved.ts`). One file, `.claude-flow/console/wf-views.json`,+version 1, at most 64 kB: the cursor by run id, run name, phase title and agent label (so a new run does not move it), filters (at most 8,+set through `updateSaved` by any feature), the search, and up to 20 pinned runs. Decoding never throws and trusts nothing: bad JSON, a+non-object or an unknown version gives defaults with the problem named (and the next change replaces the file); a version **newer** than+this console's is `isForeign` and is neither read nor written. Strings are cleaned, masked and capped on the way in and out. The live half+reads once per project, restores the cursor once the first read has runs (exact run, else the newest of the same name, else leaves it), and+writes when something changed, at most every 2 s, one at a time, a failure keeping the change to retry. The write is the console's own+state file, silent like the other persisted console state, fixed argv (`dd of=` or `install -D`, text on stdin). Removing it is+`rm -f -- <path>` behind the confirm card, after which the cursor is not saved again until something is pinned.++## 3. Consequences++- The page gains four folded sections and no hotkey. Keyboard users reach them with the page's focus ring and Enter; a hotkey would have to+ take one of the letters the tabs already own.+- The saved file creates `.claude-flow/console/` in a project on the first page open. It holds a cursor and names, never run content.+- `install -D` is GNU: on macOS an export to a folder that does not exist yet fails with the tool's own message (name an existing folder).+- Replay resolution is the agents' start and end moments, no finer: a long agent shows as running through its whole span.+- The merge owner must wire four calls (section 5). Until they are made the page still draws; saved views simply do not load or save, and an+ export is refused with a plain reason.++## 4. Test and benchmark plan++Specs in `plugins/ruflo-console/tests/`: `wf-replay.spec.ts` (timeline order and ties, untimed agents, board at every step, scrub+determinism, phase jumps, play on the wall clock, speed clamp), `wf-compare.spec.ts` (matching, marks, both thresholds at their boundary,+unknown figures), `wf-export.spec.ts` (markdown, masking, escaping, cap, path rules, link and existing-file checks, argv has no shell, a real+`dd conv=excl` refusing to overwrite), `wf-saved.spec.ts` (schema, corruption, foreign version, cursor by name, pins, caps, live load,+restore, write gap, failure retry, forget), `wf-replay-views.spec.ts` (registration without a hotkey, fold, the buttons, export through the+confirm card, saved views). Mutation checks flip the end-before-start tie order, the mid-run token carry, the phase jump boundary, both+compare thresholds, the `..` check, the link check, the cell mask, the version gate, the pin cap, the save-gap boundary, the foreign-file+write guards and the unwired-fs refusal: each fails a test. Performance: the timeline is cached per run signature and `boardAt` is linear in+agents; the board draws at most 22 rows. `scripts/bench-swarmui.mjs` is the existing page bench; no new bench is added.++## 5. Wiring (merge owner)++1. `views/wf-register.ts`: `import './wf-replay'`.+2. `controller.ts` init (once, where `host` exists): `setExportFs(host.fs)`; where the scratchpad is known, `setExportRoots(dir)`.+3. After `refreshWorkflows(...)` in `wf-live.ts` or its call sites (open, dump, the refresh tick): `await syncSavedViews(state, host)`.+4. Optional: `setExportCostSource(run => ...)` once a per-run cost source exists; features that filter or search call+ `updateSaved(cwd, s => setFilter(s, key, value))`.++## 6. Rollback++Remove the import line from `views/wf-register.ts`: the page returns to the board alone and nothing else changes. `.claude-flow/console/`+may be deleted by hand or with "Forget saved views"; exports are ordinary files. No other file was edited.