test(ruflo-swarm): engine-kit tests for register and pane over a real ruflo run

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
ruv committed 2026-10-01 17:28:58 -04:00
1 parent 5c133697ee
commit 77e5262537
5 files changed
+637

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
import type { AgentSpawnInput, RenderInput, SessionStartInput } from 'claude-code'
export const PLUGIN = 'ruflo-swarm'
export const CWD = '/work'
export const SESSION: SessionStartInput = { surface: 'terminal', isInteractive: true, cwd: CWD }
export const HINT: RenderInput<'PromptHint'> = {
component: 'PromptHint',
surface: 'terminal',
requestId: 'hint',
viewport: { columns: 180, rows: 48, isFullscreen: true },
props: { isDraft: false, isWorking: false, hint: '' },
}
export const MAIN_SCREEN_HINT: RenderInput<'PromptHint'> = { ...HINT, viewport: { columns: 180, rows: 48, isFullscreen: false } }
/** The swarm pane as the engine asks for it, docked, 72 columns of body and 44 rows. */
export const PANE: RenderInput<'Pane'> = {
component: 'Pane',
surface: 'terminal',
requestId: 'ruflo-swarm',
viewport: { columns: 180, rows: 48, isFullscreen: true },
props: { title: 'Swarm', isFocused: false, bodyColumns: 73, placement: 'dock', scroll: { offset: 0, bodyRows: 44 }, view: {} },
}
export const paneAt = (bodyColumns: number, bodyRows = 44): RenderInput<'Pane'> => ({ ...PANE, props: { ...PANE.props, bodyColumns, scroll: { offset: 0, bodyRows } } })
export const command = (name: string, args = '') => ({
command: name,
args,
origin: { kind: 'composer' as const },
presentation: { isFullscreen: true, columns: 180 },
})
/** An Agent tool's spawn as the engine raises it, with what the caller asked for. */
export const spawn = (subagentType: string, prompt: string, name?: string): AgentSpawnInput => ({
tool_use_id: `toolu_${subagentType.replace(/\W/g, '')}`,
prompt,
description: prompt.slice(0, 30),
subagentType,
provider: { plugin: 'engine', tier: 'core' },
parentModel: 'claude-opus-5-5',
background: true,
fork: false,
...(name !== undefined && { name }),
})
+180
View File
@@ -0,0 +1,180 @@
/**
* The files ruflo 3.49.0 wrote in a real run (swarm init, three agent spawns, two tasks, a claim, an assignment,
* hive-mind init and a consensus proposal), captured from disk. The hive token is replaced by a sentinel the tests
* assert never reaches a drawing, a command's text or a log.
*/
export const HIVE_TOKEN = 'HIVE-TOKEN-SENTINEL-must-never-render'
export const RUFLO_RUN: Record<string, string> = {
".claude-flow/swarm/swarm-state.json": JSON.stringify({
"swarms": {
"swarm-1790888806724-u3ktj4": {
"swarmId": "swarm-1790888806724-u3ktj4",
"topology": "hierarchical",
"maxAgents": 8,
"status": "running",
"agents": [
"agent-1790888815793-6ju96w",
"agent-1790888816288-z5xsn6",
"agent-1790888816793-b2xzp7"
],
"tasks": [],
"config": {
"topology": "hierarchical",
"maxAgents": 8,
"strategy": "specialized",
"communicationProtocol": "message-bus",
"autoScaling": true,
"consensusMechanism": "majority"
},
"createdAt": "2026-10-01T21:06:46.724Z",
"updatedAt": "2026-10-01T21:06:46.724Z"
}
},
"version": "3.0.0"
}),
".swarm/state.json": JSON.stringify({
"id": "swarm-1790888806724-u3ktj4",
"topology": "hierarchical",
"maxAgents": 8,
"strategy": "specialized",
"v3Mode": false,
"permissions": null,
"initializedAt": "2026-10-01T21:06:46.724Z",
"status": "ready"
}),
".claude-flow/agents/store.json": JSON.stringify({
"agents": {
"agent-1790888815793-6ju96w": {
"agentId": "agent-1790888815793-6ju96w",
"agentType": "coder",
"status": "busy",
"health": 1,
"taskCount": 0,
"config": {
"provider": "anthropic",
"timeout": 300,
"autoTools": true
},
"createdAt": "2026-10-01T21:06:55.793Z",
"model": "sonnet",
"modelRoutedBy": "default",
"currentTask": "task-1790888817265-vatniv"
},
"agent-1790888816288-z5xsn6": {
"agentId": "agent-1790888816288-z5xsn6",
"agentType": "tester",
"status": "idle",
"health": 1,
"taskCount": 0,
"config": {
"provider": "anthropic",
"timeout": 300,
"autoTools": true
},
"createdAt": "2026-10-01T21:06:56.288Z",
"model": "sonnet",
"modelRoutedBy": "default"
},
"agent-1790888816793-b2xzp7": {
"agentId": "agent-1790888816793-b2xzp7",
"agentType": "reviewer",
"status": "idle",
"health": 1,
"taskCount": 0,
"config": {
"provider": "anthropic",
"timeout": 300,
"autoTools": true
},
"createdAt": "2026-10-01T21:06:56.793Z",
"model": "sonnet",
"modelRoutedBy": "default"
}
},
"version": "3.0.0"
}),
".claude-flow/tasks/store.json": JSON.stringify({
"tasks": {
"task-1790888817265-vatniv": {
"taskId": "task-1790888817265-vatniv",
"type": "implementation",
"description": "Build login form",
"priority": "normal",
"status": "in_progress",
"progress": 0,
"assignedTo": [
"agent-1790888815793-6ju96w"
],
"tags": [],
"createdAt": "2026-10-01T21:06:57.265Z",
"startedAt": "2026-10-01T21:07:39.789Z",
"completedAt": null
},
"task-1790888817757-h3rps7": {
"taskId": "task-1790888817757-h3rps7",
"type": "testing",
"description": "Write login tests",
"priority": "normal",
"status": "pending",
"progress": 0,
"assignedTo": [],
"tags": [],
"createdAt": "2026-10-01T21:06:57.757Z",
"startedAt": null,
"completedAt": null
}
},
"version": "3.0.0"
}),
".claude-flow/claims/claims.json": JSON.stringify({
"claims": {
"task-1790888817265-vatniv": {
"issueId": "task-1790888817265-vatniv",
"claimant": {
"type": "agent",
"agentId": "agent-1790888815793-6ju96w",
"agentType": "coder"
},
"claimedAt": "2026-10-01T21:07:39.332Z",
"status": "active",
"statusChangedAt": "2026-10-01T21:07:39.332Z",
"progress": 0
}
},
"stealable": {},
"contests": {}
}),
".claude-flow/hive-mind/state.json": JSON.stringify({
"initialized": true,
"topology": "hierarchical",
"workers": [],
"consensus": {
"pending": [
{
"proposalId": "proposal-1790888860262-55jkcl",
"type": "design",
"value": "use-jwt",
"proposedBy": "system",
"proposedAt": "2026-10-01T21:07:40.262Z",
"votes": {},
"status": "pending",
"strategy": "raft",
"term": 1,
"timeoutAt": "2026-10-01T21:08:10.262Z"
}
],
"history": []
},
"sharedMemory": {},
"createdAt": "2026-10-01T21:06:58.222Z",
"updatedAt": "2026-10-01T21:07:40.262Z",
"consensusStrategy": "byzantine",
"queen": {
"agentId": "queen-1790888818222",
"electedAt": "2026-10-01T21:06:58.222Z",
"term": 1
},
"hiveToken": "HIVE-TOKEN-SENTINEL-must-never-render"
}),
}
+171
View File
@@ -0,0 +1,171 @@
import type { On, RenderElement, RenderNode } from 'claude-code'
import { CWD } from './inputs'
/** One `$.process.run` the mod made, and what the world answers it with. */
export type Run = { argv: string[]; timeoutMs?: number }
export type Responder = (argv: readonly string[]) => { exitCode: number; stdout: string; stderr: string; write?: Record<string, string> }
/**
* The world beneath the mod, in memory: a file tree `$.fs` answers from, a process table `$.process.run` answers
* from, and a record of everything the mod asked the engine to do.
*/
export type World = {
files: Map<string, string>
runs: Run[]
opened: string[]
closed: string[]
toasts: string[]
logs: string[]
fills: string[]
commands: string[]
stored: Map<string, unknown>
invalidations: number
respond: Responder
/** Writes a file as ruflo's CLI would, moving its mtime on. */
put: (path: string, text: string) => void
}
const relOf = (path: string) => (path.startsWith(`${CWD}/`) ? path.slice(CWD.length + 1) : path)
export const exitOk = (stdout = ''): ReturnType<Responder> => ({ exitCode: 0, stdout, stderr: '' })
/** Seats the in-memory world beneath the plugin. `usage` is what `$.session.usage()` answers; null refuses it. */
export function worldOf(on: On, files: Readonly<Record<string, string>>, usage: unknown = { context: { tokens: 68_000, window: 200_000, percent: 34 }, rateLimits: [], cost: { usd: 0.4213 } }): World {
let tick = 1_000
const mtimes = new Map<string, number>(Object.keys(files).map(path => [path, tick]))
const world: World = {
files: new Map(Object.entries(files)),
runs: [],
opened: [],
closed: [],
toasts: [],
logs: [],
fills: [],
commands: [],
stored: new Map(),
invalidations: 0,
respond: () => exitOk(),
put: (path, text) => {
tick += 1_000
world.files.set(path, text)
mtimes.set(path, tick)
},
}
on('fs.read', ($, e) => {
const text = world.files.get(relOf(e.path))
return text === undefined ? { deny: `ENOENT: ${e.path}` } : { value: text }
})
on('fs.stat', ($, e) => {
const text = world.files.get(relOf(e.path))
return text === undefined ? { deny: `ENOENT: ${e.path}` } : { value: { kind: 'file' as const, size: text.length, mtimeMs: mtimes.get(relOf(e.path)) ?? 0, isLink: false } }
})
on('process.run', ($, e) => {
world.runs.push({ argv: [...e.argv], ...(e.init?.timeoutMs !== undefined && { timeoutMs: e.init.timeoutMs }) })
const answer = world.respond(e.argv)
for (const [path, text] of Object.entries(answer.write ?? {})) {
world.put(path, text)
}
return { value: { exitCode: answer.exitCode, stdout: answer.stdout, stderr: answer.stderr } }
})
on('session.usage', () => (usage === null ? { deny: 'usage refused' } : { value: usage as never }))
on('agent.list', () => ({ value: [] }))
on('store.get', ($, e) => ({ value: world.stored.get(e.key) }))
on('store.set', ($, e) => {
world.stored.set(e.key, e.value)
return { value: undefined }
})
on('command.register', ($, e) => {
world.commands.push(e.name)
return { value: { command: e.name } }
})
on('ui.open', ($, e) => {
world.opened.push(e.id)
return { value: { isPlaced: true } } as never
})
on('ui.close', ($, e) => {
world.closed.push(e.id)
return { value: undefined }
})
on('ui.toast', ($, e) => {
world.toasts.push(e.text)
return { value: undefined }
})
on('ui.log', ($, e) => {
world.logs.push(e.text)
return { value: undefined }
})
on('ui.invalidate', () => {
world.invalidations += 1
return { value: undefined }
})
on('prompt.fill', ($, e) => {
world.fills.push(e.text)
return { isFilled: true }
})
on('session.start', ($, e) => ({ cwd: e.cwd }))
on('turn.start', ($, e) => ({ turnId: e.turnId }))
on('turn.complete', ($, e) => ({ text: e.answer }))
return world
}
/** Every string a drawn tree holds, button labels included, in drawing order. */
export function stringsOf(node: RenderNode | RenderElement | null | undefined): string[] {
if (node === null || node === undefined || typeof node === 'boolean') {
return []
}
if (typeof node === 'string' || typeof node === 'number') {
return [String(node)]
}
const props = (node as { props?: Record<string, unknown> }).props
const own = node.type === 'Button' && typeof props?.label === 'string' ? [props.label] : []
const children = (node as { children?: readonly RenderNode[] }).children ?? []
return [...own, ...children.flatMap(child => stringsOf(child))]
}
export const textOf = (node: RenderNode | RenderElement | null | undefined): string => stringsOf(node).join('')
/** Every element of `type` in a drawn tree. */
export function elementsOf(node: RenderNode | RenderElement | null | undefined, type: string): RenderElement[] {
if (node === null || node === undefined || typeof node !== 'object') {
return []
}
const children = (node as { children?: readonly RenderNode[] }).children ?? []
return [...(node.type === type ? [node as RenderElement] : []), ...children.flatMap(child => elementsOf(child, type))]
}
/** The `key`s of every Button drawn, in order. */
export const buttonKeysOf = (node: RenderNode | RenderElement | null | undefined): string[] =>
elementsOf(node, 'Button').map(button => String((button as { key?: unknown; props?: { key?: unknown } }).key ?? (button as { props?: { key?: unknown } }).props?.key ?? ''))
+129
View File
@@ -0,0 +1,129 @@
import type { RenderElement } from 'claude-code'
import { describe, expect, mock, test } from 'claude-code/testing'
import { HIVE_TOKEN, RUFLO_RUN } from './fixtures/ruflo-run'
import { command, PANE, paneAt, PLUGIN, SESSION, spawn } from './fixtures/inputs'
import { buttonKeysOf, elementsOf, textOf, worldOf } from './fixtures/world'
const tileOf = (tree: RenderElement, label: string) =>
elementsOf(tree, 'Text').find(node => textOf(node).includes(label) && (node as { props?: { inverse?: boolean } }).props?.inverse !== undefined) as
| { props: { inverse?: boolean; color?: string } }
| undefined
describe('pane', () => {
test('draws the swarm: tiles by state, the leader, the board, consensus, topology, router and usage', async ($, on) => {
worldOf(on, RUFLO_RUN)
mock.clock(on)
await $.session.start(SESSION)
await $.command.run(command('ruflo-swarm-pane'))
const tree = await $.ui.render(PANE)
const text = textOf(tree)
expect(text).toContain('swarm …4-u3ktj4 · hierarchical · running')
expect(text).toContain('★ queen')
for (const role of ['coder', 'tester', 'reviewer', 'claude (main)']) {
expect(text).toContain(role)
}
expect(text).toContain('pending 1 · claimed 1 · done 0')
expect(text).toContain('Build login form → coder')
expect(text).toContain('Write login tests → unassigned')
expect(text).toContain('design (raft) for 0 · against 0')
expect(text).toContain('├─ coder')
expect(text).toContain('router: no pick seen this session')
expect(text).toContain('cost $0.421 · context 68k/200k (34%)')
expect(text).not.toContain(HIVE_TOKEN)
expect(buttonKeysOf(tree)).toEqual(expect.arrayContaining(['hide', 'prev', 'next', 'logs', 'task-prev', 'task-next', 'offer', 'reroute', 'vote-yes', 'vote-no']))
})
test('a figure the engine does not give is n/a, never zero', async ($, on) => {
worldOf(on, RUFLO_RUN, { context: { window: 200_000 }, rateLimits: [] })
mock.clock(on)
await $.session.start(SESSION)
expect(textOf(await $.ui.render(PANE))).toContain('cost n/a · context n/a/200k')
})
test('a tile lights blue while its agent reads and yellow while it writes, then fades', async ($, on) => {
worldOf(on, RUFLO_RUN)
mock.clock(on)
on('tool.call', () => ({ result: 'ok', text: 'ok' }))
on('agent.spawn', () => ({ model: 'haiku', agentId: 'agent-cc-1' }))
await $.session.start(SESSION)
await $.command.run(command('ruflo-swarm-pane'))
await $.agent.spawn(spawn('ruflo-swarm:coordinator', 'write the tests', 'tester-cc'))
await $.tool.call({ tool: 'Read', file_path: '/work/src/a.ts', agentId: 'agent-cc-1' } as never)
const reading = tileOf(await $.ui.render(PANE), 'tester-cc')
expect(reading?.props.inverse).toBe(true)
expect(reading?.props.color).toBe('suggestion')
await $.tool.call({ tool: 'Edit', file_path: '/work/src/a.ts', old_string: 'a', new_string: 'b', agentId: 'agent-cc-1' } as never)
expect(tileOf(await $.ui.render(PANE), 'tester-cc')?.props.color).toBe('warning')
})
test('Claude Code subagents join as members by their type, and a finished one reads as done', async ($, on) => {
worldOf(on, RUFLO_RUN)
mock.clock(on)
on('agent.spawn', () => ({ model: 'haiku', agentId: 'agent-cc-2' }))
await $.session.start(SESSION)
await $.agent.spawn(spawn('ruflo-core:reviewer', 'review it'))
expect(textOf(await $.ui.render(PANE))).toContain('reviewer')
await $.turn.complete({ answer: 'ok', durationMs: 5, isAborted: false, turnId: 't9', reason: 'answer', agentId: 'agent-cc-2' } as never)
const status = (await $.command.run(command('ruflo-swarm-status'))).text ?? ''
expect(status).toContain('· reviewer (claude) completed')
})
test('narrower than 44 columns the pane is a list, and the terminal accepts it at every width', async ($, on) => {
worldOf(on, RUFLO_RUN)
mock.clock(on)
on('ui.render', () => ({ type: 'Text', children: [''] }))
await $.session.start(SESSION)
await $.command.run(command('ruflo-swarm-pane'))
const narrow = await $.ui.render(paneAt(30, 30))
expect(textOf(narrow)).toContain('tasks 1 pending · 1 claimed')
expect(buttonKeysOf(narrow)).not.toContain('offer')
for (const [columns, rows] of [[24, 12], [30, 30], [48, 40], [73, 44], [120, 8], [160, 60]] as const) {
const mounted = await $.ui.mount({ ...paneAt(columns, rows), plugin: PLUGIN })
expect(mounted.surface).toBe('terminal')
await mounted.unmount()
}
})
test('a short body sheds the lower sections first and keeps the tiles and selection', async ($, on) => {
worldOf(on, RUFLO_RUN)
mock.clock(on)
await $.session.start(SESSION)
const text = textOf(await $.ui.render(paneAt(73, 8)))
expect(text).toContain('coder')
expect(text).not.toContain('Topology')
})
test('draws in theme colours only, never ANSI names that fade on a light background', async ($, on) => {
worldOf(on, RUFLO_RUN)
mock.clock(on)
await $.session.start(SESSION)
const colors = new Set(elementsOf(await $.ui.render(PANE), 'Text').flatMap(node => {
const color = (node as { props?: { color?: string } }).props?.color
return color === undefined ? [] : [color]
}))
for (const color of colors) {
expect(['suggestion', 'success', 'error', 'warning', 'claude']).toContain(color)
}
})
})
+110
View File
@@ -0,0 +1,110 @@
import { describe, expect, mock, test } from 'claude-code/testing'
import { HIVE_TOKEN, RUFLO_RUN } from './fixtures/ruflo-run'
import { command, HINT, MAIN_SCREEN_HINT, PANE, PLUGIN, SESSION } from './fixtures/inputs'
import { buttonKeysOf, textOf, worldOf } from './fixtures/world'
describe('register', () => {
test('the start registers the five commands and opens nothing by itself', async ($, on) => {
const world = worldOf(on, RUFLO_RUN)
mock.clock(on)
await $.session.start(SESSION)
expect(world.commands.sort()).toEqual(['ruflo-swarm-claims', 'ruflo-swarm-consensus', 'ruflo-swarm-pane', 'ruflo-swarm-status', 'ruflo-swarm-topology'])
expect(world.opened).toEqual([])
})
test('with a swarm on disk the pane opens once the fullscreen hint draws; on the main screen it waits', async ($, on) => {
const world = worldOf(on, RUFLO_RUN)
const clock = mock.clock(on)
on('ui.render', () => ({ type: 'Text', children: [''] }))
await $.session.start(SESSION)
await $.ui.render(MAIN_SCREEN_HINT)
await clock.advance(200)
expect(world.opened, 'not fullscreen: nothing opens unasked').toEqual([])
await $.ui.render(HINT)
await clock.advance(200)
await $.ui.render(HINT)
await clock.advance(200)
expect(world.opened).toEqual([PLUGIN])
})
test('with no swarm on disk nothing opens, and the pane says how to start one', async ($, on) => {
const world = worldOf(on, { 'README.md': 'x' })
const clock = mock.clock(on)
on('ui.render', () => ({ type: 'Text', children: [''] }))
await $.session.start(SESSION)
await $.ui.render(HINT)
await clock.advance(200)
expect(world.opened).toEqual([])
const tree = await $.ui.render(PANE)
expect(textOf(tree)).toContain('No ruflo swarm on disk in this folder.')
expect(textOf(tree)).toContain('/ruflo-swarm:swarm init')
expect(buttonKeysOf(tree)).toEqual(['hide', 'fill'])
await $.ui.press({ plugin: PLUGIN, key: 'fill' })
expect(world.fills).toEqual(['/ruflo-swarm:swarm init'])
})
test('/ruflo-swarm-pane toggles the pane and says which', async ($, on) => {
const world = worldOf(on, RUFLO_RUN)
mock.clock(on)
await $.session.start(SESSION)
expect(await $.command.run(command('ruflo-swarm-pane'))).toEqual({ text: 'Swarm pane shown' })
expect(await $.command.run(command('ruflo-swarm-pane'))).toEqual({ text: 'Swarm pane hidden' })
expect(world.opened).toEqual([PLUGIN])
expect(world.closed).toEqual([PLUGIN])
})
test('the markdown /ruflo-swarm:watch still runs, and the mod opens the pane beside it', async ($, on) => {
const world = worldOf(on, RUFLO_RUN)
const ran: string[] = []
mock.clock(on)
on('command.run', ($, e) => {
ran.push(e.command)
return { text: 'markdown command ran' }
})
await $.session.start(SESSION)
expect(await $.command.run(command('ruflo-swarm:watch'))).toEqual({ text: 'markdown command ran' })
expect(ran).toEqual(['ruflo-swarm:watch'])
expect(world.opened).toEqual([PLUGIN])
})
test('the status, topology, claims and consensus commands report what is on disk, never the hive token', async ($, on) => {
worldOf(on, RUFLO_RUN)
mock.clock(on)
await $.session.start(SESSION)
const status = (await $.command.run(command('ruflo-swarm-status'))).text ?? ''
const json = (await $.command.run(command('ruflo-swarm-status', 'json'))).text ?? ''
const topology = (await $.command.run(command('ruflo-swarm-topology'))).text ?? ''
const claims = (await $.command.run(command('ruflo-swarm-claims'))).text ?? ''
const consensus = (await $.command.run(command('ruflo-swarm-consensus'))).text ?? ''
expect(status).toContain('swarm …4-u3ktj4 · hierarchical · running')
expect(status).toContain('· coder (ruflo) busy')
expect(status).toContain('tasks: 1 pending, 1 claimed, 0 done')
expect(status).toContain('router: no pick seen this session')
expect(status).toContain('cost $0.421 · context 68k/200k (34%)')
expect(topology).toContain('hierarchical (strategy specialized, max 8 agents, hive consensus byzantine)')
expect(topology).toContain('★ queen')
expect(topology).toContain('├─ coder')
expect(claims).toContain('task-1790888817265-vatniv: active by agent coder agent-1790888815793-6ju96w')
expect(consensus).toContain('open proposal-1790888860262-55jkcl design (raft): for 0, against 0')
for (const text of [status, json, topology, claims, consensus]) {
expect(text).not.toContain(HIVE_TOKEN)
}
})
})