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

test(ruflo-swarm): hostile-text readers, vitest parser spec, render/refresh benchmark at 8/32/100 agents

ruv50041312630c
diff --git a/plugins/ruflo-swarm/tests/parse.spec.ts b/plugins/ruflo-swarm/tests/parse.spec.ts
new file mode 100644
index 0000000000..b1164018f7
--- /dev/null
+++ b/plugins/ruflo-swarm/tests/parse.spec.ts
@@ -0,0 +1,71 @@
+/**
+ * The pure readers under vitest, beside the engine kit's own run of the same modules (parse.test.ts): they import nothing
+ * from the engine, so they run in Node as they are. Run with
+ * npx vitest run --root plugins/ruflo-swarm tests/parse.spec.ts
+ */
+import { describe, expect, it } from 'vitest'
+
+import { idOf, parseAgents, parseClaims, parseHive, parseRoute, parseSwarmStore, parseTasks, plain, routeFromStore } from '../hooks/reader/parse'
+import { readSnapshot, type ReadCache } from '../hooks/reader/snapshot'
+import { HIVE_TOKEN, RUFLO_RUN } from './fixtures/ruflo-run'
+
+const at = (path: string) => RUFLO_RUN[path] ?? null
+
+describe('parse (vitest)', () => {
+ it('reads the real run: one running swarm, three agents, two tasks, one claim, a queen and an open proposal', () => {
+ expect(parseSwarmStore(at('.claude-flow/swarm/swarm-state.json'))).toMatchObject({ id: 'swarm-1790888806724-u3ktj4', topology: 'hierarchical', status: 'running', strategy: 'specialized', agentIds: expect.any(Array) })
+ expect(parseAgents(at('.claude-flow/agents/store.json')).map(agent => `${agent.type}:${agent.status}`)).toEqual(['coder:busy', 'tester:idle', 'reviewer:idle'])
+ expect(parseTasks(at('.claude-flow/tasks/store.json')).map(task => task.status)).toEqual(['in_progress', 'pending'])
+ expect(parseClaims(at('.claude-flow/claims/claims.json'))).toEqual([
+ { issueId: 'task-1790888817265-vatniv', status: 'active', claimant: { kind: 'agent', id: 'agent-1790888815793-6ju96w', agentType: 'coder' }, progress: 0, isStealable: false },
+ ])
+
+ const hive = parseHive(at('.claude-flow/hive-mind/state.json'))
+
+ expect(hive?.queen).toEqual({ id: 'queen-1790888818222', term: 1 })
+ expect(hive?.pending[0]).toMatchObject({ type: 'design', strategy: 'raft', votesFor: 0, votesAgainst: 0 })
+ expect(JSON.stringify(hive)).not.toContain(HIVE_TOKEN)
+ })
+
+ it('a missing file is a missing fact, and the snapshot names which', async () => {
+ const files: Record<string, string> = { '.swarm/state.json': at('.swarm/state.json') ?? '' }
+ const fs = {
+ read: async (path: string) => files[path] ?? Promise.reject(new Error('ENOENT')),
+ stat: async (path: string) => (files[path] !== undefined ? { mtimeMs: 1, size: 1 } : Promise.reject(new Error('ENOENT'))),
+ }
+ const cache: ReadCache = new Map()
+ const snapshot = await readSnapshot(fs, cache, 0)
+
+ expect(snapshot.swarm).toMatchObject({ id: 'swarm-1790888806724-u3ktj4', topology: 'hierarchical', status: 'ready' })
+ expect(snapshot.missing).toEqual(['swarm', 'agents', 'tasks', 'claims', 'hive'])
+ expect(snapshot.hasSwarm).toBe(true)
+ })
+
+ it('an unchanged file is not read twice', async () => {
+ let reads = 0
+ const fs = { read: async () => (reads++, at('.claude-flow/agents/store.json') ?? ''), stat: async () => ({ mtimeMs: 7, size: 9 }) }
+ const cache: ReadCache = new Map()
+
+ await readSnapshot(fs, cache, 0)
+ await readSnapshot(fs, cache, 1)
+ expect(reads).toBe(6)
+ })
+
+ it('ids are only what ruflo mints; text is printable and bounded', () => {
+ expect(idOf('agent-1790888815793-6ju96w')).toBe('agent-1790888815793-6ju96w')
+ for (const bad of ['', ' agent', 'a b', 'a;rm', '$(x)', '-rf', '../x', 'a'.repeat(200), 7, null]) {
+ expect(idOf(bad)).toBeNull()
+ }
+ expect(plain('a\u001b[31mred\u0007‮evil', 50)).toBe('a [31mred evil')
+ expect(plain('x'.repeat(500), 10)).toHaveLength(10)
+ })
+
+ it('a router pick keeps its own matched flag and its score; a store copy is re-checked', () => {
+ const pick = parseRoute('[INFO] x\n{"task":"t","matched":true,"primaryAgent":{"type":"architect","confidence":0.41},"alternativeAgents":[]}', 3)
+
+ expect(pick).toMatchObject({ agent: 'architect', confidence: 0.41, matched: true })
+ expect(parseRoute('no json here', 0)).toBeNull()
+ expect(routeFromStore({ task: 't', agent: 'x', confidence: 'high', atMs: 1 })).toBeNull()
+ expect(routeFromStore(pick)).toMatchObject({ agent: 'architect', confidence: 0.41 })
+ })
+})
diff --git a/plugins/ruflo-swarm/tests/parse.test.ts b/plugins/ruflo-swarm/tests/parse.test.ts
new file mode 100644
index 0000000000..c214389604
--- /dev/null
+++ b/plugins/ruflo-swarm/tests/parse.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, test } from 'claude-code/testing'
+
+import { MAX_TEXT, parseAgents, parseClaims, parseHive, parseRoute, parseSwarmPointer, parseSwarmStore, parseTasks } from '../hooks/reader/parse'
+
+/** Text from another process's files: a line of a hundred thousand characters must cost a moment, not a frozen hook. */
+const N = 100_000
+
+const SHAPES: Record<string, string> = {
+ spaces: `${' '.repeat(N)}x`,
+ braces: `${'{'.repeat(N)}${'}'.repeat(N)}`,
+ brackets: `${'['.repeat(N)}${']'.repeat(N)}`,
+ digits: '9'.repeat(N),
+ 'log then brace': `${'[INFO] x\n'.repeat(N / 10)}{`,
+ 'deep json': `${'{"a":'.repeat(5_000)}1${'}'.repeat(5_000)}`,
+ 'many agents': JSON.stringify({ agents: Object.fromEntries(Array.from({ length: 5_000 }, (_, i) => [`a${i}`, { agentId: `agent-${i}`, agentType: 'coder', status: 'idle' }])) }),
+ 'control characters': JSON.stringify({ tasks: { t: { taskId: 'task-1', description: '\u001b[2J\u0007'.repeat(N / 10), status: 'pending' } } }),
+ 'oversized': `{"agents":{${' '.repeat(MAX_TEXT)}}}`,
+}
+
+const PARSERS: Record<string, (text: string) => unknown> = {
+ swarm: parseSwarmStore,
+ pointer: parseSwarmPointer,
+ agents: parseAgents,
+ tasks: parseTasks,
+ claims: parseClaims,
+ hive: parseHive,
+ route: text => parseRoute(text, 0),
+}
+
+describe('parse', () => {
+ test('no reader takes long over hostile text, whatever it is made of', () => {
+ const slow: string[] = []
+
+ for (const [parserName, parse] of Object.entries(PARSERS)) {
+ for (const [shapeName, text] of Object.entries(SHAPES)) {
+ const started = Date.now()
+
+ parse(text)
+
+ const took = Date.now() - started
+
+ if (took > 500) {
+ slow.push(`${parserName} on ${shapeName}: ${took} ms`)
+ }
+ }
+ }
+
+ expect(slow).toEqual([])
+ })
+
+ test('a store with more agents than the pane keeps is cut to a thousand, and terminal escapes never pass through', () => {
+ expect(parseAgents(SHAPES['many agents'] ?? '')).toHaveLength(1_000)
+ expect(parseTasks(SHAPES['control characters'] ?? '')[0]?.description).not.toMatch(/[\u0000-\u001f]/)
+ expect(parseAgents(SHAPES.oversized ?? ''), 'past the size cap nothing is parsed').toEqual([])
+ })
+
+ test('shapes ruflo does not write are left out, never guessed at', () => {
+ expect(parseSwarmStore('[]')).toBeNull()
+ expect(parseSwarmStore('{"swarms":{"x":{"swarmId":"bad id;rm"}}}')).toBeNull()
+ expect(parseAgents('{"agents":{"a":{"agentType":"coder"}}}'), 'no id').toEqual([])
+ expect(parseClaims('{"claims":{"t":{"issueId":"task-1","claimant":{"type":"agent","agentId":"$(x)"}}}}')).toEqual([])
+ expect(parseHive('{"initialized":false}')).toBeNull()
+ expect(parseRoute('{"primaryAgent":{"type":"coder"}}', 0), 'no confidence: no pick').toBeNull()
+ })
+})
diff --git a/plugins/ruflo-swarm/tests/views.test.ts b/plugins/ruflo-swarm/tests/views.test.ts
new file mode 100644
index 0000000000..703ba317c5
--- /dev/null
+++ b/plugins/ruflo-swarm/tests/views.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, mock, test } from 'claude-code/testing'
+
+import { RUFLO_RUN } from './fixtures/ruflo-run'
+import { command, paneAt, SESSION } from './fixtures/inputs'
+import { textOf, worldOf } from './fixtures/world'
+
+/** A swarm of `agents` ruflo agents and as many tasks, in the shapes ruflo 3.49.0 writes. */
+function swarmOf(agents: number): Record<string, string> {
+ const ids = Array.from({ length: agents }, (_, i) => `agent-17908888${String(i).padStart(5, '0')}-x${i}`)
+ const types = ['coder', 'tester', 'reviewer', 'architect', 'researcher']
+
+ return {
+ ...RUFLO_RUN,
+ '.claude-flow/agents/store.json': JSON.stringify({
+ agents: Object.fromEntries(ids.map((id, i) => [id, { agentId: id, agentType: types[i % types.length], status: i % 3 === 0 ? 'busy' : 'idle', health: 1, taskCount: 0 }])),
+ version: '3.0.0',
+ }),
+ '.claude-flow/tasks/store.json': JSON.stringify({
+ tasks: Object.fromEntries(ids.map((id, i) => [`task-${i}`, { taskId: `task-${i}`, type: 'implementation', description: `task number ${i}`, priority: 'normal', status: i % 4 === 0 ? 'completed' : 'pending', assignedTo: [id], tags: [] }])),
+ version: '3.0.0',
+ }),
+ }
+}
+
+/** The kit's environment prints with `console`; the declarations name no DOM, so it is declared here. */
+declare const console: { log: (...values: unknown[]) => void }
+
+const quantile = (sorted: readonly number[], q: number) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0
+
+/**
+ * What a render and a re-read of the disk cost with 8, 32 and 100 agents, through the engine's own `$`: the numbers
+ * print, and a bound fails the test if a change makes a render slow enough to be felt (the engine gives a dispatch 10 s).
+ */
+describe('views', () => {
+ for (const agents of [8, 32, 100]) {
+ test(`render and refresh with ${agents} agents`, { timeoutMs: 30_000 }, async ($, on) => {
+ worldOf(on, swarmOf(agents))
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const renders: number[] = []
+ const narrow: number[] = []
+ const refreshes: number[] = []
+
+ for (let i = 0; i < 60; i += 1) {
+ let started = performance.now()
+
+ await $.ui.render(paneAt(120, 60))
+ renders.push(performance.now() - started)
+
+ started = performance.now()
+ await $.ui.render(paneAt(30, 30))
+ narrow.push(performance.now() - started)
+
+ // The status command re-reads every file (mtime-cached) before it answers: one refresh.
+ started = performance.now()
+ await $.command.run(command('ruflo-swarm-status'))
+ refreshes.push(performance.now() - started)
+ }
+
+ const report = (name: string, samples: number[]) => {
+ const sorted = [...samples].sort((a, b) => a - b)
+
+ return `${name} median ${quantile(sorted, 0.5).toFixed(2)} ms p95 ${quantile(sorted, 0.95).toFixed(2)} ms`
+ }
+
+ console.log(`[bench] ${agents} agents: ${report('render', renders)} · ${report('narrow', narrow)} · ${report('refresh', refreshes)}`)
+
+ const tree = await $.ui.render(paneAt(120, 60))
+
+ expect(textOf(tree)).toMatch(agents > 36 ? /\+\d+ more agents/ : /coder/)
+ expect(quantile([...renders].sort((a, b) => a - b), 0.95)).toBeLessThan(250)
+ })
+ }
+})