🌊 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(ruflo-console): tests, smoke, bench, marketplace entry, CI baseline
ruv6eb25a823c33
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 0ab7e26805..9670837790 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -225,6 +225,11 @@"name": "ruflo-ruos","source": "./plugins/ruflo-ruos","description": "Run ruflo swarm agents on your own ruOS cloud desktops via the tenant-authenticated fleet MCP or per-tenant SSH; optional, removable"+ },+ {+ "name": "ruflo-console",+ "source": "./plugins/ruflo-console",+ "description": "Early access: ruflo's real-time cockpit as a Claude Code mod (function hooks) \u2014 eight views (overview, swarm topology graph, claims board with confirm-gated actions, federation, plugins and marketplace freshness, self-learning, MetaHarness, memory and cost) plus a band above the prompt; reads ruflo's files and the CLI's local JSON, no network by default"}]}diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.tsindex 6587c6c780..bc292cf7f7 100644--- a/plugins/ruflo-console/hooks/controller.ts+++ b/plugins/ruflo-console/hooks/controller.ts@@ -17,6 +17,8 @@ const ACTIVITY_BUCKET_MS = 5_000const PANE_WATCH_MS = 1_000const PENDING_TTL_MS = 30_000const MAX_PARALLEL_PROBES = 2+const BAR_FRESH_MS = 10_000+const IDLE_REFRESH_MS = 30_000export type Controller = {refresh: () => Promise<void>@@ -53,6 +55,8 @@ export function createController(state: State, host: Host): Controller {let pendingSpec: ActionSpec | null = nulllet markRequest: string | null = nulllet lastSegment: string | null | undefined+ let lastSpend: number | undefined+ let hasDrawn = falseconst lastAttempt = new Map<string, number>()const persist = () => void host.storeSet(storeKeyOf(state.cwd), { view: state.view }).catch(() => undefined)@@ -69,6 +73,12 @@ export function createController(state: State, host: Host): Controller {return inflight}+ /** A read that starts after this call: what an action checks, since a read already running may predate its write. */+ async function freshRead(): Promise<void> {+ await inflight?.catch(() => undefined)+ await refresh()+ }+async function readAll(): Promise<void> {state.isRefreshing = true@@ -105,7 +115,15 @@ export function createController(state: State, host: Host): Controller {} finally {state.isRefreshing = falsepush(state.stats.refreshes, Date.now() - started, 200)- host.invalidate()++ // Redraw only for something new while the pane is closed: the band need not repaint an unchanged line.+ const spend = state.usage?.costUsd++ if (state.pane.isOpen || (state.snapshot?.changed ?? 0) > 0 || spend !== lastSpend || !hasDrawn) {+ hasDrawn = true+ lastSpend = spend+ host.invalidate()+ }}}@@ -213,8 +231,17 @@ export function createController(state: State, host: Host): Controller {}function start(): void {+ let lastIdleMs = 0+every('refresh', state.options.refreshSeconds * 1000, () => {- void refresh().then(() => probe())+ const now = Date.now()+ const isSeen = state.pane.isOpen || now - state.barDrawnAtMs < BAR_FRESH_MS++ // Nothing on screen reads the disk: re-read only on the idle cadence, so a closed console costs nearly nothing.+ if (isSeen || now - lastIdleMs >= IDLE_REFRESH_MS) {+ lastIdleMs = now+ void refresh().then(() => probe())+ }})every('activity', ACTIVITY_BUCKET_MS, () => {push(state.activity, activityCount)@@ -304,7 +331,7 @@ export function createController(state: State, host: Host): Controller {const error = /"error"\s*:\s*"([^"]{0,160})"/.exec(result.stdout)?.[1]const ok = result.exitCode === 0 && answer !== 'false'- await refresh()+ await freshRead()const verified = state.snapshot === null ? 'n/a' : spec.verify(state.snapshot) ? 'yes' : 'no'@@ -366,7 +393,7 @@ export function createController(state: State, host: Host): Controller {markRequest = requestIdif (isWorking && state.options.fps > 0) {- every('mark', 120, () => {+ every('mark', Math.round(1000 / state.options.fps), () => {if (markRequest !== null) host.blit({ requestId: markRequest, key: 'mark', cells: markPicture(true, Date.now()).encode(), columns: 2, rows: 1 })})} else {diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.tsindex ddc8ae0e7f..005603299f 100644--- a/plugins/ruflo-console/hooks/data/cli.ts+++ b/plugins/ruflo-console/hooks/data/cli.ts@@ -4,7 +4,7 @@* person turns `federationNetwork` on. `plugins list` is never run (it fetches the IPFS registry), nor `verify` (it* fetches a manifest from GitHub).*/-import { jsonObject, msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'+import { msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'export type ViewId = 'overview' | 'swarm' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory'diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.tsindex 8a9bfbc52f..a8b72edf8e 100644--- a/plugins/ruflo-console/hooks/register.ts+++ b/plugins/ruflo-console/hooks/register.ts@@ -171,6 +171,9 @@ export const register: Register = (on, raw: PluginOptions) => {const table = $.ui.resolve(e) as unknown as Kitconst bound = control++ state.barDrawnAtMs = Date.now()+const mark = table.Raster !== undefined ? table.Raster(markPicture(e.props.isWorking, Date.now()).toRaster(BAR_KEY)) : nullbound.markFrame(e.requestId, e.props.isWorking && mark !== null)@@ -178,6 +181,23 @@ export const register: Register = (on, raw: PluginOptions) => {return barView(table, state, Math.floor(Number(e.props.bodyColumns) || 80), mark, () => void bound.open())})+ /** The band's mark pulses during a turn: a redraw at its start, and the loop stopped at its end, whatever redraws. */+ on('turn.start', ($, e, next) => {+ try {+ $.ui.invalidate('ui.render')+ } catch {+ // A refused redraw leaves the mark at rest.+ }++ return next(e)+ })++ on('turn.complete', ($, e, next) => {+ if (e.agentId === undefined) control?.markFrame('', false)++ return next(e)+ })+on('ui.close', async ($, e, next) => {const result = await next(e)diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.tsindex 250a0b284d..07302705b6 100644--- a/plugins/ruflo-console/hooks/state.ts+++ b/plugins/ruflo-console/hooks/state.ts@@ -107,6 +107,8 @@ export type State = {outcome: Outcome | nullisActing: booleanisRefreshing: boolean+ /** When the band above the prompt last drew: the disk is re-read on the fast cadence only while it is seen. */+ barDrawnAtMs: numbertimers: Map<string, Timer>stats: { renders: number[]; refreshes: number[]; frames: number[] }}@@ -134,6 +136,7 @@ export function newState(raw: PluginOptions | undefined): State {outcome: null,isActing: false,isRefreshing: false,+ barDrawnAtMs: 0,timers: new Map(),stats: { renders: [], refreshes: [], frames: [] },}diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.tsindex 013838ac6a..f858f923c3 100644--- a/plugins/ruflo-console/hooks/views/pane.ts+++ b/plugins/ruflo-console/hooks/views/pane.ts@@ -91,7 +91,7 @@ function footer(ctx: Ctx): RenderElement {if (outcome !== null && nowMs - outcome.atMs < 60_000) {parts.push(- text(ctx, `${outcome.ok ? '✓' : '✗'} ${outcome.label}: ${outcome.detail}${outcome.verified === 'yes' ? ' · on disk' : outcome.verified === 'no' ? ' · not on disk yet' : ''}`, {+ text(ctx, `${outcome.ok ? '✓' : '✗'} ${outcome.label}${outcome.verified === 'yes' ? ' · on disk' : outcome.verified === 'no' ? ' · not on disk yet' : ''}: ${outcome.detail}`, {color: outcome.ok ? THEME.ok : THEME.bad,}),)diff --git a/plugins/ruflo-console/scripts/bench.ts b/plugins/ruflo-console/scripts/bench.tsnew file mode 100644index 0000000000..35c9c39288--- /dev/null+++ b/plugins/ruflo-console/scripts/bench.ts@@ -0,0 +1,91 @@+/**+ * Measures the console's pure costs on the captured run (tests/fixtures/ruflo-run.ts): one disk refresh over an+ * in-memory fs (parse cost; the engine's own fs latency is not in it), one full pane tree per view, and one animation+ * frame (every picture of the view drawn and base64-encoded). Prints median and p95 per row.+ * npx -y tsx plugins/ruflo-console/scripts/bench.ts [iterations]+ */+import { PROBES } from '../hooks/data/cli'+import { readSnapshot, type Snapshot } from '../hooks/data/snapshot'+import { newState, VIEWS } from '../hooks/state'+import type { Actions, Kit } from '../hooks/views/common'+import { picturesOf } from '../hooks/views/frames'+import { paneView } from '../hooks/views/pane'+import { CLI_OUT, RUFLO_FILES } from '../tests/fixtures/ruflo-run'++const N = Math.max(10, Number(process.argv[2]) || 300)+const COLUMNS = 110+const files = Object.fromEntries(Object.entries(RUFLO_FILES).map(([path, text]) => [`/work/${path}`, text]))+const fs = {+ read: async (path: string) => files[path] ?? Promise.reject(new Error('ENOENT')),+ stat: async (path: string) => (files[path] !== undefined ? { mtimeMs: 1, size: (files[path] as string).length } : Promise.reject(new Error('ENOENT'))),+ list: async () => [],+}+const element = (type: string) => (props: Record<string, unknown>) => ({ type, props }) as never+const kit = { Box: element('Box'), Text: element('Text'), Button: element('Button'), Raster: element('Raster') } as unknown as Kit+const noop = () => undefined+const act = new Proxy({}, { get: () => noop }) as Actions+const ms = (start: bigint) => Number(process.hrtime.bigint() - start) / 1e6++function stats(samples: number[]): string {+ const sorted = [...samples].sort((a, b) => a - b)+ const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))] ?? 0++ return `median ${at(0.5).toFixed(3)} ms · p95 ${at(0.95).toFixed(3)} ms`+}++async function main() {+ const state = newState({})+ const byProbe: Record<string, string> = { version: 'version', memory: 'memory-stats', namespaces: 'memory-list', metaharness: 'mh-score', flywheel: 'mh-flywheel', intelligence: 'intel', peers: 'bbs-peers', channels: 'channels' }++ for (const probe of PROBES) {+ const name = byProbe[probe.id]++ if (name !== undefined) state.probes.set(probe.id, { value: probe.parse(CLI_OUT[name] ?? ''), okAtMs: Date.now(), error: null, errorAtMs: null, isRunning: false })+ }++ state.cwd = '/work'+ state.activity = Array.from({ length: 60 }, (_, i) => i % 7)+ state.writes = Array.from({ length: 60 }, (_, i) => i % 3)++ const cold: number[] = []+ const warm: number[] = []+ let snapshot: Snapshot | null = null++ for (let i = 0; i < N; i++) {+ let start = process.hrtime.bigint()++ snapshot = await readSnapshot(fs, new Map(), '/work', null, {}, Date.now())+ cold.push(ms(start))+ start = process.hrtime.bigint()+ await readSnapshot(fs, state.cache, '/work', null, {}, Date.now())+ warm.push(ms(start))+ }++ state.snapshot = snapshot+ console.log(`refresh (parse every file) ${stats(cold)}`)+ console.log(`refresh (unchanged files cached) ${stats(warm)}`)++ for (const view of VIEWS) {+ state.view = view.id++ const renders: number[] = []+ const frames: number[] = []++ for (let i = 0; i < N; i++) {+ let start = process.hrtime.bigint()+ const pictures = picturesOf(state, COLUMNS, Date.now(), Date.now())++ paneView({ kit, state, nowMs: Date.now(), columns: COLUMNS, pictures, act })+ renders.push(ms(start))+ start = process.hrtime.bigint()+ for (const grid of picturesOf(state, COLUMNS, Date.now(), Date.now() + i * 125).values()) grid.encode()+ frames.push(ms(start))+ }++ const pictures = [...picturesOf(state, COLUMNS, Date.now(), Date.now()).keys()].join(',') || 'none'++ console.log(`${view.id.padEnd(12)} render ${stats(renders)} · frame [${pictures}] ${stats(frames)}`)+ }+}++void main()diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.shnew file mode 100755index 0000000000..71fe4ee862--- /dev/null+++ b/plugins/ruflo-console/scripts/smoke.sh@@ -0,0 +1,78 @@+#!/usr/bin/env bash+# Structural + security smoke for ruflo-console. Static checks first (CI has no Claude Code), then the pure vitest+# specs. The hooks module's behaviour is held by `claude plugin test plugins/ruflo-console` where function hooks are on.+set -u+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REPO="$(cd "$ROOT/../.." && pwd)"+HOOKS="$ROOT/hooks"+PASS=0+FAIL=0+step() { printf "→ %s ... " "$1"; }+ok() { printf "PASS\n"; PASS=$((PASS+1)); }+bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }++step "1. plugin.json declares ruflo-console 0.1.0"+grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \+ && grep -q '"version": "0.1.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"++step "2. hooks.json names exactly one module and no classic hook commands"+grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \+ && ok || bad "hooks.json must be modules-only"++step "3. no Node, Buffer or dynamic import in the module"+hits=$(grep -rnE "from ['\"]node:|\bBuffer\b|\bimport\(|require\(" "$HOOKS" || true)+[[ -z "$hits" ]] && ok || bad "$hits"++step "4. no import reaches outside the plugin folder"+deep=$(grep -rnE "from ['\"](\.\./){3,}" "$HOOKS" || true)+[[ -z "$deep" ]] && ok || bad "$deep"++step "5. no network call from the module (\$.http) and \$ is touched in register.ts only"+http=$(grep -rnE '\$\.http\.' "$HOOKS" || true)+# Code lines only: comments may name the calls they explain.+outside=$(grep -rnE '\$\.(fs|process|ui|clock|store|env|ruflo|tool|session|settings|command)\.' "$HOOKS" | grep -vE '^[^:]+:[0-9]+:\s*(\*|//|/\*)' | grep -v '/register.ts:' || true)+[[ -z "$http" && -z "$outside" ]] && ok || bad "http: $http outside: $outside"++step "6. never runs plugins list or verify (network) and the roster is the one network probe"+cmds=$(grep -nE "args: \['(plugins|verify)'" "$HOOKS/data/cli.ts" || true)+net=$(grep -c "isNetwork: true" "$HOOKS/data/cli.ts")+[[ -z "$cmds" && "$net" == "1" ]] && grep -q "federationNetwork" "$HOOKS/controller.ts" && ok || bad "cmds: $cmds network probes: $net"++step "7. private key files are never read paths"+# The federation folder is listed for its file names (node ids); a key file's path never reaches fs.read.+keys=$(grep -nE "(key-[^'\"]*\.json|channels\.json|nostr\.key)" "$HOOKS/data/files.ts" | grep -vE "^\s*[0-9]+:\s*(\*|//)|NOSTR_KEY = |test\(entry\.name\)" || true)+grep -q "fs.stat(under(home, NOSTR_KEY))" "$HOOKS/data/files.ts" && [[ -z "$keys" ]] && ok || bad "$keys"++step "8. mutations only through claims_* with JSON.stringify params, behind a confirm"+grep -q "JSON.stringify(params)" "$HOOKS/actions.ts" \+ && [[ "$(grep -oE "exec\('claims_[a-z-]+'" "$HOOKS/actions.ts" | sort -u | tr '\n' ' ')" == "exec('claims_claim' exec('claims_handoff' exec('claims_release' exec('claims_steal' " ]] \+ && grep -q "state.pending = " "$HOOKS/controller.ts" && ok || bad "action surface changed"++step "9. plugin.register and tool.call are observed, never answered"+reg=$(awk '/on\(.plugin.register./,/^ }\)/' "$HOOKS/register.ts" | grep -cE "refuse:|deny:")+tool=$(awk '/on\(.tool.call./,/^ }\)/' "$HOOKS/register.ts" | grep -cE "deny|result:")+[[ "$reg" == "0" && "$tool" == "0" ]] && ok || bad "plugin.register answers: $reg tool.call answers: $tool"++step "10. no secrets or credentials in the module"+sec=$(grep -rniE "(api[_-]?key|secret|password|token)\s*[:=]\s*['\"][^'\"]{8,}" "$HOOKS" || true)+[[ -z "$sec" ]] && ok || bad "$sec"++step "11. every source file is under 500 lines"+long=$(find "$HOOKS" "$ROOT/tests" "$ROOT/scripts" -name '*.ts' -not -path '*/fixtures/ruflo-run.ts' -exec awk 'END { if (NR > 500) print FILENAME }' {} \;)+[[ -z "$long" ]] && ok || bad "$long"++step "12. kit tests are in the CI baseline (root vitest cannot resolve claude-code/testing)"+miss=""+for f in "$ROOT"/tests/*.test.ts; do+ grep -qx "plugins/ruflo-console/tests/$(basename "$f")" "$REPO/scripts/ci-test-baseline.txt" || miss="$miss $(basename "$f")"+done+[[ -z "$miss" ]] && ok || bad "not in baseline:$miss"++step "13. marketplace lists ruflo-console"+grep -q '"name": "ruflo-console"' "$REPO/.claude-plugin/marketplace.json" && ok || bad "missing marketplace entry"++step "14. pure specs pass under vitest"+if (cd "$REPO" && npx vitest run plugins/ruflo-console/tests/pure.spec.ts plugins/ruflo-console/tests/vendored-types.spec.ts >/dev/null 2>&1); then ok; else bad "vitest specs failed"; fi++printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"+[[ $FAIL -eq 0 ]]diff --git a/plugins/ruflo-console/tests/behaviour.test.ts b/plugins/ruflo-console/tests/behaviour.test.tsnew file mode 100644index 0000000000..10cc307df4--- /dev/null+++ b/plugins/ruflo-console/tests/behaviour.test.ts@@ -0,0 +1,245 @@+import { describe, expect, mock, test } from 'claude-code/testing'++import { RUFLO_FILES } from './fixtures/ruflo-run'+import { BAND, command, elementsOf, fakeRuflo, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'++const VIEWS = ['overview', 'swarm', 'claims', 'federation', 'plugins', 'learning', 'metaharness', 'memory'] as const++describe('behaviour', () => {+ test('a tab hotkey switches the view and the choice is kept for this folder only', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command())++ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })++ expect(textOf(await pane.drawn())).toContain('Overview◂')+ await pane.press({ key: 'tab-claims' })+ expect(textOf(await pane.drawn())).toContain('Claims◂')+ expect(world.stored.get('ruflo-console/ui:/work')).toEqual({ view: 'claims' })+ expect(world.opened.length).toBeGreaterThanOrEqual(2)+ await pane.unmount()+ })++ test('claim asks first, runs one fixed argv on yes, and reads the disk to say it took', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ const task = JSON.parse(RUFLO_FILES['.claude-flow/tasks/store.json'] ?? '{}') as { tasks: Record<string, unknown> }+ const taskId = Object.keys(task.tasks)[0] as string+ mock.clock(on)+ world.respond = argv => {+ if (argv.includes('claims_claim')) {+ const store = JSON.parse(world.files.get('/work/.claude-flow/claims/claims.json') as string) as { claims: Record<string, unknown> }+ const params = JSON.parse(argv[argv.length - 1] as string) as { issueId: string; claimant: string }+ const [, agentId, agentType] = params.claimant.split(':')++ store.claims[params.issueId] = { issueId: params.issueId, claimant: { type: 'agent', agentId, agentType }, status: 'active', claimedAt: '2026-10-02T01:20:00.000Z', progress: 0 }+ world.put('.claude-flow/claims/claims.json', JSON.stringify(store))++ return { exitCode: 0, stdout: 'Result:\n{\n "success": true\n}', stderr: '' }+ }++ return { exitCode: 0, stdout: '{}', stderr: '' }+ }+ await $.session.start(SESSION)+ await $.command.run(command('claims'))++ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })++ await pane.press({ key: 'claim' })++ const asking = await pane.drawn()++ expect(textOf(asking)).toContain(`Confirm: claim ${taskId} for coder?`)+ expect(textOf(asking)).toContain('runs: ruflo mcp exec -t claims_claim -p')+ expect(elementsOf(asking, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['confirm', 'cancel']))+ expect(world.runs.filter(argv => argv.includes('claims_claim'))).toHaveLength(0)++ await pane.press({ key: 'confirm' })++ const runs = world.runs.filter(argv => argv.includes('claims_claim'))++ expect(runs).toHaveLength(1)+ expect(runs[0]?.slice(0, 4)).toEqual(['npx', '--offline', '-y', '@claude-flow/cli@latest'])+ expect(JSON.parse(runs[0]?.at(-1) ?? '{}')).toEqual({ issueId: taskId, claimant: 'agent:agent-1790903032181-97m25s:coder' })+ expect(textOf(await pane.drawn())).toContain(`✓ claim ${taskId} for coder · on disk: ruflo answered ok`)+ await pane.unmount()+ })++ test('cancel runs nothing, and a button with nothing to act on says why', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command('claims'))++ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })++ await pane.press({ key: 'release' })+ expect(textOf(await pane.drawn())).toContain('Confirm: release console-demo-1 held by coder?')+ await pane.press({ key: 'cancel' })+ expect(textOf(await pane.drawn())).not.toContain('Confirm:')+ await pane.press({ key: 'steal' })+ expect(textOf(await pane.drawn())).toContain('nothing to do: the picked agent already holds it')+ expect(world.runs.some(argv => argv.some(arg => arg.startsWith('claims_') && arg !== 'claims_board'))).toBe(false)+ await pane.unmount()+ })++ test('every affordance refused: each view still draws, nothing throws, nothing runs', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES, { refuseAll: true })+ mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command())++ for (const view of VIEWS) {+ await $.command.run(command(view))++ const pane = await $.ui.mount({ ...paneAt(100), plugin: PLUGIN })+ const text = textOf(await pane.drawn())++ expect(text).toContain('◂')+ await pane.unmount()+ }++ expect(world.runs).toHaveLength(0)+ })++ test('no ruflo project: views say n/a or how to start, and the band stays out of the way', async ($, on) => {+ worldOf(on, {})+ mock.clock(on)+ on('ui.render', () => ({ type: 'Text', children: ['engine'] }) as never)+ await $.session.start(SESSION)+ await $.command.run(command('overview'))+ await $.command.run(command('status'))++ const overview = textOf(await $.ui.render(paneAt(110)))++ expect(overview).toContain('n/a — no .claude-flow here')+ expect(overview).toContain('n/a — no swarm on disk')+ expect(overview).not.toMatch(/\b0 agents\b/)+ await $.command.run(command('swarm'))+ expect(textOf(await $.ui.render(paneAt(110)))).toContain('No swarm on disk here')+ expect(textOf(await $.ui.render(BAND))).toBe('engine')+ })++ test('narrow terminals get text only: no Raster, one tab line, no claims buttons', async ($, on) => {+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command('claims'))+ await $.command.run(command('status'))++ for (const [columns, rows] of [[24, 12], [30, 30], [43, 40], [44, 40], [120, 8], [160, 60]] as const) {+ const pane = await $.ui.mount({ ...paneAt(columns, rows), plugin: PLUGIN })+ const tree = await pane.drawn()+ const isNarrow = columns - 1 < 44++ expect(elementsOf(tree, 'Raster').length === 0).toBe(isNarrow)+ expect(elementsOf(tree, 'Button').map(keyOf).includes('claim')).toBe(!isNarrow)+ if (isNarrow) expect(textOf(tree)).toContain('3/8 Claims')+ await pane.unmount()+ }+ })++ test('the frame loop blits while shown and focused, and stops when hidden or unfocused', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ const clock = mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command('swarm'))+ await $.command.run(command('status'))++ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })++ for (let i = 0; i < 6; i++) await clock.advance(125)+ expect(world.blits.filter(key => key === 'topology').length).toBeGreaterThan(2)++ const panes = world.panes[0]++ if (panes !== undefined) panes.isShown = false+ await clock.advance(1_000)++ const hidden = world.blits.length++ for (let i = 0; i < 8; i++) await clock.advance(125)+ expect(world.blits.length).toBe(hidden)+ await pane.unmount()+ })++ test('unfocused, the pane draws but does not animate', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ const clock = mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command('swarm'))++ const opened = world.panes[0]++ if (opened !== undefined) opened.isFocused = false++ const pane = await $.ui.mount({ ...paneAt(110, 40, false), plugin: PLUGIN })++ for (let i = 0; i < 12; i++) await clock.advance(125)+ expect(textOf(await pane.drawn())).toContain('keys: off')+ expect(world.blits).toHaveLength(0)+ await pane.unmount()+ })++ test('hostile text: control and bidi characters never reach the tree, bad ids are dropped', async ($, on) => {+ const agents = JSON.parse(RUFLO_FILES['.claude-flow/agents/store.json'] ?? '{}') as { agents: Record<string, Record<string, unknown>> }+ const first = Object.values(agents.agents)[0] as Record<string, unknown>++ first.name = 'c1\u001b[31m‮EVIL\u0000'+ const claims = { claims: { 'bad id!': { issueId: 'bad id!', claimant: { type: 'agent', agentId: 'x', agentType: 'coder' }, status: 'active' } } }++ worldOf(on, { ...RUFLO_FILES, '.claude-flow/agents/store.json': JSON.stringify(agents), '.claude-flow/claims/claims.json': JSON.stringify(claims) })+ mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command('swarm'))+ await $.command.run(command('status'))++ const swarm = textOf(await $.ui.render(paneAt(110)))++ expect(swarm).toContain('c1 [31m EVIL')+ expect(swarm).not.toMatch(/[\u0000-\u001f‪-‮](?<!\n)/)+ await $.command.run(command('claims'))+ expect(textOf(await $.ui.render(paneAt(110)))).toContain('No claims on disk')+ })++ test('the band: one line of facts, yields to a survey, and its mark pulses only during a turn', async ($, on) => {+ fakeRuflo().register(on, {})+ const world = worldOf(on, RUFLO_FILES)+ const clock = mock.clock(on)+ on('ui.render', () => ({ type: 'Text', children: ['engine'] }) as never)+ await $.session.start(SESSION)+ await $.command.run(command('status'))++ expect(textOf(await $.ui.render(BAND))).toContain('ruflo · hierarchical 0/2 busy · 2 claims (1 stealable) · 30.8k patterns · → tester · $0.42')+ expect(textOf(await $.ui.render({ ...BAND, props: { ...BAND.props, hasSurvey: true } }))).toBe('engine')++ await $.ui.render({ ...BAND, props: { ...BAND.props, isWorking: true } })+ for (let i = 0; i < 4; i++) await clock.advance(125)+ expect(world.blits.filter(key => key === 'mark').length).toBeGreaterThan(1)++ await $.turn.complete({ answer: 'ok', durationMs: 5, isAborted: false, turnId: 't1', reason: 'answer' } as never)++ const stopped = world.blits.length++ for (let i = 0; i < 4; i++) await clock.advance(125)+ expect(world.blits.length).toBe(stopped)+ })++ test('on the desktop surface, which has no Raster, every picture becomes a text line and the tree is accepted', async ($, on) => {+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ for (const view of VIEWS) {+ await $.command.run(command(view))++ const pane = await $.ui.mount({ ...paneAt(110, 40, true, 'desktop'), plugin: PLUGIN })+ const tree = await pane.drawn()++ expect(pane.surface).toBe('desktop')+ expect(elementsOf(tree, 'Raster')).toHaveLength(0)+ await pane.unmount()+ }+ })+})diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.tsindex b81808f698..204521d6d6 100644--- a/plugins/ruflo-console/tests/fixtures/world.ts+++ b/plugins/ruflo-console/tests/fixtures/world.ts@@ -96,9 +96,11 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, optionsreturn refuse || names.length === 0 ? { deny: 'ENOENT' } : { value: names.map(name => ({ name, kind: 'file' as const, size: 1, mtimeMs: 1, isLink: false })) }})on('process.run', ($, e) => {+ if (refuse) return { deny: 'process.run withheld' }+world.runs.push([...e.argv])- const answer = refuse ? { deny: 'process.run withheld' } : world.respond(e.argv)+ const answer = world.respond(e.argv)return 'deny' in answer ? { deny: answer.deny } : { value: { ...answer, isStdoutTruncated: false, isStderrTruncated: false } }})@@ -135,6 +137,8 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, optionsreturn { value: {} }})on('ui.toast', () => ({ value: undefined }))+ on('turn.start', ($, e) => ({ turnId: e.turnId }))+ on('turn.complete', ($, e) => ({ text: e.answer }))return world}diff --git a/plugins/ruflo-console/tests/pure.spec.ts b/plugins/ruflo-console/tests/pure.spec.tsnew file mode 100644index 0000000000..50b3d66471--- /dev/null+++ b/plugins/ruflo-console/tests/pure.spec.ts@@ -0,0 +1,180 @@+/**+ * The console's pure parts under vitest, beside the engine kit's run of the whole mod (*.test.ts): readers, CLI JSON,+ * cell graphics, and the frame functions. They import nothing from the engine at run time. Run with+ * npx vitest run plugins/ruflo-console+ */+import { describe, expect, it } from 'vitest'++import { jsonAfter, PROBES } from '../hooks/data/cli'+import { parseMarketplaces, parseNeural, parseOutcomes, parseRouter } from '../hooks/data/facts'+import { readBounded, READ_MAX, type ReadCache } from '../hooks/data/files'+import { idOf, parseAgents, parseClaims, parseHive, parseSwarmStore, plain } from '../hooks/data/parse'+import { readSnapshot } from '../hooks/data/snapshot'+import { activityPicture, claimsPicture, curvePicture, markPicture, scorePicture, topologyPicture } from '../hooks/gfx/pictures'+import { Grid, toBase64 } from '../hooks/gfx/raster'+import { newState } from '../hooks/state'+import { picturesOf, topoModelOf } from '../hooks/views/frames'+import { ladder } from '../hooks/views/memory'+import { CLI_OUT, HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'++const at = (path: string) => RUFLO_FILES[path] ?? null++const memoryFs = (files: Record<string, string>) => ({+ read: async (path: string) => files[path] ?? Promise.reject(new Error('ENOENT')),+ stat: async (path: string) => (files[path] !== undefined ? { mtimeMs: 1, size: (files[path] as string).length } : Promise.reject(new Error('ENOENT'))),+ list: async () => Promise.reject(new Error('ENOENT')),+})++describe('readers', () => {+ it('read the captured run: one swarm, two agents, two claims (one stealable), a queen and a proposal, no token', () => {+ expect(parseSwarmStore(at('.claude-flow/swarm/swarm-state.json'))).toMatchObject({ id: 'swarm-1790903031804-y9rnjr', topology: 'hierarchical', status: 'running', strategy: 'specialized', maxAgents: 6 })+ expect(parseAgents(at('.claude-flow/agents/store.json')).map(agent => `${agent.type}:${agent.status}`)).toEqual(['coder:idle', 'tester:idle'])++ const claims = parseClaims(at('.claude-flow/claims/claims.json'))++ expect(claims.map(claim => [claim.issueId, claim.isStealable])).toEqual([+ ['console-demo-1', false],+ ['console-demo-2', true],+ ])+ expect(claims[0]?.expiresAtMs).toBeUndefined()++ const hive = parseHive(at('.claude-flow/hive-mind/state.json'))++ expect(hive?.queen).toMatch(/^queen-/)+ expect(hive?.pending[0]).toMatchObject({ type: 'design', strategy: 'raft', votesFor: 0 })+ expect(JSON.stringify(hive)).not.toContain(HIVE_TOKEN)+ })++ it('learning stores: counts as written, a rate with its N, a default never taken as a measurement', () => {+ expect(parseNeural(at('.claude-flow/neural/stats.json'))).toMatchObject({ trajectories: 30797, patterns: 30781 })+ expect(parseOutcomes(at('.claude-flow/routing-outcomes.json'))).toMatchObject({ total: 9, successes: 9 })+ expect(parseRouter(at('.swarm/model-router-state.json'))).toMatchObject({ decisions: 11 })+ expect(parseNeural('not json')).toBeNull()+ expect(parseOutcomes('{"outcomes": [{"success": "yes"}]}')).toEqual({ total: 0, successes: 0, points: [] })+ })++ it('plain strips control and bidi characters; idOf admits only id-shaped strings', () => {+ expect(plain('a\u001b[31m‮b\u0000c')).toBe('a [31m b c')+ expect(plain('x'.repeat(50), 10)).toHaveLength(10)+ expect(idOf('agent-1790903032181-97m25s')).toBe('agent-1790903032181-97m25s')+ for (const bad of ['bad id!', '-rf', '', 'a'.repeat(200), '../etc', 42]) expect(idOf(bad)).toBeNull()+ })++ it('a marketplace path with .. or not absolute is never followed', () => {+ const markets = parseMarketplaces(JSON.stringify({ a: { installLocation: '/x/../etc' }, b: { installLocation: 'relative' }, ruflo: { installLocation: '/home/dev/m/ruflo' } }))++ expect(markets?.map(market => market.location)).toEqual([undefined, undefined, '/home/dev/m/ruflo'])+ })++ it('a file over the read cap is stat-ed, never read', async () => {+ let reads = 0+ const fs = { read: async () => ((reads += 1), 'x'), stat: async () => ({ mtimeMs: 1, size: READ_MAX + 1 }), list: async () => [] }++ expect(await readBounded(fs, new Map(), '/work/.claude-flow/policy/state.json')).toEqual({ text: null, reason: 'too-large', size: READ_MAX + 1 })+ expect(reads).toBe(0)+ })++ it('the snapshot names a stale marketplace clone by what it lacks, and an unchanged file is not read twice', async () => {+ const files: Record<string, string> = {+ ...Object.fromEntries(Object.entries(RUFLO_FILES).map(([path, text]) => [`/work/${path}`, text])),+ '/home/dev/.claude/plugins/known_marketplaces.json': JSON.stringify({ ruflo: { installLocation: '/home/dev/m/ruflo' } }),+ '/home/dev/m/ruflo/.claude-plugin/marketplace.json': JSON.stringify({ plugins: [{ name: 'ruflo-core' }, { name: 'ruflo-swarm' }] }),+ }+ const fs = memoryFs(files)+ const cache: ReadCache = new Map()+ const first = await readSnapshot(fs, cache, '/work', '/home/dev', {}, 0)++ expect(first.plugins.missingFromClone).toEqual(['ruflo-mods'])+ expect(first.isRufloProject).toBe(true)++ let reads = 0+ const counting = { ...fs, read: async (path: string) => ((reads += 1), fs.read(path)) }++ await readSnapshot(counting, cache, '/work', '/home/dev', {}, 1)+ expect(reads).toBe(0)+ })+})++describe('CLI JSON', () => {+ it('every captured probe output parses, log lines and the mcp exec header notwithstanding', () => {+ const byProbe: Record<string, string> = { version: 'version', memory: 'memory-stats', namespaces: 'memory-list', metaharness: 'mh-score', flywheel: 'mh-flywheel', intelligence: 'intel', peers: 'bbs-peers', channels: 'channels' }++ for (const probe of PROBES) {+ const name = byProbe[probe.id]++ if (name === undefined) continue++ expect(probe.parse(CLI_OUT[name] ?? ''), probe.id).not.toBeNull()+ }++ expect(jsonAfter('Transformers.js loaded: x\n{\n "a": 1\n}\n')).toEqual({ a: 1 })+ expect(jsonAfter('[INFO] Executing tool\nResult:\n{\n "b": [1]\n}')).toEqual({ b: [1] })+ expect(jsonAfter('no json here')).toBeNull()+ })++ it('no probe reaches the network but the opt-in roster; plugins list and verify are never run', () => {+ expect(PROBES.filter(probe => probe.isNetwork === true).map(probe => probe.id)).toEqual(['roster'])++ for (const probe of PROBES) {+ expect(probe.args.slice(0, 2).join(' ')).not.toBe('plugins list')+ expect(probe.args[0]).not.toBe('verify')+ }+ })++ it('the intelligence probe drops the default confidence the tool answers before any decision', () => {+ const intel = PROBES.find(probe => probe.id === 'intelligence')?.parse(CLI_OUT.intel ?? '') as { routerConfidence?: number; routerDecisions?: number }++ expect(intel.routerDecisions).toBe(0)+ expect(intel.routerConfidence).toBeUndefined()+ })+})++describe('graphics', () => {+ it('toBase64 matches Buffer for every length 0..17', () => {+ for (let n = 0; n <= 17; n++) {+ const bytes = Uint8Array.from({ length: n }, (_, i) => (i * 37 + 11) & 255)++ expect(toBase64(bytes)).toBe(Buffer.from(bytes).toString('base64'))+ }+ })++ it('every picture keeps its size across time, so a blit always fits the mounted Raster', () => {+ const model = topoModelOf({ swarm: parseSwarmStore(at('.claude-flow/swarm/swarm-state.json')), hive: parseHive(at('.claude-flow/hive-mind/state.json')), agents: parseAgents(at('.claude-flow/agents/store.json')).map(agent => ({ ...agent, status: 'busy' })) } as never)++ for (const t of [0, 1234, 99_999]) {+ const pictures: Grid[] = [+ topologyPicture(model ?? { topology: 'mesh', nodes: [] }, 80, 12, t),+ activityPicture([{ label: 'a', values: [1, 2, 3] }, { label: 'b', values: [] }], 80, t),+ curvePicture([true, false, true], 80, 6, t),+ claimsPicture([{ label: 'x', isStealable: false, claimedAtMs: 0 }, { label: 'y', isStealable: true, claimedAtMs: 0, expiresAtMs: 10_000 }], 80, 2, t),+ scorePicture([{ name: 'harnessFit', value: 42 }], 80, t, 0),+ markPicture(true, t),+ ]++ expect(pictures.map(grid => [grid.columns, grid.rows])).toEqual([[80, 12], [80, 2], [80, 6], [80, 2], [80, 1], [2, 1]])+ for (const grid of pictures) expect(grid.encode().length).toBe(Math.ceil((grid.columns * grid.rows * 12) / 3) * 4)+ }+ })++ it('a TTL counts down and an age counts up on the real clock', () => {+ const glyphs = (grid: Grid) => Array.from({ length: grid.columns }, (_, x) => String.fromCodePoint(grid.glyph(x, 0))).join('')+ const ttl = { label: 'c', isStealable: false, claimedAtMs: 0, expiresAtMs: 100_000 }++ expect(glyphs(claimsPicture([ttl], 60, 1, 10_000))).toContain('ttl 1m30s')+ expect(glyphs(claimsPicture([ttl], 60, 1, 200_000))).toContain('ttl expired')+ expect(glyphs(claimsPicture([{ label: 'c', isStealable: false, claimedAtMs: 0 }], 60, 1, 3_600_000))).toContain('age 1h00m')+ })++ it('the frame functions answer the same pictures for the render and the loop', () => {+ const state = newState({})++ state.view = 'learning'+ expect([...picturesOf(state, 90, 0, 5).keys()]).toEqual(['curve'])+ state.view = 'federation'+ expect(picturesOf(state, 90, 0, 5).size).toBe(0)+ })++ it('the budget ladder marks 50/75/90/100% and fills to the spend', () => {+ expect(ladder(3.9, 5, 20)).toBe('█████████│████│█·│·│')+ })+})diff --git a/plugins/ruflo-console/tests/vendored-types.spec.ts b/plugins/ruflo-console/tests/vendored-types.spec.tsnew file mode 100644index 0000000000..ab22ee6496--- /dev/null+++ b/plugins/ruflo-console/tests/vendored-types.spec.ts@@ -0,0 +1,37 @@+/**+ * Parity: types/index.d.ts vendors the `$.ruflo` contract from plugins/ruflo-mods/types/index.d.ts (ADR-404). If the+ * source changes shape, this fails instead of the console silently reading "ruflo-mods not seated".+ */+import { existsSync, readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++import { describe, expect, it } from 'vitest'++const here = dirname(fileURLToPath(import.meta.url))+const VENDORED = join(here, '../types/index.d.ts')+const SOURCE = join(here, '../../ruflo-mods/types/index.d.ts')++const norm = (text: string) => text.replace(/\/\*\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').trim()+const pick = (text: string, re: RegExp) => norm(re.exec(text)?.[0] ?? '')++describe.skipIf(!existsSync(SOURCE))('vendored $.ruflo', () => {+ const vendored = readFileSync(VENDORED, 'utf8')+ const source = readFileSync(SOURCE, 'utf8')++ it.each([+ ['RufloSegment', /export type RufloSegment = [^\n]+/],+ ['RufloRoute', /export type RufloRoute = \{[\s\S]*?\n\}/],+ ['RufloSnapshot', /export type RufloSnapshot = \{[\s\S]*?\n\}/],+ ])('%s matches ruflo-mods', (_name, re) => {+ expect(pick(source, re)).not.toBe('')+ expect(pick(vendored, re)).toBe(pick(source, re))+ })++ it('the three methods keep their signatures', () => {+ for (const method of ['segment: (input: RufloSegment) => Promise<void>', 'lastRoute: () => Promise<RufloRoute | null>', 'snapshot: () => Promise<RufloSnapshot>']) {+ expect(source).toContain(method)+ expect(vendored).toContain(method)+ }+ })+})diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txtindex 4ffe248215..21edeb280f 100644--- a/scripts/ci-test-baseline.txt+++ b/scripts/ci-test-baseline.txt@@ -157,3 +157,7 @@ plugins/ruflo-ruos/tests/validate-autostop.test.mjsplugins/ruflo-ruos/tests/vendored-types.test.mjs# ruflo-ruos mod test: imports 'claude-code/testing' (run by `claude plugin test plugins/ruflo-ruos`)plugins/ruflo-ruos/tests/mod.test.ts+# ruflo-console: Claude Code engine-kit tests (import 'claude-code/testing', run by `claude plugin test plugins/ruflo-console`);+# root vitest cannot resolve that import. The pure readers and graphics run under root vitest via tests/*.spec.ts+plugins/ruflo-console/tests/behaviour.test.ts+plugins/ruflo-console/tests/views.test.ts