Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

perf(console): memoize transcript parses and bound page cells; add bench-swarmui (ADR-458)

ruv2169b620b970
diff --git a/plugins/ruflo-console/hooks/data/workflows-read.ts b/plugins/ruflo-console/hooks/data/workflows-read.ts
index b9ce599e0d..3dbb8bce7e 100644
--- a/plugins/ruflo-console/hooks/data/workflows-read.ts
+++ b/plugins/ruflo-console/hooks/data/workflows-read.ts
@@ -6,7 +6,7 @@
* its transcripts are not read.
*/
import { readBounded, under, type ReadCache, type ReaderFs } from './files'
-import { buildRun, type RunInput, type WfRun } from './workflows'
+import { buildRun, parseTranscript, type RunInput, type TranscriptFacts, type WfRun } from './workflows'
/** The engine refuses files over 4 MiB; below this a transcript is read whole. */
export const TRANSCRIPT_CAP = 3_000_000
@@ -23,6 +23,29 @@ export type WorkflowRuns = { runs: WfRun[]; /** The project's folder under the c
/** Claude Code's folder name for a project: every character that is not a letter or digit becomes `-`. */
export const slugOf = (cwd: string): string => cwd.replace(/[^A-Za-z0-9]/g, '-')
+/**
+ * What each transcript parsed to, by path. A refresh re-reads every run on a timer; JSON.parse of the same unchanged
+ * transcripts was the whole cost of it (bench-swarmui.mjs: ~170 ms of ~170 ms at 6 runs x 60 agents). The read cache hands back
+ * the same string while a file is unchanged, so the text itself is the key's check. Bounded, oldest out.
+ */
+const PARSED_MAX = MAX_RUNS * MAX_AGENTS * 2
+const parsed = new Map<string, { text: string; isTail: boolean; facts: TranscriptFacts }>()
+
+function factsOf(path: string, text: string, isTail: boolean): TranscriptFacts {
+ const held = parsed.get(path)
+
+ if (held !== undefined && held.isTail === isTail && held.text === text) return held.facts
+
+ const facts = parseTranscript(text, isTail)
+
+ parsed.delete(path)
+ parsed.set(path, { text, isTail, facts })
+
+ if (parsed.size > PARSED_MAX) parsed.delete(parsed.keys().next().value as string)
+
+ return facts
+}
+
const safeList = (fs: ReaderFs, path: string) => fs.list(path).catch(() => [] as Awaited<ReturnType<ReaderFs['list']>>)
export async function readWorkflowRuns(fs: WorkflowFs, cache: ReadCache, options: { configDir: string | null; cwd: string; nowMs: number; maxRuns?: number }): Promise<WorkflowRuns> {
@@ -68,7 +91,7 @@ export async function readWorkflowRuns(fs: WorkflowFs, cache: ReadCache, options
if (transcript === null) skipped.push(path)
}
- return [agentId, { meta, transcript, isTail, path }] as const
+ return [agentId, { meta, transcript, isTail, path, ...(transcript !== null && { facts: factsOf(path, transcript, isTail) }) }] as const
}),
),
)
diff --git a/plugins/ruflo-console/hooks/data/workflows.ts b/plugins/ruflo-console/hooks/data/workflows.ts
index 9f6bb25fe9..801c605417 100644
--- a/plugins/ruflo-console/hooks/data/workflows.ts
+++ b/plugins/ruflo-console/hooks/data/workflows.ts
@@ -258,7 +258,7 @@ export type RunInput = {
dir?: string
journal: string | null
/** agentId → meta file text, transcript text (and whether it is a tail), and its path. */
- agents: ReadonlyMap<string, { meta: string | null; transcript: string | null; isTail: boolean; path: string }>
+ agents: ReadonlyMap<string, { meta: string | null; transcript: string | null; isTail: boolean; path: string; /** What `parseTranscript` already made of this very text, where the reader kept it. */ facts?: TranscriptFacts }>
record: string | null
script: string | null
nowMs: number
@@ -282,7 +282,7 @@ export function buildRun(input: RunInput): WfRun {
const r = fromRecord.get(id)
const source = input.agents.get(id)
const meta = parseAgentMeta(source?.meta ?? null)
- const facts = source === undefined ? null : parseTranscript(source.transcript, source.isTail)
+ const facts = source === undefined ? null : (source.facts ?? parseTranscript(source.transcript, source.isTail))
const startedMs = r?.startedMs ?? (source?.isTail === true ? undefined : facts?.firstMs)
const lastSeen = facts?.lastMs ?? input.lastActivityMs
const hasResult = j?.hasResult === true
diff --git a/plugins/ruflo-console/hooks/views/workflows.ts b/plugins/ruflo-console/hooks/views/workflows.ts
index 79eca0de59..13f5faacdb 100644
--- a/plugins/ruflo-console/hooks/views/workflows.ts
+++ b/plugins/ruflo-console/hooks/views/workflows.ts
@@ -144,19 +144,25 @@ export function workflowsView(ctx: Ctx, model: WorkflowsModel | null, ui: WfUi,
rows.push(rule(ctx, 'Phases', phase === null ? '' : `${phase.title}${phase.detail === undefined ? '' : ` · ${clip(phase.detail, 40)}`}`))
- const phases = run.phases.map((entry, i) => phaseCell(ctx, entry, i, { isHere: i === here.ui.phase && here.ui.column === 'phases', isCurrent: i === current, width: left }))
- const agents = (phase?.agents ?? []).map((entry, i) => agentCell(ctx, entry, i === here.ui.agent && here.ui.column === 'agents', right))
+ // Cells are built for the rows that are drawn only: a run can name thousands of agents, and a frame must not scale with them.
+ const rowsMax = 14
+ const phaseTotal = run.phases.length
+ const agentList = phase?.agents ?? []
+ const phases = run.phases.slice(0, rowsMax).map((entry, i) => phaseCell(ctx, entry, i, { isHere: i === here.ui.phase && here.ui.column === 'phases', isCurrent: i === current, width: left }))
+ const agents = agentList.slice(0, rowsMax).map((entry, i) => agentCell(ctx, entry, i === here.ui.agent && here.ui.column === 'agents', right))
if (run.phases.length === 0) rows.push(text(ctx, 'This run has no agents yet.', { dimColor: true }))
else if (wide) {
- for (let i = 0; i < Math.min(14, Math.max(phases.length, agents.length)); i += 1) {
+ for (let i = 0; i < Math.max(phases.length, agents.length); i += 1) {
rows.push(row(ctx, [phases[i] ?? text(ctx, ' '.repeat(left)), ctx.kit.Text({ dimColor: true, children: ' │ ' }), agents[i] ?? text(ctx, ' ')], `wf-${i}`))
}
} else {
rows.push(...phases, ...agents)
}
- if (Math.max(phases.length, agents.length) > 14 && wide) rows.push(text(ctx, `+${Math.max(phases.length, agents.length) - 14} more (j/k walks all of them)`, { dimColor: true }))
+ const hidden = Math.max(phaseTotal, agentList.length) - rowsMax
+
+ if (hidden > 0) rows.push(text(ctx, `+${hidden} more (j/k walks all of them)`, { dimColor: true }))
if (phase !== null && phase.agents.length === 0) rows.push(text(ctx, 'No agent has started in this phase yet.', { dimColor: true }))
if (here.ui.isInspecting && here.agent !== null) rows.push(...inspect(ctx, run, here.agent, hooks))
diff --git a/plugins/ruflo-console/scripts/bench-swarmui.mjs b/plugins/ruflo-console/scripts/bench-swarmui.mjs
new file mode 100644
index 0000000000..02ebc7fb0c
--- /dev/null
+++ b/plugins/ruflo-console/scripts/bench-swarmui.mjs
@@ -0,0 +1,158 @@
+// @ts-check
+/**
+ * ADR-458 benchmark: the workflows page's data functions and its render at 1k and 10k items. Plain node, no fixtures on
+ * disk: every input is generated here with the shapes Claude Code writes. Median and p99 wall time per case, plus
+ * approximate bytes allocated per call (heapUsed delta after gc(); needs NODE_OPTIONS=--expose-gc, else n/a).
+ * NODE_OPTIONS=--expose-gc npx -y tsx plugins/ruflo-console/scripts/bench-swarmui.mjs [runs]
+ * Cases: transcript lines (parseTranscript), journal events (parseJournal), agents in one run (buildRun, groupPhases),
+ * the page drawn for a run with that many agents (workflowsView, bounded to 14 rows a column), and the whole reader
+ * (readWorkflowRuns) over an in-memory disk at its own caps (6 runs x 60 agents).
+ */
+import { newState } from '../hooks/state.ts'
+import { buildRun, parseJournal, parseTranscript } from '../hooks/data/workflows.ts'
+import { allRuns, newWfUi, startOn } from '../hooks/data/workflows-nav.ts'
+import { readWorkflowRuns, slugOf } from '../hooks/data/workflows-read.ts'
+import { workflowsView } from '../hooks/views/workflows.ts'
+
+const RUNS = Math.max(5, Number(process.argv[2]) || 21)
+const NOW = Date.parse('2026-10-06T02:00:00.000Z')
+const iso = (/** @type {number} */ s) => new Date(NOW - 3_600_000 + s * 1000).toISOString()
+const gc = /** @type {(() => void) | undefined} */ (globalThis.gc)
+const ms = (/** @type {bigint} */ start) => Number(process.hrtime.bigint() - start) / 1e6
+
+const transcriptOf = (/** @type {number} */ n) => {
+ const out = [JSON.stringify({ type: 'user', timestamp: iso(0), message: { role: 'user', content: 'task' } })]
+
+ for (let i = 0; i < n / 2; i++) {
+ const base = { type: 'assistant', timestamp: iso(i), message: { id: `m${i}`, model: 'claude-sonnet-5-5', role: 'assistant', content: i % 3 === 0 ? [{ type: 'tool_use', id: `t${i}`, name: 'Bash' }] : [{ type: 'text', text: 'ok' }], usage: { input_tokens: 2, cache_creation_input_tokens: 500, cache_read_input_tokens: 100_000 + i, output_tokens: 50 } } }
+
+ out.push(JSON.stringify({ ...base, message: { ...base.message, usage: { ...base.message.usage, output_tokens: 3 } } }), JSON.stringify(base))
+ }
+
+ return out.join('\n') + '\n'
+}
+const PHASES = ['Build', 'Tune', 'Review', 'Ship']
+const journalOf = (/** @type {number} */ n) => [JSON.stringify({ type: 'launched' }), ...Array.from({ length: n }, (_, i) => JSON.stringify({ type: i % 2 ? 'result' : 'started', key: `v2:a${i >> 1}`, agentId: `a${i >> 1}`, label: `agent ${i >> 1}`, phase: PHASES[(i >> 1) % 4], result: 'finished the work' }))].join('\n') + '\n'
+const inputOf = (/** @type {number} */ n) => ({
+ id: 'wf_bench',
+ journal: journalOf(n * 2),
+ agents: new Map(Array.from({ length: n }, (_, i) => [`a${i}`, { meta: JSON.stringify({ description: `agent ${i}`, workflowPhase: PHASES[i % 4] }), transcript: null, isTail: false, path: `/d/agent-a${i}.jsonl` }])),
+ record: null,
+ script: null,
+ nowMs: NOW,
+})
+
+const element = (/** @type {string} */ kind) => (/** @type {Record<string, unknown>} */ props) => ({ kind, props })
+const kit = /** @type {never} */ ({ Box: element('Box'), Text: element('Text'), Button: element('Button'), Raster: element('Raster') })
+const ctx = /** @type {never} */ ({ kit, state: newState({}), nowMs: NOW, columns: 110, pictures: new Map(), act: {} })
+
+/** @type {(name: string, fn: () => unknown, iterations?: number) => void} */
+function bench(name, fn, iterations = RUNS) {
+ for (let i = 0; i < 3; i++) fn()
+
+ const times = []
+
+ for (let i = 0; i < iterations; i++) {
+ const start = process.hrtime.bigint()
+
+ fn()
+ times.push(ms(start))
+ }
+
+ times.sort((a, b) => a - b)
+
+ let bytes = 'n/a'
+
+ if (gc !== undefined) {
+ gc()
+ const before = process.memoryUsage().heapUsed
+
+ for (let i = 0; i < 5; i++) fn()
+ bytes = `~${Math.round((process.memoryUsage().heapUsed - before) / 5 / 1024)} KiB`
+ }
+
+ console.log(`${name.padEnd(34)} median ${(times[Math.floor(times.length / 2)] ?? 0).toFixed(3).padStart(9)} ms · p99 ${(times[Math.min(times.length - 1, Math.floor(times.length * 0.99))] ?? 0).toFixed(3).padStart(9)} ms · alloc/call ${bytes}`)
+}
+
+console.log(`${RUNS} timed runs per case · 110 columns · node ${process.version}`)
+
+for (const n of [1000, 10_000]) {
+ const t = transcriptOf(n)
+ const j = journalOf(n)
+
+ bench(`parseTranscript ${n} lines`, () => parseTranscript(t))
+ bench(`parseJournal ${n} events`, () => parseJournal(j))
+}
+
+for (const n of [1000, 10_000]) {
+ const input = inputOf(n)
+ const run = buildRun(input)
+ const runs = allRuns([run], null, [], NOW)
+ const ui = startOn(newWfUi(), run)
+
+ bench(`buildRun ${n} agents`, () => buildRun(input), n > 1000 ? 9 : RUNS)
+ bench(`workflowsView ${n} agents`, () => workflowsView(ctx, { runs, root: '/c', capBytes: 3_000_000, skipped: 0, more: 0 }, ui, { ask: () => undefined, show: () => undefined }))
+}
+
+// The whole reader at its own caps: 8 runs on disk (6 read), 60 agents each, transcripts of 400 lines.
+const root = `/cfg/projects/${slugOf('/work')}`
+const files = /** @type {Record<string, string>} */ ({})
+const sessions = ['00000000-0000-0000-0000-000000000001']
+
+for (let r = 0; r < 8; r++) {
+ const dir = `${root}/${sessions[0]}/subagents/workflows/wf_r${r}`
+
+ files[`${dir}/journal.jsonl`] = journalOf(120)
+
+ for (let a = 0; a < 70; a++) {
+ files[`${dir}/agent-a${a}.meta.json`] = JSON.stringify({ description: `agent ${a}`, workflowPhase: PHASES[a % 4] })
+ files[`${dir}/agent-a${a}.jsonl`] = transcriptOf(400)
+ }
+}
+
+// An indexed in-memory disk (directory → children), so the bench times the reader and not a linear-scan stand-in.
+const index = /** @type {Map<string, Map<string, boolean>>} */ (new Map())
+
+for (const file of Object.keys(files)) {
+ const parts = file.split('/')
+
+ for (let i = 1; i < parts.length; i++) {
+ const parent = parts.slice(0, i).join('/') || '/'
+ const kids = index.get(parent) ?? new Map()
+
+ kids.set(/** @type {string} */ (parts[i]), i === parts.length - 1)
+ index.set(parent, kids)
+ }
+}
+
+const fs = {
+ read: async (/** @type {string} */ path) => files[path] ?? Promise.reject(new Error('ENOENT')),
+ stat: async (/** @type {string} */ path) => (files[path] !== undefined ? { mtimeMs: 1, size: files[path].length } : Promise.reject(new Error('ENOENT'))),
+ list: async (/** @type {string} */ path) => {
+ const dir = path.replace(/\/+$/, '')
+
+ return [...(index.get(dir) ?? new Map()).entries()].map(([name, isFile]) => ({ name, kind: isFile ? 'file' : 'dir', mtimeMs: 1, size: isFile ? (files[`${dir}/${name}`]?.length ?? 0) : 0 }))
+ },
+}
+/**
+ * The reader: the first read (empty read cache, empty parse memo) and the refreshes after it with nothing changed, which is
+ * what the console's timer does. The parse memo lives in the module, so only the first call of a process is cold.
+ */
+const shared = new Map()
+const times = []
+let first = 0
+
+for (let i = 0; i < 12; i++) {
+ const start = process.hrtime.bigint()
+ const out = await readWorkflowRuns(/** @type {never} */ (fs), /** @type {never} */ (shared), { configDir: '/cfg', cwd: '/work', nowMs: NOW })
+ const took = ms(start)
+
+ if (i === 0 && (out.runs.length !== 6 || out.runs[0]?.total !== 60)) throw new Error(`reader caps not exercised: ${out.runs.length} runs, ${out.runs[0]?.total} agents`)
+
+ if (i === 0) first = took
+ else times.push(took)
+}
+
+times.sort((a, b) => a - b)
+console.log(`${'readWorkflowRuns 6x60 first'.padEnd(34)} ${first.toFixed(3).padStart(9)} ms (in-memory fs: no disk latency in it)`)
+console.log(`${'readWorkflowRuns 6x60 refresh'.padEnd(34)} median ${(times[Math.floor(times.length / 2)] ?? 0).toFixed(3).padStart(9)} ms · p99 ${(times[times.length - 1] ?? 0).toFixed(3).padStart(9)} ms (same cache, nothing changed)`)
diff --git a/plugins/ruflo-console/tests/workflows.spec.ts b/plugins/ruflo-console/tests/workflows.spec.ts
index 366c03695b..f988f228df 100644
--- a/plugins/ruflo-console/tests/workflows.spec.ts
+++ b/plugins/ruflo-console/tests/workflows.spec.ts
@@ -326,6 +326,17 @@ describe('view', () => {
expect(text).toContain('derived from the journal and transcripts')
})
+ it('draws at most 14 rows a column however many agents the run names, wide or narrow', () => {
+ const many = buildRun({ ...liveInput(), journal: journal(...Array.from({ length: 500 }, (_, i) => started(`x${i}`, `agent ${i}`, 'Build'))), agents: new Map() })
+
+ for (const columns of [110, 50]) {
+ const out = lines(workflowsView(ctxOf(columns), model([many]), startOn(newWfUi(), many), hooks))
+
+ expect(out.filter(l => /◐ agent/.test(l)).length).toBe(14)
+ expect(out.join('\n')).toContain('+486 more')
+ }
+ })
+
it('narrow screens drop the model and badge instead of overflowing', () => {
const out = lines(workflowsView(ctxOf(50), model(), startOn(newWfUi(), live), hooks))