🌊 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): one /ruflo command, auto-start, diagrams, palette and management views
ruvcbbabb8339ba
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.jsonindex f72e7bd728..62cabef4d2 100644--- a/plugins/ruflo-console/.claude-plugin/plugin.json+++ b/plugins/ruflo-console/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "ruflo-console",- "description": "ruflo's real-time cockpit inside Claude Code (function hooks, early access): a pane of eight views — overview, swarm topology graph, claims board with TTL bars and confirm-gated claim/release/handoff/steal, federation, plugins and marketplace freshness, self-learning curve, MetaHarness score and flywheel, memory and cost ladder — plus a one-line band above the prompt. Reads ruflo's files and the ruflo CLI's local JSON; anything not measured reads n/a.",+ "description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a; no network by default.","version": "0.1.0","author": {"name": "ruvnet",@@ -8,14 +8,33 @@},"homepage": "https://github.com/ruvnet/ruflo","license": "MIT",- "keywords": ["ruflo", "mods", "function-hooks", "pane", "console", "dashboard", "swarm", "claims", "federation", "metaharness"],+ "keywords": [+ "approvals",+ "claims",+ "console",+ "dashboard",+ "federation",+ "function-hooks",+ "metaharness",+ "mods",+ "palette",+ "pane",+ "ruflo",+ "swarm",+ "timeline"+ ],"userConfig": {"cli": {"type": "string","title": "ruflo CLI","description": "How the console reaches ruflo. npx-offline (default) uses the locally cached @claude-flow/cli and never touches the network; npx may download it; ruflo and claude-flow use a global install.","default": "npx-offline",- "options": ["npx-offline", "npx", "ruflo", "claude-flow"]+ "options": [+ "npx-offline",+ "npx",+ "ruflo",+ "claude-flow"+ ]},"refreshSeconds": {"type": "number",@@ -26,7 +45,7 @@"fps": {"type": "number","title": "Animation frames per second",- "description": "Frame cap while the pane is shown and holds the keys (0 to 10; 0 turns motion off). Hidden or unfocused, nothing animates.",+ "description": "Frame cap while the pane is shown and holds the keys (0 to 12; 0 turns motion off). Hidden, unfocused or closed, nothing animates.","default": 8},"bar": {@@ -34,7 +53,22 @@"title": "Band above the prompt","description": "auto shows the one-line ruflo band in a ruflo project; on shows it everywhere; off hides it (the console then adds a 'console' segment to ruflo-mods' status line instead).","default": "auto",- "options": ["auto", "on", "off"]+ "options": [+ "auto",+ "on",+ "off"+ ]+ },+ "panel": {+ "type": "string",+ "title": "Cockpit pane",+ "description": "auto opens the cockpit at session start where it docks beside the transcript (a terminal 144 columns or wider), never taking the keys; elsewhere the band says /ruflo to open. command opens it only with /ruflo. off never opens it unasked.",+ "default": "auto",+ "options": [+ "auto",+ "command",+ "off"+ ]},"federationNetwork": {"type": "boolean",diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.tsindex ca354c085d..2b1e08d71a 100644--- a/plugins/ruflo-console/hooks/actions.ts+++ b/plugins/ruflo-console/hooks/actions.ts@@ -10,10 +10,12 @@ export type ActionSpec = {label: stringargs: readonly string[]expect: string- verify: (snapshot: Snapshot) => boolean+ verify?: (snapshot: Snapshot) => boolean+ /** Reads only: runs at once, without the confirm step, and shows what the CLI printed. */+ isReadOnly?: boolean}-const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const+export const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as constconst SAFE_WORD = /^[A-Za-z0-9_.-]{1,40}$//** `agent:<id>:<type>` or `human:<id>:<name>`, the forms ruflo's claims tools parse; null when a part would not survive it. */diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.tsnew file mode 100644index 0000000000..c343ae84d1--- /dev/null+++ b/plugins/ruflo-console/hooks/bindings.ts@@ -0,0 +1,116 @@+/**+ * The closures the pane's buttons and `/ruflo` subcommands call: view switches, selection, the claims buttons, the+ * palette. Each does its work through the runner or the controller functions it is handed; nothing here touches `$`.+ */+import { claimTask, handoffClaim, releaseClaim, stealClaim, whyNot } from './actions'+import { EVENT_KINDS } from './data/events'+import { plain } from './data/parse'+import type { Host } from './host'+import { filterPalette, paletteEntries } from './palette'+import type { Runner } from './runner'+import type { State } from './state'+import type { Actions } from './views/common'+import { openTasks, selection } from './views/select'++export type Steps = {+ freshRead: () => Promise<void>+ probe: (force?: boolean) => Promise<void>+ setView: (view: State['view']) => void+ drill: (agentId: string) => void+ close: () => Promise<void>+}++export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps): Actions {+ const { freshRead, probe, setView, drill, close } = steps++ /** j/k: what moves depends on the view in front. */+ function select(by: number): void {+ const view = state.view+ const key = view === 'claims' ? 'claim' : view === 'swarm' || view === 'timeline' || view === 'agent' ? 'agent' : 'item'++ state.select[key] += by++ const next = view === 'agent' ? selection(state).agent : null++ // In the drill-down, j/k walks to the next agent and asks for its logs.+ if (next !== null) drill(next.id)+ host.invalidate()+ }++ const actions: Actions = {+ view: setView,+ refresh: () => void freshRead().then(() => probe(true)),+ help: () => {+ state.isHelp = !state.isHelp+ host.invalidate()+ },+ close: () => void close(),+ back: () => setView(state.view === 'agent' ? state.back : 'overview'),+ confirm: () => void runner.confirm(),+ cancel: runner.cancel,+ select,+ agentNext: () => {+ state.select.agent += 1+ host.invalidate()+ },+ taskNext: () => {+ state.select.task += 1+ host.invalidate()+ },+ drill: () => {+ const agent = selection(state).agent++ if (agent !== null) drill(agent.id)+ },+ claim: () => {+ const { agent, task, claim } = selection(state)++ runner.ask(task !== null && agent !== null ? claimTask(task, agent) : null, whyNot('claim', claim, agent, openTasks(state)[0] ?? task))+ },+ release: () => {+ const { claim, agent, task } = selection(state)++ runner.ask(claim !== null ? releaseClaim(claim) : null, whyNot('release', claim, agent, task))+ },+ handoff: () => {+ const { claim, agent, task } = selection(state)++ runner.ask(claim !== null && agent !== null ? handoffClaim(claim, agent) : null, whyNot('handoff', claim, agent, task))+ },+ steal: () => {+ const { claim, agent, task } = selection(state)++ runner.ask(claim !== null && agent !== null ? stealClaim(claim, agent) : null, whyNot('steal', claim, agent, task))+ },+ palette: context => {+ state.palette = { isOpen: !state.palette.isOpen || state.palette.context !== context, query: '', index: 0, context }+ state.isHelp = false+ host.invalidate()+ },+ paletteQuery: text => {+ state.palette.query = plain(text, 200)+ state.palette.index = 0+ host.invalidate()+ },+ paletteRun: id => {+ const entry = paletteEntries(state, Date.now()).find(candidate => candidate.id === id)++ if (entry !== undefined) runner.runEntry(entry, entry.run.kind === 'text' ? state.palette.query.trim().slice(entry.run.keyword.length).trim() : '')+ },+ paletteSubmit: () => {+ const best = filterPalette(paletteEntries(state, Date.now()), state.palette.query, state.palette.context)[0]++ if (best !== undefined) runner.runEntry(best, best.run.kind === 'text' ? state.palette.query.trim().slice(best.run.keyword.length).trim() : '')+ },+ run: (id, text = '') => runner.runById(id, text),+ filter: () => {+ const order = ['all', ...EVENT_KINDS] as const+ const at = order.indexOf(state.eventFilter)++ state.eventFilter = order[(at + 1) % order.length] ?? 'all'+ host.invalidate()+ },+ }++ return actions+}diff --git a/plugins/ruflo-console/hooks/commands.ts b/plugins/ruflo-console/hooks/commands.tsnew file mode 100644index 0000000000..89f800a3c5--- /dev/null+++ b/plugins/ruflo-console/hooks/commands.ts@@ -0,0 +1,101 @@+/**+ * `/ruflo`, the one command for every ruflo mod. Pure: it reads the arguments into an intent; register.ts carries it+ * out. `mods` and `swarm <sub>` belong to ruflo-mods and ruflo-swarm, which hook the same command; the console passes+ * them on and answers only when neither is loaded. Every pane key has a subcommand here, since keys need focus.+ */+import { EVENT_KINDS, type EventKind } from './data/events'+import { VIEWS, viewOf, type ViewId } from './state'++export const SWARM_SUBS = ['pane', 'status', 'topology', 'claims', 'consensus'] as const++export type Intent =+ | { kind: 'open'; view: ViewId | null }+ | { kind: 'help' }+ | { kind: 'close' }+ | { kind: 'status' }+ | { kind: 'delegate'; owner: 'ruflo-mods' | 'ruflo-swarm'; words: string }+ | { kind: 'palette'; query: string }+ | { kind: 'run'; paletteId: string; text: string }+ | { kind: 'confirm'; isYes: boolean }+ | { kind: 'agent'; who: string }+ | { kind: 'back' }+ | { kind: 'select'; by: number }+ | { kind: 'filter'; filter: 'all' | EventKind }+ | { kind: 'unknown'; word: string }++export function parseRuflo(args: string): Intent {+ const words = args.trim().split(/\s+/).filter(Boolean)+ const [head = '', second = ''] = words.map(word => word.toLowerCase())+ const rest = args.trim().slice(words[0]?.length ?? 0).trim()++ switch (head) {+ case '':+ case 'open':+ return { kind: 'open', view: null }+ case 'help':+ case '?':+ return { kind: 'help' }+ case 'close':+ return { kind: 'close' }+ case 'status':+ return { kind: 'status' }+ case 'mods':+ return { kind: 'delegate', owner: 'ruflo-mods', words: rest }+ case 'swarm':+ return (SWARM_SUBS as readonly string[]).includes(second) ? { kind: 'delegate', owner: 'ruflo-swarm', words: rest } : { kind: 'open', view: 'swarm' }+ case 'palette':+ case 'p':+ return { kind: 'palette', query: rest }+ case 'run':+ case 'act':+ return second === '' ? { kind: 'palette', query: '' } : { kind: 'run', paletteId: second, text: rest.slice(second.length).trim() }+ case 'yes':+ case 'y':+ return { kind: 'confirm', isYes: true }+ case 'no':+ case 'n':+ return { kind: 'confirm', isYes: false }+ case 'agent':+ return second === '' ? { kind: 'open', view: 'swarm' } : { kind: 'agent', who: words[1] ?? '' }+ case 'back':+ return { kind: 'back' }+ case 'next':+ case 'j':+ return { kind: 'select', by: 1 }+ case 'prev':+ case 'k':+ return { kind: 'select', by: -1 }+ case 'filter':+ return { kind: 'filter', filter: (EVENT_KINDS as readonly string[]).includes(second) ? (second as EventKind) : 'all' }+ default: {+ const view = viewOf(head)++ return view !== null ? { kind: 'open', view } : { kind: 'unknown', word: head }+ }+ }+}++export const HELP = [+ '/ruflo — the ruflo console and every ruflo mod command',+ '',+ 'Open and switch',+ ` /ruflo open the cockpit (also opens by itself where it can dock, panel=auto)`,+ ` /ruflo <view> ${VIEWS.map(view => `${view.id} (${view.key})`).join(', ')}`,+ ' /ruflo agent <id|name> drill into one agent: role, task, claims, activity, logs, timeline',+ ' /ruflo back | close | status',+ '',+ 'Act (each change asks to confirm; /ruflo yes or /ruflo no answers without focus)',+ ' /ruflo palette [query] the command palette (key p): spawn, claims, swarm, votes, workers, memory',+ ' /ruflo run <entry> [text] run a palette entry by id, e.g. run spawn-coder, run route fix the login bug',+ ' /ruflo next | prev move the selection (keys j / k)',+ ' /ruflo filter <kind> events view filter: all, swarm, claims, federation, learning, tools, mods',+ '',+ 'Other mods (answered by their own plugin)',+ ' /ruflo mods ruflo-mods: what this session routed, recorded and tightened (was /ruflo-mods)',+ ' /ruflo swarm pane|status|topology|claims|consensus ruflo-swarm (was /ruflo-swarm-*)',+ '',+ 'Pane keys (while it holds the keyboard: click it, or ctrl+x tab)',+ ' 1-9 views · g timeline · q approvals · e events · p palette · x actions for the selection',+ ' j/k select · d drill in · b back · r refresh · h help · f event filter · y/n confirm · Esc close',+ ' (? and Enter cannot be pane hotkeys in this Claude Code build: use h, and d to drill in)',+].join('\n')diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.tsindex 7c8d427ca9..e92eaee423 100644--- a/plugins/ruflo-console/hooks/controller.ts+++ b/plugins/ruflo-console/hooks/controller.ts@@ -1,21 +1,23 @@/**- * Everything the console does over time, as plain functions over a Host: the disk refresh, the CLI probes, the- * animation loop, and the claims actions with their confirm step. Nothing here reaches `$` but through the Host.+ * Everything the console does over time, as plain functions over a Host: the disk refresh and the event diff, the CLI+ * probes, the pane's lifecycle (auto-open without taking the keys), and the animation loop. Actions go through+ * ./runner. Nothing here reaches `$` but through the Host.*/-import { claimTask, handoffClaim, releaseClaim, stealClaim, whyNot, type ActionSpec } from './actions'+import { actionsOf } from './bindings'import { PROBES, type ProbeResult } from './data/cli'+import { diffEvents, record } from './data/events'import { plain } from './data/parse'import { readSnapshot } from './data/snapshot'import { markPicture } from './gfx/pictures'import type { Host } from './host'-import { CLI_PREFIXES, PANE_ID, push, storeKeyOf, VIEWS, type State } from './state'+import { agentLogs } from './ops'+import { createRunner, type Runner } from './runner'+import { CLI_PREFIXES, PANE_ID, push, rowsOf, storeKeyOf, type State } from './state'import type { Actions } from './views/common'import { picturesOf } from './views/frames'-import { selection, openTasks } from './views/select'const ACTIVITY_BUCKET_MS = 5_000const PANE_WATCH_MS = 1_000-const PENDING_TTL_MS = 30_000const MAX_PARALLEL_PROBES = 2const BAR_FRESH_MS = 10_000const IDLE_REFRESH_MS = 30_000@@ -29,11 +31,15 @@ export type Controller = {resume: () => voidstop: () => voidopen: (focus?: boolean) => Promise<{ isPlaced: boolean; reason: string }>+ /** At session start, with `panel: auto`: opens where it docks, never taking the keys; else leaves a hint. */+ autoOpen: () => voidclose: () => Promise<void>setView: (view: State['view']) => void+ drill: (agentId: string) => voidanimate: () => void- noteToolCall: () => void+ noteToolCall: (agentId: string | undefined, tool: string) => voidactions: Actions+ runner: Runner/** Blits the band's mark while Claude works; the band calls it with its requestId. */markFrame: (requestId: string, isWorking: boolean) => void}@@ -53,20 +59,17 @@ export const p95 = (values: readonly number[]) => sorted(values)[Math.min(valuesexport function createController(state: State, host: Host): Controller {let activityCount = 0- let pendingSpec: ActionSpec | null = nulllet markRequest: string | null = nulllet lastSegment: string | null | undefinedlet lastSpend: number | undefinedlet hasDrawn = falselet toolsCountedAt = 0+ let inflight: Promise<void> | null = nullconst lastAttempt = new Map<string, number>()- const persist = () => void host.storeSet(storeKeyOf(state.cwd), { view: state.view }).catch(() => undefined)+ const persist = () => void host.storeSet(storeKeyOf(state.cwd), { view: state.view === 'agent' ? state.back : state.view, isClosedByPerson: state.pane.isClosedByPerson }).catch(() => undefined)const isVisible = () => state.pane.isOpen && state.pane.isShown- let inflight: Promise<void> | null = null-- /** Re-reads the disk and the ruflo noun; a call while one runs joins it rather than starting a second. */function refresh(): Promise<void> {inflight ??= readAll().finally(() => {inflight = null@@ -99,7 +102,7 @@ export function createController(state: State, host: Host): Controller {void host.rufloTools().then(counted => void (state.rufloTools = counted), () => undefined)}- const [settings, usage, snapshot, route] = await Promise.all([+ const [settings, usage, ruflo, route] = await Promise.all([host.settings().catch(() => null),host.usage().catch(() => null),host.rufloSnapshot().catch((error: unknown) => {@@ -109,12 +112,35 @@ export function createController(state: State, host: Host): Controller {}),host.rufloRoute().catch(() => null),])+ const previous = state.snapshot+ const now = Date.now()+ const snapshot = await readSnapshot(host.fs, state.cache, state.cwd, state.home, settings, now)++ state.snapshot = snapshot+ record(state.events, diffEvents(previous, snapshot, now))++ if (route !== null && route.agent !== state.ruflo.route?.agent) record(state.events, [{ atMs: now, kind: 'learning', text: `router picked ${route.agent} (${Math.round(route.confidence * 100)}%)` }])- state.snapshot = await readSnapshot(host.fs, state.cache, state.cwd, state.home, settings, Date.now())state.usage = usage- state.ruflo.snapshot = snapshot- state.ruflo.route = route ?? snapshot?.lastRoute ?? null- push(state.writes, state.snapshot.changed)+ state.ruflo.snapshot = ruflo+ state.ruflo.route = route ?? ruflo?.lastRoute ?? null+ push(state.writes, snapshot.changed)++ for (const agent of snapshot.agents.slice(0, 200)) {+ const log = state.statusLog.get(agent.id) ?? []++ if (log.at(-1)?.status !== agent.status) push(log, { atMs: now, status: agent.status }, 100)+ state.statusLog.set(agent.id, log)+ }++ const patterns = snapshot.neural?.patterns++ if (patterns !== undefined && state.history.patterns.at(-1)?.value !== patterns) push(state.history.patterns, { atMs: now, value: patterns })+ if (usage?.costUsd !== undefined && state.history.spend.at(-1)?.value !== usage.costUsd) push(state.history.spend, { atMs: now, value: usage.costUsd })+ if ((snapshot.outcomes?.total ?? 0) > state.history.outcomes) {+ if (state.history.outcomes > 0) state.curveGrewAtMs = now+ state.history.outcomes = snapshot.outcomes?.total ?? 0+ }if (state.options.bar === 'off') {const text = segmentOf(state)@@ -187,9 +213,7 @@ export function createController(state: State, host: Host): Controller {}function every(name: string, ms: number, fn: () => void): void {- if (!state.timers.has(name)) {- state.timers.set(name, host.every(ms, fn))- }+ if (!state.timers.has(name)) state.timers.set(name, host.every(ms, fn))}function cancel(name: string): void {@@ -200,9 +224,8 @@ export function createController(state: State, host: Host): Controller {/** One frame of every picture of the view in front, each blitted only at the size it was mounted. */function frame(): void {const started = Date.now()- const pictures = picturesOf(state, state.pane.columns, Date.now(), Date.now())- for (const [key, grid] of pictures) {+ for (const [key, grid] of picturesOf(state, state.pane.columns, Date.now(), Date.now())) {const mounted = state.mounted.get(key)if (mounted !== undefined && mounted.columns === grid.columns && mounted.rows === grid.rows) {@@ -215,9 +238,7 @@ export function createController(state: State, host: Host): Controller {/** Runs the frame loop while the pane is shown and holds the keys, at `fps`; stops it otherwise. */function animate(): void {- const shouldRun = state.options.fps > 0 && isVisible() && state.pane.isFocused && state.mounted.size > 0-- if (!shouldRun) {+ if (!(state.options.fps > 0 && isVisible() && state.pane.isFocused && state.mounted.size > 0)) {cancel('frames')return@@ -237,9 +258,7 @@ export function createController(state: State, host: Host): Controller {state.pane.isFocused = mine?.isFocused === true}- if (!state.pane.isOpen) {- cancel('watch')- }+ if (!state.pane.isOpen) cancel('watch')animate()}@@ -263,9 +282,7 @@ export function createController(state: State, host: Host): Controller {})}- function resume(): void {- every('watch', PANE_WATCH_MS, () => void watchPane())- }+ const resume = () => every('watch', PANE_WATCH_MS, () => void watchPane())function stop(): void {for (const timer of state.timers.values()) timer.cancel()@@ -273,15 +290,15 @@ export function createController(state: State, host: Host): Controller {}async function open(focus = true): Promise<{ isPlaced: boolean; reason: string }> {- const rows = VIEWS.find(view => view.id === state.view)?.rows ?? 24-try {- const result = await host.openPane({ id: PANE_ID, title: 'ruflo console', rows, ...(focus && { focus: true, closeOnEscape: true, holdToasts: true }) })+ const result = await host.openPane({ id: PANE_ID, title: 'ruflo', rows: rowsOf(state.view), ...(focus && { focus: true, closeOnEscape: true, holdToasts: true }) })const isPlaced = result === undefined || result.isPlaced !== falsestate.pane.isOpen = isPlacedstate.pane.isShown = isPlaced- every('watch', PANE_WATCH_MS, () => void watchPane())+ if (focus) state.pane.isClosedByPerson = false+ if (isPlaced) persist()+ resume()void refresh().then(() => probe(true))return { isPlaced, reason: result?.reason ?? '' }@@ -290,9 +307,29 @@ export function createController(state: State, host: Host): Controller {}}+ function autoOpen(): void {+ if (state.options.panel !== 'auto' || state.pane.isOpen || state.pane.isClosedByPerson || state.pane.autoTried) return++ state.pane.autoTried = true+ // From a timer, never a render hook; without `focus`, so the prompt keeps the keys. The engine seats an unasked pane+ // only where it docks (144 columns and up) and answers why not otherwise: the band then says "/ruflo to open".+ state.timers.set(+ 'auto-open',+ host.after(50, () => {+ state.timers.delete('auto-open')+ void open(false).then(result => {+ state.pane.autoReason = result.isPlaced ? '' : result.reason || 'not placed'+ host.invalidate()+ })+ }),+ )+ }+async function close(): Promise<void> {state.pane.isOpen = falsestate.pane.isShown = false+ state.pane.isClosedByPerson = true+ persist()cancel('frames')cancel('watch')await host.closePane(PANE_ID).catch(() => undefined)@@ -300,109 +337,48 @@ export function createController(state: State, host: Host): Controller {function setView(view: State['view']): void {state.isHelp = false+ state.palette.isOpen = falseif (view !== state.view) {+ if (view === 'agent' || state.view !== 'agent') state.back = state.view === 'agent' ? state.back : state.viewstate.view = view+ state.select.item = 0state.mounted.clear()persist()// A new view asks for its own height inline; the dock ignores it.- if (state.pane.isOpen) void host.openPane({ id: PANE_ID, title: 'ruflo console', rows: VIEWS.find(entry => entry.id === view)?.rows ?? 24 }).catch(() => undefined)+ if (state.pane.isOpen) void host.openPane({ id: PANE_ID, title: 'ruflo', rows: rowsOf(view) }).catch(() => undefined)void probe(true)}host.invalidate()}- function ask(spec: ActionSpec | null, why: string): void {- if (spec === null) {- state.outcome = { label: 'nothing to do', ok: false, verified: 'n/a', detail: why, atMs: Date.now() }- } else {- pendingSpec = spec- state.pending = { label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now() }- }-- host.invalidate()- }+ function drill(agentId: string): void {+ const agent = state.snapshot?.agents.find(entry => entry.id === agentId)- async function confirm(): Promise<void> {- const spec = pendingSpec- const isFresh = state.pending !== null && Date.now() - state.pending.askedAtMs < PENDING_TTL_MS+ state.drill = { agentId, logs: null, logsAtMs: 0 }+ setView('agent')- pendingSpec = null- state.pending = null+ const spec = agent === undefined ? null : agentLogs(agent)- if (spec === null || !isFresh || state.isActing) {- host.invalidate()-- return- }-- state.isActing = true- host.invalidate()-- try {- const result = await host.run([...CLI_PREFIXES[state.options.cli], ...spec.args], 60_000)- const answer = /"success"\s*:\s*(true|false)/.exec(result.stdout)?.[1]- const error = /"error"\s*:\s*"([^"]{0,160})"/.exec(result.stdout)?.[1]- const ok = result.exitCode === 0 && answer !== 'false'-- await freshRead()-- const verified = state.snapshot === null ? 'n/a' : spec.verify(state.snapshot) ? 'yes' : 'no'-- state.outcome = { label: spec.label, ok: ok && verified !== 'no', verified, detail: ok ? `ruflo answered ok; expected ${spec.expect}` : plain(error ?? result.stderr, 120) || `exit ${result.exitCode}`, atMs: Date.now() }- } catch (error) {- state.outcome = { label: spec.label, ok: false, verified: 'n/a', detail: plain(error instanceof Error ? error.message : String(error), 120) || 'refused', atMs: Date.now() }- } finally {- state.isActing = false- host.invalidate()+ if (spec !== null) {+ void host+ .run([...CLI_PREFIXES[state.options.cli], ...spec.args], 30_000)+ .then(result => {+ if (state.drill.agentId === agentId) state.drill = { agentId, logs: result.stdout.split('\n').map(line => plain(line, 160)).filter(Boolean).slice(-12), logsAtMs: Date.now() }+ })+ .catch(() => undefined)+ .finally(() => host.invalidate())}}- const step = (key: keyof State['select'], by: number) => () => {- state.select[key] += by- host.invalidate()- }-- const actions: Actions = {- view: setView,- refresh: () => void freshRead().then(() => probe(true)),- help: () => {- state.isHelp = !state.isHelp- host.invalidate()- },- close: () => void close(),- confirm: () => void confirm(),- cancel: () => {- pendingSpec = null- state.pending = null- host.invalidate()- },- claimPrev: step('claim', -1),- claimNext: step('claim', 1),- agentNext: step('agent', 1),- taskNext: step('task', 1),- claim: () => {- const { agent, task, claim } = selection(state)-- ask(task !== null && agent !== null ? claimTask(task, agent) : null, whyNot('claim', claim, agent, openTasks(state)[0] ?? task))- },- release: () => {- const { claim, agent, task } = selection(state)-- ask(claim !== null ? releaseClaim(claim) : null, whyNot('release', claim, agent, task))- },- handoff: () => {- const { claim, agent, task } = selection(state)-- ask(claim !== null && agent !== null ? handoffClaim(claim, agent) : null, whyNot('handoff', claim, agent, task))- },- steal: () => {- const { claim, agent, task } = selection(state)-- ask(claim !== null && agent !== null ? stealClaim(claim, agent) : null, whyNot('steal', claim, agent, task))- },- }+ const runner = createRunner(state, host, {+ freshRead,+ setView,+ drill,+ command: name => (name === 'refresh' ? actions.refresh() : name === 'help' ? actions.help() : actions.close()),+ })+ const actions: Actions = actionsOf(state, host, runner, { freshRead, probe, setView, drill, close })function markFrame(requestId: string, isWorking: boolean): void {markRequest = requestId@@ -416,5 +392,17 @@ export function createController(state: State, host: Host): Controller {}}- return { refresh, probe, start, resume, stop, open, close, setView, animate, noteToolCall: () => void (activityCount += 1), actions, markFrame }+ function noteToolCall(agentId: string | undefined, tool: string): void {+ activityCount += 1++ const who = agentId ?? 'main'+ const list = state.toolsByAgent.get(who) ?? []++ push(list, { atMs: Date.now(), tool: plain(tool, 40) }, 200)+ state.toolsByAgent.set(who, list)+ if (state.toolsByAgent.size > 50) state.toolsByAgent.delete(state.toolsByAgent.keys().next().value as string)+ record(state.events, [{ atMs: Date.now(), kind: 'tools', text: `${who === 'main' ? 'claude' : who}: ${plain(tool, 40)}` }])+ }++ return { refresh, probe, start, resume, stop, open, autoOpen, close, setView, drill, animate, noteToolCall, actions, runner, markFrame }}diff --git a/plugins/ruflo-console/hooks/data/alerts.ts b/plugins/ruflo-console/hooks/data/alerts.tsnew file mode 100644index 0000000000..bf64732b1d--- /dev/null+++ b/plugins/ruflo-console/hooks/data/alerts.ts@@ -0,0 +1,112 @@+/**+ * Health alerts and the approvals queue, derived from the state. Pure: each alert names what it saw and the exact+ * command (or palette entry) that addresses it; each approval names what a person decides and how. Nothing here+ * guesses: an agent is "stalled" only when ruflo marks it busy and the console has seen nothing of it for a while.+ */+import type { State } from '../state'+import type { ClaimRecord } from './parse'+import { RUFLO_MARKET } from './snapshot'++export type Alert = { id: string; level: 'bad' | 'warn' | 'info'; text: string; fix: string; paletteId?: string }++export type ApprovalAction = { label: string; paletteId: string }+export type Approval = { id: string; kind: 'proposal' | 'mod-trust' | 'policy-deny' | 'budget' | 'stealable'; text: string; detail: string; actions: ApprovalAction[] }++export const STALL_MS = 10 * 60_000+const DAY = 86_400_000++const ownerOf = (claim: ClaimRecord) => claim.claimant.agentType ?? claim.claimant.name ?? claim.claimant.id++/** The last time the console saw anything of each agent: an event about it, or its first sight. */+function lastSeen(state: State, loadedAtMs: number): Map<string, number> {+ const seen = new Map<string, number>()++ for (const agent of state.snapshot?.agents ?? []) seen.set(agent.id, Math.max(loadedAtMs, agent.createdAtMs ?? 0))+ for (const event of state.events) if (event.agentId !== undefined) seen.set(event.agentId, Math.max(seen.get(event.agentId) ?? 0, event.atMs))++ return seen+}++export function alertsOf(state: State, nowMs: number, loadedAtMs: number): Alert[] {+ const snap = state.snapshot+ const out: Alert[] = []++ if (snap === null) return out++ const seen = lastSeen(state, loadedAtMs)++ for (const agent of snap.agents) {+ const since = nowMs - (seen.get(agent.id) ?? nowMs)++ if (/busy/i.test(agent.status) && since >= STALL_MS) {+ out.push({ id: `stalled-${agent.id}`, level: 'warn', text: `${agent.name ?? agent.type} busy with no change for ${Math.round(since / 60_000)}m`, fix: `npx ruflo agent logs --id ${agent.id}`, paletteId: 'agent-logs' })+ }+ }++ for (const claim of snap.claims) {+ if (claim.expiresAtMs !== undefined && claim.expiresAtMs < nowMs) {+ out.push({ id: `expired-${claim.issueId}`, level: 'bad', text: `claim ${claim.issueId} expired (held by ${ownerOf(claim)})`, fix: 'release it (palette: release)', paletteId: 'claim-release' })+ } else if (claim.status === 'active' && claim.claimedAtMs !== undefined && nowMs - claim.claimedAtMs > DAY) {+ out.push({ id: `old-${claim.issueId}`, level: 'info', text: `claim ${claim.issueId} active for ${Math.floor((nowMs - claim.claimedAtMs) / DAY)}d`, fix: 'hand off or release it if the work stopped' })+ }+ }++ const budget = state.ruflo.snapshot?.budget++ if (budget !== undefined && budget.level !== 'OK') {+ out.push({ id: 'budget', level: budget.level === 'INFO' ? 'info' : budget.level === 'WARNING' ? 'warn' : 'bad', text: `budget ${budget.level}: $${(budget.usd ?? state.usage?.costUsd ?? 0).toFixed(2)} of $${budget.limit.toFixed(2)}`, fix: 'see Cost (9); raise costBudgetUsd in /config ruflo-mods' })+ }++ if (snap.plugins.missingFromClone.length > 0) {+ out.push({ id: 'marketplace', level: 'bad', text: `marketplace clone stale: no ${snap.plugins.missingFromClone.join(', ')}`, fix: `/plugin marketplace update ${RUFLO_MARKET}` })+ }++ if (snap.daemon !== null && !snap.daemon.running) out.push({ id: 'daemon', level: 'info', text: 'daemon stopped (per daemon-state.json)', fix: 'npx ruflo daemon start' })+ if (state.ruflo.snapshot === null && snap.isRufloProject) out.push({ id: 'mods', level: 'info', text: 'ruflo-mods not seated: no in-process routing or budget ladder', fix: 'npx ruflo mods install' })++ for (const mod of state.mods.filter(entry => !entry.isLoaded).slice(-3)) {+ out.push({ id: `refused-${mod.provenance}`, level: 'warn', text: `mod ${mod.name} refused`, fix: `allow ${mod.provenance} in ruflo-mods modTrustAllow, if you trust it` })+ }++ return out+}++/** Decisions waiting for a person, each with the palette entries that act on it in place. */+export function approvalsOf(state: State): Approval[] {+ const snap = state.snapshot+ const out: Approval[] = []++ for (const proposal of snap?.hive?.pending ?? []) {+ out.push({+ id: `proposal-${proposal.id}`,+ kind: 'proposal',+ text: `hive-mind proposal: ${proposal.type} (${proposal.strategy})`,+ detail: `${proposal.status} · for ${proposal.votesFor} · against ${proposal.votesAgainst} · ${proposal.id}`,+ actions: [+ { label: 'vote yes', paletteId: `vote-yes-${proposal.id}` },+ { label: 'vote no', paletteId: `vote-no-${proposal.id}` },+ ],+ })+ }++ for (const claim of (snap?.claims ?? []).filter(entry => entry.isStealable)) {+ out.push({ id: `steal-${claim.issueId}`, kind: 'stealable', text: `claim ${claim.issueId} offered for stealing`, detail: `held by ${ownerOf(claim)}; pick an agent (a) and steal`, actions: [{ label: 'steal for picked agent', paletteId: 'claim-steal' }] })+ }++ for (const mod of state.mods.filter(entry => !entry.isLoaded)) {+ out.push({ id: `mod-${mod.provenance}`, kind: 'mod-trust', text: `mod ${mod.name} refused by a trust gate`, detail: `${mod.reason ?? ''} — to allow it, add ${mod.provenance} to modTrustAllow (/config ruflo-mods)`, actions: [] })+ }++ for (const deny of state.denied.slice(-5)) {+ out.push({ id: `deny-${deny.atMs}`, kind: 'policy-deny', text: `${deny.tool} denied by a permission verdict`, detail: `${deny.reason} — a deny is never loosened from here; change the policy if it is wrong`, actions: [] })+ }++ const budget = state.ruflo.snapshot?.budget++ if (budget !== undefined && (budget.level === 'WARNING' || budget.level === 'CRITICAL' || budget.level === 'HARD_STOP')) {+ out.push({ id: 'budget', kind: 'budget', text: `budget ${budget.level}`, detail: `$${(budget.usd ?? 0).toFixed(2)} of $${budget.limit.toFixed(2)}`, actions: [{ label: 'open Cost', paletteId: 'view-cost' }] })+ }++ return out+}+diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.tsindex 005603299f..bf7ba057d8 100644--- a/plugins/ruflo-console/hooks/data/cli.ts+++ b/plugins/ruflo-console/hooks/data/cli.ts@@ -6,7 +6,9 @@*/import { msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'-export type ViewId = 'overview' | 'swarm' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory'+import type { ViewId } from '../state'++export type { ViewId }export type Probe<T> = {id: string@@ -57,7 +59,7 @@ export type MemoryStats = { backend: string; total?: number; vectors?: number; sexport const memoryProbe: Probe<MemoryStats> = {id: 'memory',args: ['memory', 'stats', '--format', 'json'],- views: ['overview', 'memory'],+ views: ['overview', 'memory', 'cost'],everyMs: 30_000,timeoutMs: 30_000,parse: stdout => {@@ -184,6 +186,42 @@ export const flywheelProbe: Probe<Flywheel> = {},}+export type AuditTrend = { total: number; points: { atMs: number; worst?: string; findings?: number }[] }++const SEVERITY: Record<string, number> = { clean: 0, low: 1, medium: 2, high: 3, critical: 4 }++/** Stored MetaHarness audits, oldest first: the trend line's points. Reads memory; runs nothing. */+export const auditProbe: Probe<AuditTrend> = {+ id: 'audits',+ args: ['metaharness', 'audit-list', '--format', 'json'],+ views: ['metaharness'],+ everyMs: 120_000,+ timeoutMs: 60_000,+ parse: stdout => {+ const value = objectOf(stdout)++ if (value === null || !Array.isArray(value.records)) {+ return null+ }++ const points = value.records.slice(0, 50).flatMap(entry => {+ const record = recordOf(entry)+ const atMs = msOf(record?.timestamp ?? record?.generatedAt ?? record?.createdAt ?? recordOf(record?.value)?.generatedAt)+ const worst = stringOf(record?.worst ?? recordOf(record?.value)?.worst, 12)+ const findings = numberOf(record?.findings ?? recordOf(record?.value)?.findingCount)++ return atMs === undefined ? [] : [{ atMs, ...(worst !== undefined && { worst }), ...(findings !== undefined && { findings }) }]+ })++ points.sort((a, b) => a.atMs - b.atMs)++ return { total: numberOf(value.totalInNamespace) ?? points.length, points }+ },+}++/** A severity word as a 0-4 level, for the trend line; unknown words are null. */+export const severityOf = (word: string | undefined): number | null => (word === undefined ? null : (SEVERITY[word.toLowerCase()] ?? null))+export type Intelligence = { trajectories?: number; patterns?: number; successRate?: number; moeDecisions?: number; ewcConsolidations?: number; routerDecisions?: number; routerConfidence?: number; neuralRouter?: string }export const intelligenceProbe: Probe<Intelligence> = {@@ -317,7 +355,7 @@ export const rosterProbe: Probe<Roster> = {},}-export const PROBES = [versionProbe, memoryProbe, namespacesProbe, scoreProbe, flywheelProbe, intelligenceProbe, peersProbe, channelsProbe, rosterProbe] as const+export const PROBES = [versionProbe, memoryProbe, namespacesProbe, scoreProbe, flywheelProbe, auditProbe, intelligenceProbe, peersProbe, channelsProbe, rosterProbe] as constexport type ProbeId = (typeof PROBES)[number]['id']diff --git a/plugins/ruflo-console/hooks/data/events.ts b/plugins/ruflo-console/hooks/data/events.tsnew file mode 100644index 0000000000..40d9f42394--- /dev/null+++ b/plugins/ruflo-console/hooks/data/events.ts@@ -0,0 +1,117 @@+/**+ * The event stream: what changed between two reads of ruflo's state, plus what the console observed itself (tool calls,+ * routes, mod admissions, permission denies). Every event is something that happened on disk or in this session, with+ * the time the console saw it: the stream never synthesises activity.+ */+import type { Snapshot } from './snapshot'++export type EventKind = 'swarm' | 'claims' | 'federation' | 'learning' | 'tools' | 'mods'++export type ConsoleEvent = {+ atMs: number+ kind: EventKind+ text: string+ /** The ruflo agent the event concerns, when one does: the topology pulses along that agent's edge. */+ agentId?: string+}++export const EVENT_KINDS: readonly EventKind[] = ['swarm', 'claims', 'federation', 'learning', 'tools', 'mods']+export const MAX_EVENTS = 300++const ev = (atMs: number, kind: EventKind, text: string, agentId?: string): ConsoleEvent => ({ atMs, kind, text, ...(agentId !== undefined && { agentId }) })++/** What changed from `prev` to `next`. The first read (no `prev`) is a baseline and yields nothing. */+export function diffEvents(prev: Snapshot | null, next: Snapshot, atMs: number): ConsoleEvent[] {+ if (prev === null) {+ return []+ }++ const out: ConsoleEvent[] = []+ const before = new Map(prev.agents.map(agent => [agent.id, agent]))+ const after = new Map(next.agents.map(agent => [agent.id, agent]))++ if (prev.swarm?.id !== next.swarm?.id && next.swarm !== null) out.push(ev(atMs, 'swarm', `swarm ${next.swarm.id} (${next.swarm.topology}) appeared`))+ if (prev.swarm !== null && next.swarm !== null && prev.swarm.id === next.swarm.id && prev.swarm.status !== next.swarm.status) {+ out.push(ev(atMs, 'swarm', `swarm ${next.swarm.status} (was ${prev.swarm.status})`))+ }++ for (const [id, agent] of after) {+ const old = before.get(id)++ if (old === undefined) out.push(ev(atMs, 'swarm', `agent ${agent.name ?? agent.type} spawned (${agent.type})`, id))+ else if (old.status !== agent.status) out.push(ev(atMs, 'swarm', `agent ${agent.name ?? agent.type}: ${old.status} → ${agent.status}`, id))+ }++ for (const [id, agent] of before) {+ if (!after.has(id)) out.push(ev(atMs, 'swarm', `agent ${agent.name ?? agent.type} left the store`, id))+ }++ const claimsBefore = new Map(prev.claims.map(claim => [claim.issueId, claim]))+ const claimsAfter = new Map(next.claims.map(claim => [claim.issueId, claim]))++ for (const [id, claim] of claimsAfter) {+ const old = claimsBefore.get(id)+ const owner = claim.claimant.kind === 'agent' ? claim.claimant.id : undefined++ if (old === undefined) out.push(ev(atMs, 'claims', `${id} claimed by ${claim.claimant.agentType ?? claim.claimant.name ?? claim.claimant.id}`, owner))+ else if (old.claimant.id !== claim.claimant.id) out.push(ev(atMs, 'claims', `${id} now held by ${claim.claimant.agentType ?? claim.claimant.id}`, owner))+ else if (old.status !== claim.status) out.push(ev(atMs, 'claims', `${id}: ${old.status} → ${claim.status}${claim.handoffTo !== undefined ? ` (to ${claim.handoffTo})` : ''}`, owner))+ else if ((old.progress ?? 0) !== (claim.progress ?? 0)) out.push(ev(atMs, 'claims', `${id} progress ${claim.progress ?? 0}%`, owner))+ }++ for (const [id, claim] of claimsBefore) {+ if (!claimsAfter.has(id)) out.push(ev(atMs, 'claims', `${id} released`, claim.claimant.kind === 'agent' ? claim.claimant.id : undefined))+ }++ const tasksBefore = new Set(prev.tasks.map(task => task.id))++ for (const task of next.tasks) {+ if (!tasksBefore.has(task.id)) out.push(ev(atMs, 'claims', `task ${task.id} created: ${task.description.slice(0, 60)}`))+ }++ const proposals = new Set(prev.hive?.pending.map(entry => entry.id) ?? [])+ const decided = new Set(prev.hive?.history.map(entry => entry.id) ?? [])++ for (const proposal of next.hive?.pending ?? []) {+ if (!proposals.has(proposal.id)) out.push(ev(atMs, 'swarm', `proposal ${proposal.type} (${proposal.strategy}) opened`, next.hive?.queen))+ }++ for (const decision of next.hive?.history ?? []) {+ if (!decided.has(decision.id)) out.push(ev(atMs, 'swarm', `proposal ${decision.type} decided: ${decision.result} (${decision.votesFor}/${decision.votesAgainst})`, next.hive?.queen))+ }++ const patterns = (next.neural?.patterns ?? 0) - (prev.neural?.patterns ?? 0)++ if (prev.neural !== null && next.neural !== null && patterns > 0) out.push(ev(atMs, 'learning', `+${patterns} pattern${patterns === 1 ? '' : 's'} learned`))++ const outcomes = (next.outcomes?.total ?? 0) - (prev.outcomes?.total ?? 0)++ if (prev.outcomes !== null && outcomes > 0) out.push(ev(atMs, 'learning', `+${outcomes} routed outcome${outcomes === 1 ? '' : 's'} judged`))+ if ((prev.federationNodes?.length ?? 0) !== (next.federationNodes?.length ?? 0)) out.push(ev(atMs, 'federation', `federation keys: ${next.federationNodes?.length ?? 0} node ids on disk`))+ if (prev.hasNostrKey !== next.hasNostrKey && next.hasNostrKey === true) out.push(ev(atMs, 'federation', 'a nostr identity appeared (~/.ruflo/nostr.key)'))++ return out+}++/** Appends events, newest last, keeping at most MAX_EVENTS. */+export function record(events: ConsoleEvent[], fresh: readonly ConsoleEvent[]): void {+ if (fresh.length === 0) return++ events.push(...fresh)++ if (events.length > MAX_EVENTS) events.splice(0, events.length - MAX_EVENTS)+}++/** The agents an event touched in the last `windowMs`, newest event per agent: what the topology pulses for. */+export function recentByAgent(events: readonly ConsoleEvent[], nowMs: number, windowMs: number): Map<string, number> {+ const out = new Map<string, number>()++ for (let i = events.length - 1; i >= 0; i--) {+ const event = events[i] as ConsoleEvent++ if (nowMs - event.atMs > windowMs) break+ if (event.agentId !== undefined && !out.has(event.agentId)) out.set(event.agentId, event.atMs)+ }++ return out+}diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.tsnew file mode 100644index 0000000000..798a4e3e86--- /dev/null+++ b/plugins/ruflo-console/hooks/dispatch.ts@@ -0,0 +1,113 @@+/**+ * Carries out a `/ruflo` intent (./commands) and answers the command's row. The pane's keys all have an intent here,+ * so everything works without focus. `mods` and `swarm <sub>` are passed on to the plugins that own them; when neither+ * answers, the row says which plugin to load rather than pretending.+ */+import { HELP, parseRuflo, type Intent } from './commands'+import type { Controller } from './controller'+import { median, p95 } from './controller'+import { plain } from './data/parse'+import { VIEWS, type State } from './state'+import { barText } from './views/bar'++export type Delegate = () => Promise<{ text?: string } | undefined>++/** The one-line answer of `/ruflo status`, with the measured render, refresh and frame costs. */+export function statusLine(state: State): string {+ const stat = (name: string, values: readonly number[]) => (values.length === 0 ? `${name} n/a` : `${name} median ${median(values)}ms p95 ${p95(values)}ms (n=${values.length})`)++ return [barText(state), stat('render', state.stats.renders), stat('refresh', state.stats.refreshes), stat('frame', state.stats.frames)].join(' · ')+}++const OWNER_HINT = {+ 'ruflo-mods': 'ruflo-mods is not loaded in this session, so nothing answered `/ruflo mods`. Install it with `npx ruflo mods install` (or enable ruflo-mods@ruflo); its old `/ruflo-mods` command is the same report.',+ 'ruflo-swarm': 'ruflo-swarm is not loaded in this session, so nothing answered `/ruflo swarm …`. Enable ruflo-swarm@ruflo; the Swarm view (/ruflo swarm) is the console\'s own.',+} as const++async function open(control: Controller, state: State, label: string): Promise<{ text: string }> {+ const opened = await control.open()++ return { text: opened.isPlaced ? `ruflo console: ${label}` : `The ruflo console could not be shown: ${opened.reason}` }+}++export async function dispatch(control: Controller, state: State, args: string, delegate: Delegate): Promise<{ text: string }> {+ const intent: Intent = parseRuflo(args)++ switch (intent.kind) {+ case 'open':+ if (intent.view !== null) control.setView(intent.view)++ return open(control, state, VIEWS.find(view => view.id === state.view)?.label ?? 'Agent')+ case 'help':+ return { text: HELP }+ case 'close':+ await control.close()++ return { text: 'ruflo console closed (/ruflo opens it again)' }+ case 'status':+ await control.refresh()++ return { text: statusLine(state) }+ case 'delegate': {+ try {+ const answer = await delegate()++ if (typeof answer?.text === 'string' && answer.text.trim() !== '') return { text: answer.text }+ } catch {+ // Nothing beneath answers this command: fall through to the hint.+ }++ return { text: OWNER_HINT[intent.owner] }+ }+ case 'palette':+ state.palette = { isOpen: true, query: plain(intent.query, 200), index: 0, context: 'all' }++ return open(control, state, 'palette')+ case 'run': {+ const isRun = control.actions.run(intent.paletteId, intent.text)++ if (!isRun) return { text: `No palette entry "${plain(intent.paletteId, 40)}" right now. /ruflo palette lists them; ids look like spawn-coder, claim-release, worker-audit, route.` }++ await control.open()++ return { text: state.pending !== null ? `Asked: ${state.pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.` : (state.outcome?.label ?? 'done') }+ }+ case 'confirm':+ if (state.pending === null) return { text: 'Nothing is waiting for a confirm.' }++ if (!intent.isYes) {+ control.runner.cancel()++ return { text: 'Cancelled.' }+ }++ await control.runner.confirm()++ return { text: state.outcome === null ? 'Ran.' : `${state.outcome.ok ? '✓' : '✗'} ${state.outcome.label}: ${state.outcome.detail}${state.outcome.verified === 'yes' ? ' (on disk)' : state.outcome.verified === 'no' ? ' (not on disk yet)' : ''}` }+ case 'agent': {+ const who = intent.who.toLowerCase()+ const agent = state.snapshot?.agents.find(entry => entry.id.toLowerCase() === who || entry.name?.toLowerCase() === who) ?? state.snapshot?.agents.find(entry => entry.id.toLowerCase().endsWith(who))++ if (agent === undefined) return { text: `No agent "${plain(intent.who, 40)}" in .claude-flow/agents/store.json.` }++ control.drill(agent.id)++ return open(control, state, `agent ${agent.name ?? agent.type}`)+ }+ case 'back':+ control.actions.back()++ return open(control, state, VIEWS.find(view => view.id === state.view)?.label ?? 'back')+ case 'select':+ control.actions.select(intent.by)++ return { text: `selection moved (${intent.by > 0 ? 'next' : 'prev'}) on ${state.view}` }+ case 'filter':+ state.eventFilter = intent.filter+ control.setView('events')++ return open(control, state, `events · ${intent.filter}`)+ case 'unknown':+ return { text: `Unknown: "${plain(intent.word, 30)}". /ruflo help lists the views (${VIEWS.map(view => view.id).join(', ')}) and commands.` }+ }+}diff --git a/plugins/ruflo-console/hooks/gfx/charts.ts b/plugins/ruflo-console/hooks/gfx/charts.tsnew file mode 100644index 0000000000..1b05c308c9--- /dev/null+++ b/plugins/ruflo-console/hooks/gfx/charts.ts@@ -0,0 +1,172 @@+/**+ * Charts for the learning, MetaHarness and cost views: the learning pipeline, a score radar, a trend line, a budget+ * gauge and a sparkline over timed samples. Pure functions of data, size and the real clock; each returns a grid of+ * exactly the size asked for.+ */+import { Braille, COLOR, Grid, mix, ramp, sparkline } from './raster'++export type Stage = { name: string; count: number | null; source: string }++/**+ * RETRIEVE → JUDGE → DISTILL → CONSOLIDATE as four boxes with their counts. When a count grew in the last 1.5 s a dot+ * runs along the arrow into that stage: the motion is new learning arriving, nothing else.+ */+export function pipelinePicture(stages: readonly Stage[], columns: number, t: number, grewAtMs: readonly (number | null)[]): Grid {+ const rows = 4+ const grid = new Grid(columns, rows)+ const n = Math.max(1, stages.length)+ const box = Math.max(8, Math.floor((columns - (n - 1) * 3) / n))++ stages.forEach((stage, i) => {+ const x0 = i * (box + 3)+ const count = stage.count === null ? 'n/a' : stage.count >= 10_000 ? `${(stage.count / 1000).toFixed(1)}k` : String(stage.count)+ const grew = grewAtMs[i] ?? null+ const lit = grew !== null && t - grew >= 0 && t - grew < 1_500++ grid.text(x0, 0, `╭${'─'.repeat(box - 2)}╮`, lit ? COLOR.warn : COLOR.line)+ grid.text(x0, 1, `│${stage.name.padEnd(box - 2).slice(0, box - 2)}│`, COLOR.accent)+ grid.text(x0, 2, `│${count.padStart(box - 2).slice(0, box - 2)}│`, stage.count === null ? COLOR.dim : ramp(0.7))+ grid.text(x0, 3, `╰${'─'.repeat(box - 2)}╯`, lit ? COLOR.warn : COLOR.line)++ if (i > 0) {+ const ax = x0 - 3++ grid.text(ax, 1, '──▶', COLOR.line)++ if (lit) grid.set(ax + Math.min(2, Math.floor(((t - (grew ?? 0)) / 500) % 3)), 1, '●', COLOR.warn)+ }+ })++ return grid+}++/**+ * A radar of 0-100 scores on equal axes (braille): rings at 25/50/75/100 and the polygon of the values, which grows to+ * full size over 700 ms after `sinceMs` (decoration). Axis labels sit at each spoke's end.+ */+export function radarPicture(dims: readonly { name: string; value: number }[], columns: number, rows: number, t: number, sinceMs: number): Grid {+ const grid = new Grid(columns, rows)+ const canvas = new Braille(columns, rows)+ const n = dims.length+ const cx = canvas.width / 2+ const cy = canvas.height / 2+ const r = Math.max(3, Math.min(canvas.height / 2 - 3, canvas.width / 4 - 6))+ const grow = 1 - (1 - Math.max(0, Math.min(1, (t - sinceMs) / 700))) ** 3+ const at = (i: number, value: number) => {+ const angle = -Math.PI / 2 + (i / Math.max(1, n)) * Math.PI * 2++ return { x: cx + Math.cos(angle) * r * 2 * value, y: cy + Math.sin(angle) * r * value }+ }++ if (n < 3) return grid++ for (const ring of [0.25, 0.5, 0.75, 1]) {+ for (let i = 0; i < n; i++) {+ const p = at(i, ring)+ const q = at((i + 1) % n, ring)++ canvas.line(p.x, p.y, q.x, q.y, ring === 1 ? COLOR.line : mix(COLOR.line, 0x000000, 0.4))+ }+ }++ for (let i = 0; i < n; i++) {+ const p = at(i, 1)++ canvas.line(cx, cy, p.x, p.y, mix(COLOR.line, 0x000000, 0.4))+ }++ for (let i = 0; i < n; i++) {+ const a = dims[i] as { value: number }+ const b = dims[(i + 1) % n] as { value: number }+ const p = at(i, (a.value / 100) * grow)+ const q = at((i + 1) % n, (b.value / 100) * grow)++ canvas.line(p.x, p.y, q.x, q.y, ramp(((a.value + b.value) / 200) * 0.9 + 0.1))+ }++ canvas.blitInto(grid, 0, 0)++ dims.forEach((dim, i) => {+ const p = at(i, 1.18)+ const label = `${dim.name.slice(0, 10)} ${Math.round(dim.value)}`+ const x = Math.round(p.x / 2 - (Math.cos(-Math.PI / 2 + (i / n) * Math.PI * 2) < -0.2 ? label.length : Math.cos(-Math.PI / 2 + (i / n) * Math.PI * 2) > 0.2 ? 0 : label.length / 2))++ grid.text(Math.max(0, Math.min(columns - label.length, x)), Math.max(0, Math.min(rows - 1, Math.round(p.y / 4))), label, ramp(dim.value / 100))+ })++ return grid+}++/** A braille line over points 0..`max`, oldest left, with the axis words given; one point or none is said in words. */+export function trendPicture(values: readonly number[], columns: number, rows: number, max: number, words: { top: string; bottom: string; empty: string }): Grid {+ const grid = new Grid(columns, rows)+ const label = Math.max(words.top.length, words.bottom.length) + 1+ const canvas = new Braille(Math.max(1, columns - label), rows)++ grid.text(0, 0, words.top, COLOR.dim)+ grid.text(0, rows - 1, words.bottom, COLOR.dim)++ if (values.length < 2) {+ grid.text(label + 1, Math.floor(rows / 2), words.empty, COLOR.dim)++ return grid+ }++ const xOf = (i: number) => (i / (values.length - 1)) * (canvas.width - 1)+ const yOf = (v: number) => (1 - Math.max(0, Math.min(1, v / max))) * (canvas.height - 1)++ for (let i = 1; i < values.length; i++) canvas.line(xOf(i - 1), yOf(values[i - 1] as number), xOf(i), yOf(values[i] as number), ramp(1 - (values[i] as number) / max))++ canvas.blitInto(grid, label, 0)++ return grid+}++/**+ * Spend against a budget as a half-ring gauge: the arc is coloured by the ladder (green to 50%, amber to 90%, red past),+ * the needle at spend / limit. With no limit the arc is grey and the needle absent: there is nothing to measure against.+ */+export function gaugePicture(spend: number | null, limit: number | null, columns: number, rows: number): Grid {+ const grid = new Grid(columns, rows)+ const canvas = new Braille(columns, rows)+ const cx = canvas.width / 2+ const cy = canvas.height - 2+ const r = Math.max(4, Math.min(canvas.height - 4, canvas.width / 4))+ const point = (fraction: number, radius: number) => ({ x: cx - Math.cos(fraction * Math.PI) * radius * 2, y: cy - Math.sin(fraction * Math.PI) * radius })++ for (let i = 0; i <= 120; i++) {+ const f = i / 120+ const p = point(f, r)+ const color = limit === null ? COLOR.line : f < 0.5 ? COLOR.ok : f < 0.9 ? COLOR.warn : COLOR.bad++ canvas.dot(p.x, p.y, color)+ }++ if (spend !== null && limit !== null && limit > 0) {+ const f = Math.max(0, Math.min(1, spend / limit))+ const tip = point(f, r * 0.9)++ canvas.line(cx, cy, tip.x, tip.y, 0xffffff)+ }++ canvas.blitInto(grid, 0, 0)++ const words = limit === null ? 'no budget set' : spend === null ? `limit $${limit.toFixed(2)} · spend n/a` : `$${spend.toFixed(2)} of $${limit.toFixed(2)} (${Math.round((spend / limit) * 100)}%)`++ grid.text(Math.max(0, Math.floor((columns - words.length) / 2)), rows - 1, words, limit === null ? COLOR.dim : 0xffffff)++ return grid+}++/** A labelled sparkline over timed samples (oldest left), scaled between their own min and max. */+export function samplesPicture(label: string, samples: readonly { value: number }[], columns: number): Grid {+ const grid = new Grid(columns, 1)+ const width = Math.max(4, columns - label.length - 1)+ const values = samples.map(sample => sample.value)+ const lo = Math.min(...values, Number.POSITIVE_INFINITY)++ grid.text(0, 0, label, COLOR.dim)+ sparkline(grid, label.length + 1, 0, width, values.map(value => value - (Number.isFinite(lo) ? lo : 0) + (values.length > 0 ? 1 : 0)), v => ramp(0.3 + v * 0.6))++ return grid+}diff --git a/plugins/ruflo-console/hooks/gfx/flow.ts b/plugins/ruflo-console/hooks/gfx/flow.tsnew file mode 100644index 0000000000..adb5604ba4--- /dev/null+++ b/plugins/ruflo-console/hooks/gfx/flow.ts@@ -0,0 +1,104 @@+/**+ * The claims flow: five lanes left to right (open tasks → claimed → working → done, and stealable), one card per claim+ * with a ring and a handoff arrow where one is pending. Pure: `flowModelOf` reads the snapshot, `flowPicture` draws it+ * for an instant on the real clock. The ring is data: time left to `expiresAt` where ruflo set one, else the claim's+ * age on a 24 h scale; an expired claim's ring blinks.+ */+import type { ClaimRecord, TaskRecord } from '../data/parse'+import { COLOR, Grid, mix } from './raster'++export const LANES = ['open', 'claimed', 'working', 'done', 'stealable'] as const+export type LaneId = (typeof LANES)[number]++export const LANE_TITLES: Record<LaneId, string> = { open: 'open tasks', claimed: 'claimed', working: 'working', done: 'done', stealable: 'stealable' }++export type FlowCard = { id: string; owner: string; lane: LaneId; claimedAtMs?: number; expiresAtMs?: number; handoffTo?: string; progress?: number }++const DAY = 86_400_000+const RINGS = ['○', '◔', '◑', '◕', '●'] as const++/** The lane a claim stands in: ruflo's statuses folded into the five lanes. */+export function laneOf(claim: ClaimRecord): LaneId {+ if (claim.isStealable) return 'stealable'+ if (claim.status === 'completed') return 'done'+ if (claim.status === 'active' && (claim.progress ?? 0) === 0) return 'claimed'++ return 'working'+}++export function flowModelOf(claims: readonly ClaimRecord[], openTasks: readonly TaskRecord[]): FlowCard[] {+ return [+ ...openTasks.slice(0, 40).map(task => ({ id: task.id, owner: task.description || task.type, lane: 'open' as const })),+ ...claims.slice(0, 200).map(claim => ({+ id: claim.issueId,+ owner: claim.claimant.agentType ?? claim.claimant.name ?? claim.claimant.id,+ lane: laneOf(claim),+ ...(claim.claimedAtMs !== undefined && { claimedAtMs: claim.claimedAtMs }),+ ...(claim.expiresAtMs !== undefined && { expiresAtMs: claim.expiresAtMs }),+ ...(claim.handoffTo !== undefined && { handoffTo: claim.handoffTo }),+ ...(claim.progress !== undefined && { progress: claim.progress }),+ })),+ ]+}++/** The ring of a card at `nowMs`: its glyph, colour and words. */+export function ringOf(card: FlowCard, nowMs: number): { glyph: string; color: number; words: string; isExpired: boolean } {+ if (card.expiresAtMs !== undefined && card.claimedAtMs !== undefined && card.expiresAtMs > card.claimedAtMs) {+ const left = card.expiresAtMs - nowMs+ const fraction = Math.max(0, Math.min(1, left / (card.expiresAtMs - card.claimedAtMs)))++ return { glyph: RINGS[Math.round(fraction * 4)] as string, color: fraction < 0.2 ? COLOR.bad : fraction < 0.5 ? COLOR.warn : COLOR.ok, words: left > 0 ? `ttl ${Math.ceil(left / 1000)}s` : 'expired', isExpired: left <= 0 }+ }++ if (card.claimedAtMs === undefined) return { glyph: '·', color: COLOR.dim, words: '', isExpired: false }++ const age = Math.max(0, nowMs - card.claimedAtMs)++ return { glyph: RINGS[Math.min(4, Math.floor((age / DAY) * 4))] as string, color: mix(COLOR.info, COLOR.warn, Math.min(1, age / DAY)), words: '', isExpired: false }+}++/** Rows the flow needs for these cards: a header and two rows per card in the fullest lane, at most `maxCards`. */+export function flowRows(cards: readonly FlowCard[], maxCards = 6): number {+ const fullest = Math.max(1, ...LANES.map(lane => cards.filter(card => card.lane === lane).length))++ return 1 + 2 * Math.min(maxCards, fullest) + 1+}++export function flowPicture(cards: readonly FlowCard[], columns: number, rows: number, nowMs: number): Grid {+ const grid = new Grid(columns, rows)+ const width = Math.max(6, Math.floor(columns / LANES.length))+ const maxCards = Math.max(0, Math.floor((rows - 2) / 2))+ const blink = Math.floor(nowMs / 500) % 2 === 0++ LANES.forEach((lane, li) => {+ const x0 = li * width+ const inLane = cards.filter(card => card.lane === lane)+ const title = `${LANE_TITLES[lane]} ${inLane.length}`++ grid.text(x0, 0, title.slice(0, width - 2), lane === 'stealable' ? COLOR.warn : lane === 'done' ? COLOR.ok : COLOR.accent)+ if (li < LANES.length - 1) grid.text(x0 + width - 2, 0, '▸', COLOR.line)+ for (let y = 1; y < rows && li > 0; y++) grid.set(x0 - 1, y, '│', COLOR.line)++ inLane.slice(0, maxCards).forEach((card, ci) => {+ const y = 1 + ci * 2+ const ring = ringOf(card, nowMs)+ const inner = width - 3++ grid.set(x0, y, ring.isExpired && blink ? ' ' : ring.glyph, ring.color)+ grid.text(x0 + 2, y, card.id.slice(0, inner), lane === 'stealable' ? COLOR.warn : 0xd0d0d0)++ if (card.handoffTo !== undefined) {+ const target = `→ ${card.handoffTo}`++ grid.text(x0 + 1, y + 1, '╰─▶', COLOR.warn)+ grid.text(x0 + 4, y + 1, target.slice(2, 2 + inner - 3), COLOR.warn)+ } else {+ grid.text(x0 + 2, y + 1, `${card.owner}${card.progress !== undefined && card.progress > 0 ? ` ${card.progress}%` : ''}`.slice(0, inner), COLOR.dim)+ }+ })++ if (inLane.length > maxCards) grid.text(x0, rows - 1, `+${inLane.length - maxCards} more`.slice(0, width - 2), COLOR.dim)+ })++ return grid+}diff --git a/plugins/ruflo-console/hooks/gfx/maps.ts b/plugins/ruflo-console/hooks/gfx/maps.tsnew file mode 100644index 0000000000..f289baf60b--- /dev/null+++ b/plugins/ruflo-console/hooks/gfx/maps.ts@@ -0,0 +1,125 @@+/**+ * The federation map, the plugin health matrix and the agent timeline. Pure functions of data, size and the real clock.+ */+import { Braille, COLOR, Grid, mix } from './raster'++export type FedNode = { label: string; trust: 'pinned' | 'channel' | 'key' | 'roster'; /** When traffic was last seen with it. */ trafficAtMs?: number }++const TRUST_COLOR: Record<FedNode['trust'], number> = { pinned: COLOR.ok, channel: COLOR.info, key: COLOR.accent, roster: COLOR.dim }+/** Dots drawn per step along an edge: solid for a pinned peer, dashed for a channel, sparse for an untrusted member. */+const TRUST_DASH: Record<FedNode['trust'], number> = { pinned: 1, key: 1, channel: 2, roster: 4 }++/**+ * This node in the middle, the others around it, each edge drawn by trust: solid (pinned peer, own key), dashed+ * (channel), sparse (roster member, unvetted). A dot runs along an edge for 2 s after traffic with that node (data).+ */+export function federationPicture(center: string, nodes: readonly FedNode[], columns: number, rows: number, t: number): Grid {+ const grid = new Grid(columns, rows)+ const canvas = new Braille(columns, rows)+ const cx = canvas.width / 2+ const cy = canvas.height / 2+ const r = Math.max(4, Math.min(canvas.height / 2 - 3, canvas.width / 4 - 4))+ const shown = nodes.slice(0, 16)+ const points = shown.map((_, i) => {+ const angle = -Math.PI / 2 + (i / Math.max(1, shown.length)) * Math.PI * 2++ return { x: cx + Math.cos(angle) * r * 2, y: cy + Math.sin(angle) * r }+ })++ shown.forEach((node, i) => {+ const p = points[i] as { x: number; y: number }+ const steps = Math.ceil(Math.max(Math.abs(p.x - cx), Math.abs(p.y - cy)))+ const dash = TRUST_DASH[node.trust]++ for (let s = 0; s <= steps; s += dash) canvas.dot(cx + ((p.x - cx) * s) / steps, cy + ((p.y - cy) * s) / steps, mix(TRUST_COLOR[node.trust], 0x000000, 0.35))++ const k = node.trafficAtMs === undefined ? -1 : ((t - node.trafficAtMs) % 1_000) / 1_000++ if (node.trafficAtMs !== undefined && t - node.trafficAtMs >= 0 && t - node.trafficAtMs < 2_000 && k >= 0) {+ canvas.dot(cx + (p.x - cx) * k, cy + (p.y - cy) * k, 0xffffff)+ canvas.dot(cx + (p.x - cx) * k + 1, cy + (p.y - cy) * k, 0xffffff)+ }+ })++ canvas.blitInto(grid, 0, 0)++ const ccx = Math.floor(cx / 2)+ const ccy = Math.floor(cy / 4)++ grid.set(ccx, ccy, '◉', COLOR.accent)+ grid.text(Math.max(0, ccx - Math.floor(center.length / 2)), Math.min(rows - 1, ccy + 1), center, COLOR.accent)++ shown.forEach((node, i) => {+ const p = points[i] as { x: number; y: number }+ const x = Math.floor(p.x / 2)+ const y = Math.floor(p.y / 4)+ const label = node.label.slice(0, 14)++ grid.set(x, y, node.trust === 'roster' ? '○' : '●', TRUST_COLOR[node.trust])+ grid.text(Math.max(0, Math.min(columns - label.length, x - Math.floor(label.length / 2))), Math.min(rows - 1, y + 1), label, TRUST_COLOR[node.trust])+ })++ if (nodes.length > shown.length) grid.text(0, rows - 1, `+${nodes.length - shown.length} more`, COLOR.dim)++ return grid+}++export type HealthRow = { name: string; cells: (boolean | null)[] }++/** A health matrix: one row per plugin, a coloured block per check (green yes, red no, grey unknown), two columns wide. */+export function heatmapPicture(rows: readonly HealthRow[], checks: readonly string[], columns: number, height: number): Grid {+ const grid = new Grid(columns, height)+ const half = Math.floor(columns / 2)+ const nameWidth = Math.max(6, half - checks.length * 2 - 2)+ const perColumn = height - 1++ for (let side = 0; side < 2; side++) {+ checks.forEach((check, c) => grid.text(side * half + nameWidth + c * 2, 0, check.slice(0, 1).toUpperCase(), COLOR.dim))+ }++ rows.slice(0, perColumn * 2).forEach((row, i) => {+ const side = Math.floor(i / perColumn)+ const y = 1 + (i % perColumn)+ const x0 = side * half++ grid.text(x0, y, row.name.slice(0, nameWidth - 1), 0xd0d0d0)+ row.cells.forEach((cell, c) => grid.set(x0 + nameWidth + c * 2, y, cell === null ? '·' : '■', cell === null ? COLOR.dim : cell ? COLOR.ok : COLOR.bad))+ })++ return grid+}++export type Lane = { label: string; spans: { fromMs: number; toMs: number; busy: boolean }[]; ticks: number[] }++/**+ * Agents × time: a row per agent over [fromMs, toMs], busy stretches amber, idle blue, a white tick per tool call the+ * console saw. Only what was observed since the console loaded is drawn; before that the row is blank.+ */+export function ganttPicture(lanes: readonly Lane[], columns: number, fromMs: number, toMs: number, nowMs: number): Grid {+ const rows = Math.max(2, Math.min(lanes.length, 30) + 1)+ const grid = new Grid(columns, rows)+ const labelWidth = Math.min(16, Math.max(6, ...lanes.map(lane => lane.label.length + 1)))+ const width = Math.max(4, columns - labelWidth)+ const xOf = (ms: number) => labelWidth + Math.floor(((ms - fromMs) / Math.max(1, toMs - fromMs)) * (width - 1))+ const minutes = Math.max(1, Math.round((toMs - fromMs) / 60_000))++ grid.text(labelWidth, 0, `${minutes}m ago`, COLOR.dim)+ grid.text(columns - 3, 0, 'now', COLOR.dim)+ grid.set(Math.min(columns - 1, xOf(nowMs)), 0, '▾', COLOR.accent)++ lanes.slice(0, rows - 1).forEach((lane, i) => {+ const y = i + 1++ grid.text(0, y, lane.label.slice(0, labelWidth - 1), 0xd0d0d0)++ for (const span of lane.spans) {+ for (let x = Math.max(labelWidth, xOf(span.fromMs)); x <= Math.min(columns - 1, xOf(span.toMs)); x++) grid.set(x, y, span.busy ? '█' : '▁', span.busy ? COLOR.warn : mix(COLOR.info, 0x000000, 0.3))+ }++ for (const tick of lane.ticks) {+ if (tick >= fromMs) grid.set(Math.min(columns - 1, xOf(tick)), y, '▮', 0xffffff)+ }+ })++ return grid+}diff --git a/plugins/ruflo-console/hooks/gfx/pictures.ts b/plugins/ruflo-console/hooks/gfx/pictures.tsindex 8dffa7d226..060e67b4a7 100644--- a/plugins/ruflo-console/hooks/gfx/pictures.ts+++ b/plugins/ruflo-console/hooks/gfx/pictures.ts@@ -1,17 +1,19 @@/**- * Every animated picture the console draws, each a pure function of its data, its size and the real clock `t` (ms).- * The render and every `$.ui.blit` frame call the same function with the same size, so a frame always fits the mounted- * Raster. What motion means is said in the view beside each picture: data where it is data, decoration where it is not.+ * The animated pictures of the overview, swarm and learning views, each a pure function of its data, its size and the+ * real clock `t` (ms). The render and every `$.ui.blit` frame call the same function with the same size, so a frame+ * always fits the mounted Raster. What motion means is said beside each picture: data where it is data, decoration+ * where it is not.*/import { Braille, COLOR, Grid, mix, ramp, sparkline } from './raster'-export type TopoNode = { id: string; label: string; status: string; isLeader: boolean }+export type TopoNode = { id: string; label: string; status: string; isLeader: boolean; /** When the console last saw an event about it. */ pulseAtMs?: number }export type TopoModel = { topology: string; nodes: TopoNode[] }+export const PULSE_MS = 1_400const isBusy = (status: string) => /busy|active|running|working/i.test(status)const isDown = (status: string) => /stop|terminat|offline|dead|error|fail/i.test(status)-function nodeColor(node: TopoNode): number {+export function nodeColor(node: TopoNode): number {if (node.isLeader) return COLOR.accentif (isDown(node.status)) return /error|fail/i.test(node.status) ? COLOR.bad : COLOR.dimif (isBusy(node.status)) return COLOR.warn@@ -19,22 +21,34 @@ function nodeColor(node: TopoNode): number {return COLOR.info}-/** Where each node sits, in braille dots, by topology: a tree for hierarchical and star, a circle for mesh and ring. */+/**+ * Where each node sits, in braille dots, by topology: a tree (rows of workers under the leader) for hierarchical and+ * star, a circle for mesh and ring. Large swarms wrap into more rows rather than overprinting.+ */export function layout(model: TopoModel, width: number, height: number): { x: number; y: number }[] {const n = model.nodes.length- const isTree = /hier|star|queen/i.test(model.topology) && !/mesh/i.test(model.topology)- const isHybrid = /hierarchical-mesh/i.test(model.topology)+ const topology = model.topology.toLowerCase()+ const isCircle = (topology.includes('mesh') && !topology.includes('hierarchical')) || topology.includes('ring')- if (n === 0) {- return []- }+ if (n === 0) return []++ if (!isCircle) {+ const workers = n - 1+ const perRow = Math.max(1, Math.min(workers, Math.floor(width / 10)))+ const tiers = Math.max(1, Math.ceil(workers / perRow))+ const top = 3+ const span = Math.max(4, height - 6 - top)++ return model.nodes.map((_, i) => {+ if (i === 0) return { x: width / 2, y: top }- if (isTree || isHybrid) {- const workers = Math.max(1, n - 1)+ const k = i - 1+ const tier = Math.floor(k / perRow)+ const inTier = Math.min(perRow, workers - tier * perRow)+ const slot = k % perRow- return model.nodes.map((node, i) =>- i === 0 ? { x: width / 2, y: 3 } : { x: ((i - 0.5) / workers) * (width - 8) + 4, y: Math.max(8, height - 6) },- )+ return { x: ((slot + 0.5) / inTier) * (width - 8) + 4, y: top + 6 + (tiers === 1 ? span - 2 : (tier / Math.max(1, tiers - 1)) * (span - 2)) }+ })}const cx = width / 2@@ -48,40 +62,37 @@ export function layout(model: TopoModel, width: number, height: number): { x: nu})}-/** The edges a topology draws between node indexes. */+/** The edges a topology draws between node indexes (capped: a 100-agent mesh draws its first 300). */export function edges(model: TopoModel): [number, number][] {const n = model.nodes.lengthconst out: [number, number][] = []const topology = model.topology.toLowerCase()- if (n < 2) {- return out- }+ if (n < 2) return outif (topology.includes('mesh') && !topology.includes('hierarchical')) {- for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) out.push([a, b])+ for (let a = 0; a < n && out.length < 300; a++) for (let b = a + 1; b < n && out.length < 300; b++) out.push([a, b])} else if (topology.includes('ring')) {for (let a = 0; a < n; a++) out.push([a, (a + 1) % n])} else {for (let b = 1; b < n; b++) out.push([0, b])-- if (topology.includes('hierarchical-mesh')) {- for (let a = 1; a < n - 1; a++) out.push([a, a + 1])- }+ if (topology.includes('hierarchical-mesh')) for (let a = 1; a < n - 1; a++) out.push([a, a + 1])}- return out.slice(0, 200)+ return out}/**- * The swarm graph: nodes coloured by the status ruflo wrote, the leader in the accent colour, and pulses running from- * the leader along each edge to an agent whose status is busy. With no busy agent, the leader only breathes: decoration.+ * The swarm graph: nodes coloured by the status ruflo wrote (busy amber, idle blue, stopped grey), the leader starred.+ * A dot runs from the leader to a node once each time the console sees an event about that agent (data); the leader's+ * slow heartbeat is decoration.*/export function topologyPicture(model: TopoModel, columns: number, rows: number, t: number): Grid {const grid = new Grid(columns, rows)const canvas = new Braille(columns, rows)const points = layout(model, canvas.width, canvas.height)const links = edges(model)+ const leader = points[0]for (const [a, b] of links) {const p = points[a]@@ -90,29 +101,24 @@ export function topologyPicture(model: TopoModel, columns: number, rows: number,if (p !== undefined && q !== undefined) canvas.line(p.x, p.y, q.x, q.y, COLOR.line)}- links.forEach(([a, b], i) => {- const p = points[a]- const q = points[b]- const target = model.nodes[b]-- if (p === undefined || q === undefined || target === undefined || !isBusy(target.status)) {- return- }+ model.nodes.forEach((node, i) => {+ const q = points[i]+ const k = node.pulseAtMs === undefined ? -1 : (t - node.pulseAtMs) / PULSE_MS- for (const lag of [0, 0.5]) {- const k = (((t / 1400 + i * 0.13 + lag) % 1) + 1) % 1+ if (i === 0 || leader === undefined || q === undefined || k < 0 || k > 1) return- const x = p.x + (q.x - p.x) * k- const y = p.y + (q.y - p.y) * k+ const x = leader.x + (q.x - leader.x) * k+ const y = leader.y + (q.y - leader.y) * k- // Two dots wide, so a pulse on a vertical edge stands out of the line rather than sitting on its dots.- canvas.dot(x, y, COLOR.warn)- canvas.dot(x + 1, y, COLOR.warn)- }+ // Two dots wide, so a pulse on a vertical edge stands out of the line rather than sitting on its dots.+ canvas.dot(x, y, 0xffffff)+ canvas.dot(x + 1, y, 0xffffff)})canvas.blitInto(grid, 0, 0)+ const room = Math.floor(columns / Math.max(2, Math.min(model.nodes.length, Math.floor(canvas.width / 10))))+points.forEach((point, i) => {const node = model.nodes[i]@@ -120,12 +126,17 @@ export function topologyPicture(model: TopoModel, columns: number, rows: number,const cx = Math.floor(point.x / 2)const cy = Math.floor(point.y / 4)- const breath = node.isLeader ? 0.5 + 0.5 * Math.sin(t / 450) : 1- const color = node.isLeader ? mix(COLOR.line, COLOR.accent, breath) : nodeColor(node)- const label = node.label.slice(0, Math.max(3, Math.floor(columns / Math.max(2, model.nodes.length)) - 2))+ const heartbeat = node.isLeader ? Math.max(0, Math.sin(t / 260)) ** 6 : 0+ const flash = node.pulseAtMs !== undefined && t - node.pulseAtMs >= 0 && t - node.pulseAtMs < PULSE_MS + 600+ const color = flash ? 0xffffff : node.isLeader ? mix(COLOR.accent, 0xffffff, heartbeat) : nodeColor(node)grid.set(cx, cy, node.isLeader ? '★' : '●', color)- grid.text(Math.max(0, Math.min(columns - label.length, cx - Math.floor(label.length / 2))), Math.min(rows - 1, cy + 1), label, node.isLeader ? COLOR.accent : nodeColor(node))++ if (room >= 5 || node.isLeader) {+ const label = node.label.slice(0, Math.max(3, room - 1))++ grid.text(Math.max(0, Math.min(columns - label.length, cx - Math.floor(label.length / 2))), Math.min(rows - 1, cy + 1), label, node.isLeader ? COLOR.accent : nodeColor(node))+ }})return grid@@ -147,9 +158,7 @@ export function activityPicture(series: readonly { label: string; values: readonconst glow = 0.5 + 0.5 * Math.sin(t / 300)const last = labelWidth + width - 1- if ((entry.values[entry.values.length - 1] ?? 0) > 0) {- grid.set(last, row, grid.glyph(last, row), mix(COLOR.info, 0xffffff, glow * 0.6))- }+ if ((entry.values[entry.values.length - 1] ?? 0) > 0) grid.set(last, row, grid.glyph(last, row), mix(COLOR.info, 0xffffff, glow * 0.6))})return grid@@ -157,16 +166,14 @@ export function activityPicture(series: readonly { label: string; values: readon/*** The running success rate of routed tasks (routing-outcomes.json), oldest left, as a braille line over a 0-100% frame.- * A cursor walks the line: decoration, the line is the data.+ * When new outcomes arrive the newest stretch draws in over 900 ms from `grewAtMs`: that motion is data arriving.*/-export function curvePicture(points: readonly boolean[], columns: number, rows: number, t: number): Grid {+export function curvePicture(points: readonly boolean[], columns: number, rows: number, t: number, grewAtMs = 0): Grid {const grid = new Grid(columns, rows)- const canvas = new Braille(columns - 5, rows)+ const canvas = new Braille(Math.max(1, columns - 5), rows)const n = points.length- for (let r = 0; r < rows; r++) {- grid.text(0, r, r === 0 ? '100%' : r === rows - 1 ? ' 0%' : ' ', COLOR.dim)- }+ for (let r = 0; r < rows; r++) grid.text(0, r, r === 0 ? '100%' : r === rows - 1 ? ' 0%' : ' ', COLOR.dim)if (n === 0) {grid.text(6, Math.floor(rows / 2), 'no routed outcomes on disk yet', COLOR.dim)@@ -182,101 +189,38 @@ export function curvePicture(points: readonly boolean[], columns: number, rows:})const xOf = (i: number) => (n === 1 ? canvas.width / 2 : (i / (n - 1)) * (canvas.width - 1))const yOf = (rate: number) => (1 - rate) * (canvas.height - 1)+ const drawIn = grewAtMs > 0 ? Math.max(0, Math.min(1, (t - grewAtMs) / 900)) : 1+ const shown = Math.max(1, Math.round(n * (0.8 + 0.2 * drawIn)))for (let x = 0; x < canvas.width; x += 4) canvas.dot(x, yOf(0.5), COLOR.line)-- for (let i = 1; i < n; i++) canvas.line(xOf(i - 1), yOf(rates[i - 1] as number), xOf(i), yOf(rates[i] as number), ramp(rates[i] as number))-+ for (let i = 1; i < shown; i++) canvas.line(xOf(i - 1), yOf(rates[i - 1] as number), xOf(i), yOf(rates[i] as number), ramp(rates[i] as number))if (n === 1) canvas.dot(xOf(0), yOf(rates[0] as number), ramp(rates[0] as number))- const cursor = Math.floor(((t / 120) % n) + n) % n-- canvas.dot(xOf(cursor), yOf(rates[cursor] as number), 0xffffff)canvas.blitInto(grid, 5, 0)return grid}-/** A claim's bar: remaining time to `expiresAt` when ruflo set one, else its age on a 24 h scale. */-export type ClaimBar = { label: string; claimedAtMs?: number; expiresAtMs?: number; progress?: number; isStealable: boolean }--const DAY = 86_400_000--const span = (ms: number): string => {- const s = Math.max(0, Math.round(ms / 1000))-- if (s < 60) return `${s}s`- if (s < 3600) return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`- if (s < 86_400) return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`-- return `${Math.floor(s / 86_400)}d${Math.floor((s % 86_400) / 3600)}h`-}--/** One row per claim, counted on the real clock `nowMs`: a TTL counts down, an age counts up. Both are data. */-export function claimsPicture(bars: readonly ClaimBar[], columns: number, rows: number, nowMs: number): Grid {- const grid = new Grid(columns, rows)- const labelWidth = Math.min(22, Math.max(10, Math.floor(columns * 0.32)))- const textWidth = 12- const barWidth = Math.max(4, columns - labelWidth - textWidth - 1)-- bars.slice(0, rows).forEach((bar, row) => {- grid.text(0, row, bar.label.slice(0, labelWidth - 1), bar.isStealable ? COLOR.warn : COLOR.info)-- const hasTtl = bar.expiresAtMs !== undefined && bar.claimedAtMs !== undefined && bar.expiresAtMs > bar.claimedAtMs- const left = hasTtl ? (bar.expiresAtMs as number) - nowMs : 0- const fraction = hasTtl- ? Math.max(0, Math.min(1, left / ((bar.expiresAtMs as number) - (bar.claimedAtMs as number))))- : bar.claimedAtMs === undefined- ? 0- : Math.max(0, Math.min(1, (nowMs - bar.claimedAtMs) / DAY))- const filled = fraction * barWidth- const color = hasTtl ? (fraction < 0.2 ? COLOR.bad : fraction < 0.5 ? COLOR.warn : COLOR.ok) : mix(COLOR.info, COLOR.warn, fraction)-- for (let i = 0; i < barWidth; i++) {- const part = Math.max(0, Math.min(1, filled - i))-- grid.set(labelWidth + i, row, part >= 1 ? '█' : part > 0.5 ? '▌' : '·', part > 0 ? color : COLOR.line)- }-- const words = hasTtl ? (left > 0 ? `ttl ${span(left)}` : 'ttl expired') : bar.claimedAtMs === undefined ? 'age n/a' : `age ${span(nowMs - bar.claimedAtMs)}`+/** The band's mark: a diamond that pulses while Claude works and rests otherwise. */+export function markPicture(isWorking: boolean, t: number): Grid {+ const grid = new Grid(2, 1)+ const k = isWorking ? 0.5 + 0.5 * Math.sin(t / 220) : 1- grid.text(labelWidth + barWidth + 1, row, words.slice(0, textWidth), hasTtl && left <= 0 ? COLOR.bad : COLOR.dim)- })+ grid.set(0, 0, '◆', isWorking ? mix(COLOR.line, COLOR.accent, k) : COLOR.accent)return grid}-/** Score bars 0-100 that fill to their value over the first 700 ms after `sinceMs`, then hold: the fill is decoration. */-export function scorePicture(dims: readonly { name: string; value: number }[], columns: number, t: number, sinceMs: number): Grid {- const grid = new Grid(columns, Math.max(1, dims.length))- const labelWidth = 19- const barWidth = Math.max(4, columns - labelWidth - 5)- const grow = Math.max(0, Math.min(1, (t - sinceMs) / 700))- const eased = 1 - (1 - grow) ** 3-- dims.forEach((dim, row) => {- grid.text(0, row, dim.name.slice(0, labelWidth - 1), COLOR.dim)+/** The pane's title strip: a highlight sweeps across it every few seconds while the pane is focused. Decoration only. */+export function headerPicture(title: string, columns: number, t: number): Grid {+ const grid = new Grid(columns, 1)+ const at = ((t / 22) % (columns + 60)) - 20- const filled = (dim.value / 100) * barWidth * eased+ ;[...title.slice(0, columns)].forEach((ch, x) => {+ const glow = Math.max(0, 1 - Math.abs(x - at) / 6)- for (let i = 0; i < barWidth; i++) {- const part = Math.max(0, Math.min(1, filled - i))-- grid.set(labelWidth + i, row, part >= 1 ? '█' : part > 0.5 ? '▌' : '·', part > 0 ? ramp(dim.value / 100) : COLOR.line)- }-- grid.text(labelWidth + barWidth + 1, row, String(Math.round(dim.value)).padStart(3), ramp(dim.value / 100))+ grid.set(x, 0, ch, mix(x < 2 ? COLOR.accent : COLOR.dim, 0xffffff, glow * 0.8))})return grid}--/** The band's mark: a diamond that pulses while Claude works and rests otherwise. */-export function markPicture(isWorking: boolean, t: number): Grid {- const grid = new Grid(2, 1)- const k = isWorking ? 0.5 + 0.5 * Math.sin(t / 220) : 1-- grid.set(0, 0, '◆', isWorking ? mix(COLOR.line, COLOR.accent, k) : COLOR.accent)-- return grid-}diff --git a/plugins/ruflo-console/hooks/host.ts b/plugins/ruflo-console/hooks/host.tsindex 348e39d218..b152860596 100644--- a/plugins/ruflo-console/hooks/host.ts+++ b/plugins/ruflo-console/hooks/host.ts@@ -14,6 +14,7 @@ export type OpenResult = { isPlaced: boolean; reason?: string } | voidexport type Host = {fs: ReaderFsevery: (ms: number, fn: () => void) => Timer+ after: (ms: number, fn: () => void) => TimerstoreGet: (key: string) => Promise<unknown>storeSet: (key: string, value: unknown) => Promise<void>invalidate: () => voiddiff --git a/plugins/ruflo-console/hooks/ops.ts b/plugins/ruflo-console/hooks/ops.tsnew file mode 100644index 0000000000..bf5f1b5d13--- /dev/null+++ b/plugins/ruflo-console/hooks/ops.ts@@ -0,0 +1,125 @@+/**+ * The palette's operations beyond the claims board, each a fixed argv for the ruflo CLI (long flags: the short ones are+ * not accepted everywhere). Ids pass `idOf`; free text from the palette's input passes `textArg` and is always one argv+ * element. Read-only operations run at once; every other one goes through the confirm step.+ */+import { exec, type ActionSpec } from './actions'+import { idOf, plain, type AgentRecord, type ClaimRecord } from './data/parse'++export const AGENT_TYPES = ['coder', 'tester', 'reviewer', 'researcher', 'architect', 'planner', 'security-auditor', 'performance-engineer'] as const+export const WORKERS = ['audit', 'optimize', 'testgaps', 'map', 'consolidate', 'document', 'benchmark', 'deepdive'] as const++/** Free text as one argv element: cleaned, bounded, and never one the CLI would read as a flag. */+export function textArg(value: string, max = 200): string | null {+ const text = plain(value, max)++ return text === '' || text.startsWith('-') ? null : text+}++export function spawnAgent(type: string, nowMs: number): ActionSpec | null {+ if (!(AGENT_TYPES as readonly string[]).includes(type)) return null++ const name = `${type}-${String(nowMs).slice(-5)}`++ return {+ label: `spawn a ${type} agent named ${name}`,+ args: ['agent', 'spawn', '--type', type, '--name', name],+ expect: 'a new agent in .claude-flow/agents/store.json',+ verify: snapshot => snapshot.agents.some(agent => agent.name === name || agent.type === type),+ }+}++export function stopAgent(agent: AgentRecord): ActionSpec | null {+ const id = idOf(agent.id)++ return id === null+ ? null+ : { label: `stop agent ${agent.name ?? agent.type} (${id})`, args: ['agent', 'stop', id], expect: 'the agent no longer idle or busy', verify: snapshot => !snapshot.agents.some(entry => entry.id === id && /idle|busy/.test(entry.status)) }+}++export function agentLogs(agent: AgentRecord): ActionSpec | null {+ const id = idOf(agent.id)++ return id === null ? null : { label: `logs of ${agent.name ?? agent.type}`, args: ['agent', 'logs', '--id', id, '--tail', '20'], expect: 'the log lines', isReadOnly: true }+}++/** ruflo pauses claims, not agents. */+export function setClaimStatus(claim: ClaimRecord, status: 'paused' | 'active'): ActionSpec | null {+ const issueId = idOf(claim.issueId)++ return issueId === null+ ? null+ : {+ label: `${status === 'paused' ? 'pause' : 'resume'} the claim on ${issueId}`,+ args: exec('claims_status', { issueId, status, note: 'from ruflo-console' }),+ expect: `the claim ${status}`,+ verify: snapshot => snapshot.claims.some(entry => entry.issueId === issueId && entry.status === status),+ }+}++/** Asks the router again for a task's words: it answers a pick and changes nothing the console reads. */+export function reroute(description: string): ActionSpec | null {+ const task = textArg(description, 300)++ return task === null ? null : { label: `route "${task.slice(0, 40)}"`, args: ['hooks', 'route', '--task', task, '--format', 'json'], expect: 'a pick printed by the router', isReadOnly: true }+}++export function swarmInit(): ActionSpec {+ return {+ label: 'initialise a hierarchical swarm (max 8, specialized)',+ args: ['swarm', 'init', '--topology', 'hierarchical', '--max-agents', '8', '--strategy', 'specialized'],+ expect: 'a swarm in .claude-flow/swarm/swarm-state.json',+ verify: snapshot => snapshot.swarm !== null,+ }+}++export function swarmStop(): ActionSpec {+ return { label: 'stop the swarm', args: ['swarm', 'stop'], expect: 'the swarm no longer running', verify: snapshot => snapshot.swarm?.status !== 'running' }+}++export function vote(proposalId: string, isFor: boolean): ActionSpec | null {+ const id = idOf(proposalId)++ return id === null+ ? null+ : {+ label: `vote ${isFor ? 'yes' : 'no'} on ${id} as console-operator`,+ args: ['hive-mind', 'consensus', '--action', 'vote', '--proposal-id', id, '--vote', isFor ? 'yes' : 'no', '--voter-id', 'console-operator'],+ expect: 'a vote counted on the proposal',+ verify: snapshot => {+ const proposal = snapshot.hive?.pending.find(entry => entry.id === id)++ return snapshot.hive?.history.some(entry => entry.id === id) === true || (proposal !== undefined && proposal.votesFor + proposal.votesAgainst > 0)+ },+ }+}++export const harnessScore = (): ActionSpec => ({ label: 'score the harness now', args: ['metaharness', 'score', '--format', 'json'], expect: 'the five scores', isReadOnly: true })++export const harnessAudit = (): ActionSpec => ({ label: 'run a MetaHarness OIA audit (stored in memory namespace metaharness-audit)', args: ['metaharness', 'oia-audit'], expect: 'an audit record' })++export function dispatchWorker(worker: string): ActionSpec | null {+ return (WORKERS as readonly string[]).includes(worker) ? { label: `dispatch the ${worker} worker`, args: ['hooks', 'worker', 'dispatch', '--trigger', worker], expect: 'the worker queued' } : null+}++export function memoryStore(value: string, nowMs: number): ActionSpec | null {+ const text = textArg(value, 500)+ const key = `console-${nowMs}`++ return text === null ? null : { label: `store "${text.slice(0, 40)}" as ${key} in namespace console`, args: ['memory', 'store', '--key', key, '--value', text, '--namespace', 'console'], expect: 'one more memory entry' }+}++export function memorySearch(query: string): ActionSpec | null {+ const text = textArg(query, 200)++ return text === null ? null : { label: `search memory for "${text.slice(0, 40)}"`, args: ['memory', 'search', '--query', text, '--limit', '5'], expect: 'the matches', isReadOnly: true }+}++/** The lines a read-only run printed, cleaned, without the CLI's banners, at most `max`. */+export function outputLines(stdout: string, max = 12): string[] {+ return stdout+ .split('\n')+ .map(line => plain(line, 160))+ .filter(line => line !== '' && !/^(Transformers\.js loaded|\[INFO\] Executing tool|\[OK\] Tool executed)/.test(line))+ .slice(0, max)+}diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.tsnew file mode 100644index 0000000000..612024e283--- /dev/null+++ b/plugins/ruflo-console/hooks/palette.ts@@ -0,0 +1,128 @@+/**+ * The command palette: every action the console can take, as a flat list filtered by a fuzzy query. Pure: it builds+ * entries from the state; the controller runs the one picked. Text-taking entries (route, store, search) read their+ * argument from the query after their keyword: `route fix the login bug`.+ */+import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'+import { AGENT_TYPES, agentLogs, dispatchWorker, harnessAudit, harnessScore, memorySearch, memoryStore, reroute, setClaimStatus, spawnAgent, stopAgent, swarmInit, swarmStop, vote, WORKERS } from './ops'+import { VIEWS, type State, type ViewId } from './state'+import { selection } from './views/select'++export type PaletteRun =+ | { kind: 'spec'; spec: ActionSpec | null; why: string }+ | { kind: 'view'; view: ViewId }+ | { kind: 'drill'; agentId: string }+ | { kind: 'text'; keyword: string; make: (text: string) => ActionSpec | null }+ | { kind: 'command'; name: 'refresh' | 'help' | 'close' }++export type PaletteEntry = { id: string; label: string; group: string; run: PaletteRun }++/** A subsequence match score: higher is better, null when the query's letters are not all there in order. */+export function fuzzy(query: string, label: string): number | null {+ const q = query.trim().toLowerCase()+ const text = label.toLowerCase()++ if (q === '') return 0++ let at = 0+ let score = 0+ let streak = 0++ for (const ch of q) {+ if (ch === ' ') continue++ const found = text.indexOf(ch, at)++ if (found < 0) return null++ streak = found === at ? streak + 1 : 0+ score += 1 + streak * 2 - Math.min(5, found - at) * 0.1 + (found === 0 || text[found - 1] === ' ' ? 2 : 0)+ at = found + 1+ }++ // A contiguous match beats a scattered one, most of all at a word's start.+ const whole = text.indexOf(q)++ return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0)+}++const TEXT_KEYWORDS = ['route', 'store', 'search'] as const++/** Every entry for the state as it is, before filtering. */+export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {+ const { claim, agent, task } = selection(state)+ const out: PaletteEntry[] = []+ const add = (id: string, group: string, label: string, run: PaletteRun) => out.push({ id, group, label, run })++ if (agent !== null) {+ const name = agent.name ?? agent.type++ add('agent-drill', 'agent', `open ${name}: role, task, claims, logs, timeline`, { kind: 'drill', agentId: agent.id })+ add('agent-logs', 'agent', `show the logs of ${name}`, { kind: 'spec', spec: agentLogs(agent), why: 'that agent id cannot be passed to ruflo' })+ add('agent-stop', 'agent', `stop agent ${name}`, { kind: 'spec', spec: stopAgent(agent), why: 'that agent id cannot be passed to ruflo' })+ }++ if (claim !== null) {+ const paused = claim.status === 'paused'++ add('claim-pause', 'claims', `${paused ? 'resume' : 'pause'} the claim on ${claim.issueId}`, { kind: 'spec', spec: setClaimStatus(claim, paused ? 'active' : 'paused'), why: 'that claim cannot be passed to ruflo' })+ add('claim-release', 'claims', `release ${claim.issueId}`, { kind: 'spec', spec: releaseClaim(claim), why: 'that claimant cannot be named to ruflo' })++ if (agent !== null) {+ add('claim-handoff', 'claims', `hand ${claim.issueId} off to ${agent.name ?? agent.type}`, { kind: 'spec', spec: handoffClaim(claim, agent), why: 'the picked agent already holds it, or an id cannot be passed' })+ add('claim-steal', 'claims', `steal ${claim.issueId} for ${agent.name ?? agent.type}`, { kind: 'spec', spec: stealClaim(claim, agent), why: claim.isStealable ? 'the picked agent already holds it' : 'the claim is not marked stealable' })+ }+ }++ if (task !== null && agent !== null) add('task-claim', 'claims', `claim task ${task.id} for ${agent.name ?? agent.type}`, { kind: 'spec', spec: claimTask(task, agent), why: 'an id cannot be passed to ruflo' })++ for (const type of AGENT_TYPES) add(`spawn-${type}`, 'swarm', `spawn a ${type} agent`, { kind: 'spec', spec: spawnAgent(type, nowMs), why: 'unknown agent type' })++ add('swarm-init', 'swarm', 'start a swarm: init hierarchical, max 8, specialized', { kind: 'spec', spec: swarmInit(), why: '' })+ add('swarm-stop', 'swarm', 'stop the swarm', { kind: 'spec', spec: swarmStop(), why: '' })++ for (const proposal of state.snapshot?.hive?.pending.slice(-3) ?? []) {+ add(`vote-yes-${proposal.id}`, 'hive', `vote yes on ${proposal.type} (${proposal.id})`, { kind: 'spec', spec: vote(proposal.id, true), why: 'that proposal id cannot be passed to ruflo' })+ add(`vote-no-${proposal.id}`, 'hive', `vote no on ${proposal.type} (${proposal.id})`, { kind: 'spec', spec: vote(proposal.id, false), why: 'that proposal id cannot be passed to ruflo' })+ }++ add('mh-score', 'metaharness', 'score the harness now (metaharness score)', { kind: 'spec', spec: harnessScore(), why: '' })+ add('mh-audit', 'metaharness', 'run a MetaHarness audit (oia-audit)', { kind: 'spec', spec: harnessAudit(), why: '' })++ for (const worker of WORKERS) add(`worker-${worker}`, 'workers', `dispatch the ${worker} background worker`, { kind: 'spec', spec: dispatchWorker(worker), why: 'unknown worker' })++ add('route', 'learning', 'route <task words>: ask the router for a pick', { kind: 'text', keyword: 'route', make: reroute })+ add('store', 'memory', 'store <text>: save a note in memory namespace console', { kind: 'text', keyword: 'store', make: text => memoryStore(text, nowMs) })+ add('search', 'memory', 'search <query>: semantic memory search', { kind: 'text', keyword: 'search', make: memorySearch })++ for (const view of VIEWS) add(`view-${view.id}`, 'views', `go to ${view.label} (${view.key})`, { kind: 'view', view: view.id })++ add('refresh', 'console', 'refresh now', { kind: 'command', name: 'refresh' })+ add('help', 'console', 'help: keys and commands', { kind: 'command', name: 'help' })+ add('close', 'console', 'close the console', { kind: 'command', name: 'close' })++ return out+}++/** The entries matching `query`, best first; a text entry matches when the query starts with its keyword. */+export function filterPalette(entries: readonly PaletteEntry[], query: string, context: 'all' | 'selection'): PaletteEntry[] {+ const words = query.trim()+ const keyword = words.split(/\s+/)[0]?.toLowerCase() ?? ''+ const scoped = context === 'selection' ? entries.filter(entry => entry.group === 'agent' || entry.group === 'claims') : entries++ if ((TEXT_KEYWORDS as readonly string[]).includes(keyword) && words.length > keyword.length) {+ return scoped.filter(entry => entry.run.kind === 'text' && entry.run.keyword === keyword)+ }++ return scoped+ .flatMap(entry => {+ const score = fuzzy(words, entry.label)++ return score === null ? [] : [{ entry, score }]+ })+ .sort((a, b) => b.score - a.score)+ .map(match => match.entry)+}++/** The argument a text entry takes from the query: everything after its keyword. */+export const textOfQuery = (query: string, keyword: string): string => query.trim().slice(keyword.length).trim()diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.tsindex ff94c9b80f..870dd31f0b 100644--- a/plugins/ruflo-console/hooks/register.ts+++ b/plugins/ruflo-console/hooks/register.ts@@ -1,11 +1,13 @@import type { EngineInterface, PluginOptions, Register } from 'claude-code'-import { createController, median, p95, type Controller } from './controller'+import { createController, type Controller } from './controller'+import { record } from './data/events'import { plain } from './data/parse'+import { dispatch } from './dispatch'import { markPicture } from './gfx/pictures'import type { Host } from './host'-import { newState, PANE_ID, restore, storeKeyOf, viewOf, VIEWS, type State } from './state'-import { BAR_KEY, barText, barView } from './views/bar'+import { newState, PANE_ID, restore, storeKeyOf } from './state'+import { BAR_KEY, barView } from './views/bar'import type { Kit } from './views/common'import { picturesOf } from './views/frames'import { NARROW, paneView } from './views/pane'@@ -31,6 +33,7 @@ function hostOf($: EngineInterface, cwd: string): Host {return {fs: { read: async path => $.fs.read(rooted(path)), stat: async path => $.fs.stat(rooted(path)), list: async path => $.fs.list(rooted(path)) },every: (ms, fn) => $.clock.every(ms, fn),+ after: (ms, fn) => $.clock.after(ms, fn),storeGet: async key => $.store.get(key),storeSet: async (key, value) => $.store.set(key, value as never),invalidate: () => quietly(() => $.ui.invalidate('ui.render')),@@ -60,17 +63,10 @@ function hostOf($: EngineInterface, cwd: string): Host {}}-/** The one-line answer of `/ruflo-console status`, and the bench's numbers when asked. */-function statusLine(state: State): string {- const stat = (name: string, values: readonly number[]) => (values.length === 0 ? `${name} n/a` : `${name} median ${median(values)}ms p95 ${p95(values)}ms (n=${values.length})`)-- return [barText(state), stat('render', state.stats.renders), stat('refresh', state.stats.refreshes), stat('frame', state.stats.frames)].join(' · ')-}-/**- * ruflo-console: ruflo's cockpit inside Claude Code. A pane of eight views over ruflo's state on disk and the ruflo- * CLI's local answers, a band above the prompt, and `/ruflo-console`. Read-only but for the claims actions, which go- * through the ruflo CLI with fixed argv after a confirm.+ * ruflo-console: ruflo's cockpit inside Claude Code, and the home of `/ruflo`. A pane of views over ruflo's state on+ * disk and the ruflo CLI's local answers, a band above the prompt, a command palette, and management views (agent+ * drill-down, timeline, approvals, events). Every change goes through the ruflo CLI with fixed argv after a confirm.*/export const register: Register = (on, raw: PluginOptions) => {const state = newState(raw)@@ -87,12 +83,15 @@ export const register: Register = (on, raw: PluginOptions) => {state.home = await bound.home().catch(() => undefined) ?? nullawait Promise.all([- bound.registerCommand({ name: 'ruflo-console', description: 'ruflo console: swarms, claims, federation, plugins, learning, MetaHarness, memory', argumentHint: '[view|close|status]' }).catch(() => undefined),+ bound+ .registerCommand({ name: 'ruflo', description: 'ruflo: the cockpit (views, palette, agents, approvals) and every ruflo mod command — /ruflo help', argumentHint: '[view|palette|agent <id>|mods|swarm <sub>|help]' })+ .catch(() => undefined),bound.storeGet(storeKeyOf(e.cwd)).then(value => restore(state, value), () => undefined),bound.rufloTools().then(counted => void (state.rufloTools = counted), () => undefined),])control.start()- void control.refresh()+ await control.refresh()+ control.autoOpen()return next(e)})@@ -103,36 +102,14 @@ export const register: Register = (on, raw: PluginOptions) => {return next(e)})- on('command.run', { command: 'ruflo-console' }, async ($, e, next) => {- if (control === null) {- return next(e)- }-- const arg = e.args.trim().toLowerCase()-- if (arg === 'close') {- await control.close()-- return { text: 'ruflo console closed' }- }-- if (arg === 'status') {- await control.refresh()+ /**+ * `/ruflo`: the console's own subcommands are answered here; `mods` and `swarm <sub>` go to the plugins beneath that+ * hook the same command (ruflo-mods, ruflo-swarm), and are answered with a hint when neither does.+ */+ on('command.run', { command: 'ruflo' }, async ($, e, next) => {+ if (control === null) return next(e)- return { text: statusLine(state) }- }-- const view = arg === '' || arg === 'open' ? null : viewOf(arg)-- if (arg !== '' && arg !== 'open' && view === null) {- return { text: `Unknown view "${plain(arg, 30)}". Views: ${VIEWS.map(entry => `${entry.key} ${entry.id}`).join(', ')}; or close, status.` }- }-- if (view !== null) control.setView(view)-- const opened = await control.open()-- return { text: opened.isPlaced ? `ruflo console: ${VIEWS.find(entry => entry.id === state.view)?.label}` : `The ruflo console could not be shown: ${opened.reason}` }+ return dispatch(control, state, e.args, async () => (await next(e)) as { text?: string } | undefined)})on('ui.render', { component: 'Pane', requestId: PANE_ID }, ($, e, next) => {@@ -144,7 +121,7 @@ export const register: Register = (on, raw: PluginOptions) => {const table = $.ui.resolve(e) as unknown as Kitconst columns = Math.max(20, Math.floor(Number(e.props.bodyColumns) || 0) - 1)const isNarrow = columns < NARROW- const kit: Kit = isNarrow ? { Box: table.Box, Text: table.Text, Button: table.Button } : table+ const kit: Kit = isNarrow ? { Box: table.Box, Text: table.Text, Button: table.Button, ...(table.Input !== undefined && { Input: table.Input }) } : tablestate.pane.isOpen = truestate.pane.isFocused = e.props.isFocused === true@@ -182,7 +159,7 @@ export const register: Register = (on, raw: PluginOptions) => {bound.markFrame(e.requestId, e.props.isWorking && mark !== null)- return barView(table, state, Math.floor(Number(e.props.bodyColumns) || 80), mark, () => void bound.open())+ return barView(table, state, Math.floor(Number(e.props.bodyColumns) || 80), mark, () => void bound.open(false))})/** The band's mark pulses during a turn: a redraw at its start, and the loop stopped at its end, whatever redraws. */@@ -216,17 +193,31 @@ export const register: Register = (on, raw: PluginOptions) => {/** Observes only: every call goes on unchanged; the count feeds the activity sparkline. */on('tool.call', ($, e, next) => {- control?.noteToolCall()+ control?.noteToolCall(e.agentId, e.tool)return next(e)})+ /** Observes only: a deny any verdict reached is listed in the approvals queue; the verdict passes on unchanged. */+ on('tool.check', async ($, e, next) => {+ const verdict = await next(e)++ if (verdict.decision === 'deny') {+ state.denied.push({ tool: plain(String(e.tool), 40), reason: plain(verdict.reason ?? 'no reason given', 160), atMs: Date.now() })+ if (state.denied.length > 20) state.denied.shift()+ record(state.events, [{ atMs: Date.now(), kind: 'mods', text: `${plain(String(e.tool), 40)} denied: ${plain(verdict.reason ?? '', 80)}` }])+ }++ return verdict+ })+/** Observes only, never refuses: which mods the engine admitted or refused after the console, for the plugins view. */on('plugin.register', async ($, e, next) => {const result = await next(e)state.mods.push({ name: plain(e.name, 40), provenance: plain(e.provenance, 80), isLoaded: result.refuse === undefined, ...(result.refuse !== undefined && { reason: plain(result.refuse, 120) }), atMs: Date.now() })if (state.mods.length > 50) state.mods.shift()+ record(state.events, [{ atMs: Date.now(), kind: 'mods', text: `${plain(e.name, 40)} ${result.refuse === undefined ? 'loaded' : 'REFUSED'} (${plain(e.provenance, 60)})` }])return result})diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.tsnew file mode 100644index 0000000000..f29b0f7a0d--- /dev/null+++ b/plugins/ruflo-console/hooks/runner.ts@@ -0,0 +1,155 @@+/**+ * Runs what the person asked for: a palette entry, a claims button, an approval. A change waits for a confirm (y, or+ * `/ruflo yes`) and then runs one fixed argv through the ruflo CLI, after which the disk is re-read to say whether it+ * took; a read runs at once and shows what it printed. Nothing reaches `$` but through the Host.+ */+import type { ActionSpec } from './actions'+import { plain } from './data/parse'+import type { Host } from './host'+import { outputLines } from './ops'+import { filterPalette, paletteEntries, textOfQuery, type PaletteEntry } from './palette'+import { CLI_PREFIXES, type State } from './state'++const PENDING_TTL_MS = 30_000++export type RunnerDeps = {+ /** A read of the disk that starts after this call. */+ freshRead: () => Promise<void>+ setView: (view: State['view']) => void+ drill: (agentId: string) => void+ command: (name: 'refresh' | 'help' | 'close') => void+}++export type Runner = {+ ask: (spec: ActionSpec | null, why: string) => void+ confirm: () => Promise<void>+ cancel: () => void+ runEntry: (entry: PaletteEntry, text: string) => void+ runById: (id: string, text: string) => boolean+}++export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner {+ let pendingSpec: ActionSpec | null = null++ const say = (label: string, ok: boolean, detail: string, lines?: string[]) => {+ state.outcome = { label, ok, verified: 'n/a', detail, atMs: Date.now(), ...(lines !== undefined && { lines }) }+ host.invalidate()+ }++ async function execute(spec: ActionSpec): Promise<void> {+ state.isActing = true+ host.invalidate()++ try {+ const result = await host.run([...CLI_PREFIXES[state.options.cli], ...spec.args], 90_000)+ const answer = /"success"\s*:\s*(true|false)/.exec(result.stdout)?.[1]+ const error = /"error"\s*:\s*"([^"]{0,160})"/.exec(result.stdout)?.[1] ?? /\[ERROR\]\s*(.{0,160})/.exec(result.stdout)?.[1]+ const ok = result.exitCode === 0 && answer !== 'false' && error === undefined++ if (spec.isReadOnly === true) {+ say(spec.label, ok, ok ? 'the ruflo CLI answered:' : plain(error ?? result.stderr, 160) || `exit ${result.exitCode}`, outputLines(result.stdout))++ return+ }++ await deps.freshRead()++ const verified = spec.verify === undefined || state.snapshot === null ? 'n/a' : spec.verify(state.snapshot) ? 'yes' : 'no'++ state.outcome = {+ label: spec.label,+ ok: ok && verified !== 'no',+ verified,+ detail: ok ? `ruflo answered ok; expected ${spec.expect}` : plain(error ?? result.stderr, 160) || `exit ${result.exitCode}`,+ atMs: Date.now(),+ }+ } catch (error) {+ say(spec.label, false, plain(error instanceof Error ? error.message : String(error), 160) || 'refused')+ } finally {+ state.isActing = false+ host.invalidate()+ }+ }++ function ask(spec: ActionSpec | null, why: string): void {+ state.palette.isOpen = false++ if (spec === null) {+ say('nothing to do', false, why)++ return+ }++ if (spec.isReadOnly === true) {+ void execute(spec)++ return+ }++ pendingSpec = spec+ state.pending = { label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now() }+ host.invalidate()+ }++ async function confirm(): Promise<void> {+ const spec = pendingSpec+ const isFresh = state.pending !== null && Date.now() - state.pending.askedAtMs < PENDING_TTL_MS++ pendingSpec = null+ state.pending = null++ if (spec === null || !isFresh || state.isActing) {+ if (spec !== null && !isFresh) say(spec.label, false, 'the confirm came more than 30 s after the ask; ask again')++ host.invalidate()++ return+ }++ await execute(spec)+ }++ function cancel(): void {+ pendingSpec = null+ state.pending = null+ host.invalidate()+ }++ function runEntry(entry: PaletteEntry, text: string): void {+ state.palette.isOpen = false++ switch (entry.run.kind) {+ case 'spec':+ ask(entry.run.spec, entry.run.why)+ break+ case 'text':+ ask(entry.run.make(text), `type "${entry.run.keyword} <text>"; text may not start with -`)+ break+ case 'view':+ deps.setView(entry.run.view)+ break+ case 'drill':+ deps.drill(entry.run.agentId)+ break+ case 'command':+ deps.command(entry.run.name)+ break+ }++ host.invalidate()+ }++ /** A palette entry by its id (`/ruflo run <id> [text]`, an approval's button): false when there is none now. */+ function runById(id: string, text: string): boolean {+ const entries = paletteEntries(state, Date.now())+ const entry = entries.find(candidate => candidate.id === id) ?? (text === '' ? undefined : filterPalette(entries, `${id} ${text}`, 'all')[0])++ if (entry === undefined) return false++ runEntry(entry, entry.run.kind === 'text' ? textOfQuery(`${id} ${text}`, entry.run.keyword) : text)++ return true+ }++ return { ask, confirm, cancel, runEntry, runById }+}diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.tsindex 7573e62549..33ff8241d3 100644--- a/plugins/ruflo-console/hooks/state.ts+++ b/plugins/ruflo-console/hooks/state.ts@@ -1,6 +1,7 @@import type { PluginOptions, Timer } from 'claude-code'-import type { ProbeResult, ViewId } from './data/cli'+import type { ProbeResult } from './data/cli'+import type { ConsoleEvent } from './data/events'import type { ReadCache } from './data/files'import type { Snapshot } from './data/snapshot'import type { RufloRoute, RufloSnapshot } from '../types'@@ -8,18 +9,32 @@ import type { RufloRoute, RufloSnapshot } from '../types'export const PLUGIN_NAME = 'ruflo-console'export const PANE_ID = 'ruflo-console'-/** The views in tab order, each with its hotkey (a digit: letters are the actions'). */-export const VIEWS: readonly { id: ViewId; key: string; label: string; rows: number }[] = [- { id: 'overview', key: '1', label: 'Overview', rows: 24 },- { id: 'swarm', key: '2', label: 'Swarms', rows: 28 },- { id: 'claims', key: '3', label: 'Claims', rows: 26 },- { id: 'federation', key: '4', label: 'Federation', rows: 22 },- { id: 'plugins', key: '5', label: 'Plugins', rows: 28 },- { id: 'learning', key: '6', label: 'Learning', rows: 26 },- { id: 'metaharness', key: '7', label: 'MetaHarness', rows: 22 },- { id: 'memory', key: '8', label: 'Memory', rows: 22 },+export type ViewId = 'overview' | 'swarm' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'agent'++/**+ * The views in tab order, each with its hotkey and the inline height it asks for. Digits are the first nine; the three+ * management views take letters no other control uses. `agent` is the drill-down, reached from a selection, not a tab.+ */+export const VIEWS: readonly { id: ViewId; key: string; label: string; short: string; rows: number }[] = [+ { id: 'overview', key: '1', label: 'Overview', short: 'Ovr', rows: 26 },+ { id: 'swarm', key: '2', label: 'Swarm', short: 'Swm', rows: 30 },+ { id: 'claims', key: '3', label: 'Claims', short: 'Clm', rows: 30 },+ { id: 'federation', key: '4', label: 'Federation', short: 'Fed', rows: 26 },+ { id: 'plugins', key: '5', label: 'Plugins', short: 'Plg', rows: 30 },+ { id: 'learning', key: '6', label: 'Learning', short: 'Lrn', rows: 30 },+ { id: 'metaharness', key: '7', label: 'MetaHarness', short: 'MH', rows: 26 },+ { id: 'memory', key: '8', label: 'Memory', short: 'Mem', rows: 22 },+ { id: 'cost', key: '9', label: 'Cost', short: 'Cst', rows: 20 },+ { id: 'timeline', key: 'g', label: 'Timeline', short: 'Gnt', rows: 24 },+ { id: 'approvals', key: 'q', label: 'Approvals', short: 'Apv', rows: 24 },+ { id: 'events', key: 'e', label: 'Events', short: 'Evt', rows: 26 },]+export const AGENT_VIEW = { id: 'agent' as const, rows: 28 }++export const rowsOf = (view: ViewId): number => (view === 'agent' ? AGENT_VIEW.rows : (VIEWS.find(entry => entry.id === view)?.rows ?? 24))++/** A view by id, digit, label, or a prefix of three letters or more. */export const viewOf = (word: string): ViewId | null => {const lower = word.trim().toLowerCase()@@ -44,12 +59,14 @@ export type CliChoice = keyof typeof CLI_PREFIXESexport type Options = {cli: CliChoice- /** How often the disk is re-read while the pane or bar shows (seconds, 2-60). */+ /** How often the disk is re-read while the pane or band shows (seconds, 2-60). */refreshSeconds: number- /** The animation's frame cap while the pane is shown and focused (0 turns motion off). */+ /** The animation's frame cap while the pane is shown and focused (0 turns motion off; at most 12). */fps: number- /** `auto`: the band above the prompt shows in a ruflo project; `on`: always; `off`: never. */+ /** `auto`: the band shows in a ruflo project; `on`: always; `off`: never. */bar: 'auto' | 'on' | 'off'+ /** `auto` opens the cockpit at session start where it can dock (never taking the keys); `command` only on /ruflo; `off` never. */+ panel: 'auto' | 'command' | 'off'/** Lets the federation view ask the public relay for the roster. Off by default: no network without consent. */federationNetwork: boolean}@@ -67,8 +84,9 @@ export function optionsOf(raw: PluginOptions | undefined): Options {return {cli: typeof value.cli === 'string' && value.cli in CLI_PREFIXES ? (value.cli as CliChoice) : 'npx-offline',refreshSeconds: num(value.refreshSeconds, 3, 2, 60),- fps: num(value.fps, 8, 0, 10),+ fps: num(value.fps, 8, 0, 12),bar: value.bar === 'on' || value.bar === 'off' ? value.bar : 'auto',+ panel: value.panel === 'command' || value.panel === 'off' ? value.panel : 'auto',federationNetwork: value.federationNetwork === true,}}@@ -76,17 +94,27 @@ export function optionsOf(raw: PluginOptions | undefined): Options {/** A mutating action waiting for the person's second press. */export type Pending = { label: string; args: readonly string[]; expect: string; askedAtMs: number }-/** What an action did: what ran, how it exited, and whether the disk shows the change. */-export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number }+/** What an action did: what ran, how it exited, whether the disk shows the change, and anything it printed to show. */+export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number; lines?: string[] }/** One module seen registering since the console loaded, as the engine's scan named it. */export type ModSeen = { name: string; provenance: string; isLoaded: boolean; reason?: string; atMs: number }+/** A tool call refused by a permission verdict this session, as `tool.check` answered it. */+export type Denied = { tool: string; reason: string; atMs: number }++/** One sample of a measured series, with when it was taken. */+export type Sample = { atMs: number; value: number }+export type State = {options: Optionscwd: stringhome: string | null+ /** When this module loaded: "since the console loaded" series and stall times count from here. */+ loadedAtMs: numberview: ViewId+ /** The view to go back to from the drill-down. */+ back: ViewIdisHelp: booleansnapshot: Snapshot | nullcache: ReadCache@@ -95,14 +123,27 @@ export type State = {usage: { costUsd?: number; contextPercent?: number } | nullrufloTools: { tools: number; servers: string[] } | nullmods: ModSeen[]- /** Tool calls the console saw, per 5 s bucket, newest last: a measured series. */+ denied: Denied[]+ /** Tool calls the console saw, per 5 s bucket, newest last; and per agent (Claude Code's ids) for the timeline. */activity: number[]- /** ruflo state files that changed per refresh, newest last: a measured series. */+ toolsByAgent: Map<string, { atMs: number; tool: string }[]>+ /** ruflo state files changed per refresh, newest last. */writes: number[]- pane: { isOpen: boolean; isShown: boolean; isFocused: boolean; columns: number; rows: number; placement: 'dock' | 'inline' }+ /** Measured series since the console loaded: patterns learned, session spend. */+ history: { patterns: Sample[]; spend: Sample[]; outcomes: number }+ events: ConsoleEvent[]+ /** Each ruflo agent's status as the console saw it change, oldest first: the timeline's spans. */+ statusLog: Map<string, { atMs: number; status: string }[]>+ eventFilter: 'all' | ConsoleEvent['kind']+ /** When the newest learning point arrived: the curve draws it in from there. */+ curveGrewAtMs: number+ pane: { isOpen: boolean; isShown: boolean; isFocused: boolean; columns: number; rows: number; placement: 'dock' | 'inline'; isClosedByPerson: boolean; autoTried: boolean; autoReason: string }/** The size of each Raster as last mounted, by key: a blit of any other size is refused, so none is sent. */mounted: Map<string, { columns: number; rows: number }>- select: { claim: number; agent: number; task: number }+ select: { claim: number; agent: number; task: number; item: number }+ /** The drill-down's agent and what `agent logs` printed for it. */+ drill: { agentId: string | null; logs: string[] | null; logsAtMs: number }+ palette: { isOpen: boolean; query: string; index: number; context: 'all' | 'selection' }pending: Pending | nulloutcome: Outcome | nullisActing: boolean@@ -118,7 +159,9 @@ export function newState(raw: PluginOptions | undefined): State {options: optionsOf(raw),cwd: '',home: null,+ loadedAtMs: Date.now(),view: 'overview',+ back: 'overview',isHelp: false,snapshot: null,cache: new Map(),@@ -127,11 +170,20 @@ export function newState(raw: PluginOptions | undefined): State {usage: null,rufloTools: null,mods: [],+ denied: [],activity: [],+ toolsByAgent: new Map(),writes: [],- pane: { isOpen: false, isShown: false, isFocused: false, columns: 0, rows: 0, placement: 'inline' },+ history: { patterns: [], spend: [], outcomes: 0 },+ events: [],+ statusLog: new Map(),+ eventFilter: 'all',+ curveGrewAtMs: 0,+ pane: { isOpen: false, isShown: false, isFocused: false, columns: 0, rows: 0, placement: 'inline', isClosedByPerson: false, autoTried: false, autoReason: '' },mounted: new Map(),- select: { claim: 0, agent: 0, task: 0 },+ select: { claim: 0, agent: 0, task: 0, item: 0 },+ drill: { agentId: null, logs: null, logsAtMs: 0 },+ palette: { isOpen: false, query: '', index: 0, context: 'all' },pending: null,outcome: null,isActing: false,@@ -143,7 +195,7 @@ export function newState(raw: PluginOptions | undefined): State {}/** Keeps the newest `max` samples of a series. */-export function push(series: number[], value: number, max = 120): void {+export function push<T>(series: T[], value: T, max = 120): void {series.push(value)if (series.length > max) {@@ -152,7 +204,7 @@ export function push(series: number[], value: number, max = 120): void {}/** What is written to `$.store`: the person's choices only. */-export type Persisted = { view: ViewId }+export type Persisted = { view: ViewId; isClosedByPerson: boolean }export function restore(state: State, value: unknown): void {const held = value !== null && typeof value === 'object' ? (value as Partial<Persisted>) : {}@@ -160,4 +212,6 @@ export function restore(state: State, value: unknown): void {if (typeof held.view === 'string' && VIEWS.some(view => view.id === held.view)) {state.view = held.view}++ state.pane.isClosedByPerson = held.isClosedByPerson === true}diff --git a/plugins/ruflo-console/hooks/views/agent.ts b/plugins/ruflo-console/hooks/views/agent.tsnew file mode 100644index 0000000000..edf3fc28b4--- /dev/null+++ b/plugins/ruflo-console/hooks/views/agent.ts@@ -0,0 +1,57 @@+import type { RenderElement } from 'claude-code'++import { ago, button, col, kv, row, rule, text, THEME, type Ctx } from './common'++/**+ * One agent, drilled into: its role and state from the agent store, the tasks assigned to it and the claims it holds,+ * the status changes and events the console saw, and the tail of `ruflo agent logs`. Cost per ruflo agent is not+ * recorded anywhere, so it reads n/a; Claude Code's own spend is on the Cost view.+ */+export function agentView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const id = state.drill.agentId+ const agent = state.snapshot?.agents.find(entry => entry.id === id) ?? null+ const rows: RenderElement[] = [rule(ctx, 'Agent', id ?? '')]++ if (agent === null) {+ rows.push(text(ctx, id === null ? 'No agent picked: choose one on Swarm (2) with j/k and press d.' : `Agent ${id} is no longer in .claude-flow/agents/store.json.`, { dimColor: true }))+ rows.push(row(ctx, [button(ctx, 'back', 'Back', ctx.act.back, { hotkey: 'b' })]))++ return col(ctx, rows, 'agent')+ }++ const tasks = (state.snapshot?.tasks ?? []).filter(task => task.assignedTo.includes(agent.id))+ const claims = (state.snapshot?.claims ?? []).filter(claim => claim.claimant.id === agent.id || claim.handoffTo === agent.id)+ const log = state.statusLog.get(agent.id) ?? []+ const events = state.events.filter(event => event.agentId === agent.id).slice(-6)++ rows.push(kv(ctx, 'role', `${agent.name ?? agent.type} · ${agent.type}`))+ rows.push(kv(ctx, 'status', `${agent.status} · health ${agent.health === undefined ? 'n/a' : `${Math.round(agent.health * 100)}%`} · tasks counted ${agent.taskCount ?? 'n/a'}`, /busy/i.test(agent.status) ? THEME.warn : THEME.info))+ rows.push(kv(ctx, 'created', agent.createdAtMs === undefined ? 'n/a' : ago(agent.createdAtMs, nowMs)))+ rows.push(kv(ctx, 'current task', tasks.length === 0 ? 'none assigned in tasks/store.json' : tasks.map(task => `${task.id} (${task.status}) ${task.description}`).join(' · ')))+ rows.push(kv(ctx, 'claims', claims.length === 0 ? 'none' : claims.map(claim => `${claim.issueId} ${claim.status}${claim.handoffTo === agent.id ? ' (handoff to it)' : ''}`).join(' · ')))+ rows.push(kv(ctx, 'tokens / cost', "n/a — ruflo records no per-agent usage; Claude Code's spend is on Cost (9)"))++ rows.push(rule(ctx, 'Timeline', 'status changes seen since the console loaded'))+ rows.push(text(ctx, log.length === 0 ? 'no change seen yet' : log.slice(-6).map(entry => `${ago(entry.atMs, nowMs)} ${entry.status}`).join(' → '), { dimColor: log.length === 0 }))++ for (const event of events) rows.push(text(ctx, `${ago(event.atMs, nowMs).padStart(8)} ${event.text}`, { dimColor: true }))++ rows.push(rule(ctx, 'Logs', state.drill.logs === null ? 'asking `ruflo agent logs`…' : `ruflo agent logs, ${ago(state.drill.logsAtMs, nowMs)}`))++ for (const line of (state.drill.logs ?? []).slice(-8)) rows.push(text(ctx, line, { dimColor: true }))+ if (state.drill.logs !== null && state.drill.logs.length === 0) rows.push(text(ctx, 'no log lines', { dimColor: true }))++ if (ctx.columns >= 44) {+ rows.push(+ row(ctx, [+ button(ctx, 'back', 'Back', ctx.act.back, { hotkey: 'b' }),+ button(ctx, 'agent-prev', 'prev agent', () => ctx.act.select(-1), { hotkey: 'k' }),+ button(ctx, 'agent-next', 'next agent', () => ctx.act.select(1), { hotkey: 'j' }),+ button(ctx, 'actions', 'Actions', () => ctx.act.palette('selection'), { hotkey: 'x' }),+ ]),+ )+ }++ return col(ctx, rows, 'agent')+}diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.tsindex eb1707e7ed..bed3a472c1 100644--- a/plugins/ruflo-console/hooks/views/bar.ts+++ b/plugins/ruflo-console/hooks/views/bar.ts@@ -34,7 +34,7 @@ export function barText(state: State): string {export function barView(kit: Kit, state: State, columns: number, mark: RenderElement | null, onOpen: () => void): RenderElement {const words = barText(state)- const room = Math.max(8, columns - 14)+ const room = Math.max(8, columns - (state.pane.isOpen ? 14 : 30))return kit.Box({flexDirection: 'row',@@ -42,6 +42,7 @@ export function barView(kit: Kit, state: State, columns: number, mark: RenderEle...(mark !== null ? [mark] : [kit.Text({ color: 'claude', children: '◆ ' })]),kit.Text({ wrap: 'truncate-end', ...(state.snapshot?.plugins.missingFromClone.length ? { color: 'warning' } : { dimColor: true }), children: clip(words, room) }),kit.Text({ children: ' ' }),+ ...(state.pane.isOpen ? [] : [kit.Text({ dimColor: true, children: '/ruflo to open ' })]),kit.Button({ key: 'open-console', label: 'console', plain: true, onPress: onOpen }),],})diff --git a/plugins/ruflo-console/hooks/views/claims.ts b/plugins/ruflo-console/hooks/views/claims.tsindex 2760e5e2a2..fed6a546b9 100644--- a/plugins/ruflo-console/hooks/views/claims.ts+++ b/plugins/ruflo-console/hooks/views/claims.ts@@ -25,9 +25,11 @@ export function claimsView(ctx: Ctx): RenderElement {if (claims.length === 0) {rows.push(text(ctx, snap.reads.claims === 'too-large' ? 'claims.json is too large to read here' : 'No claims on disk (.claude-flow/claims/claims.json).', { dimColor: true }))+ if (snap.tasks.length > 0) rows.push(picture(ctx, 'flow', `${snap.tasks.length} open tasks`))} else {- rows.push(picture(ctx, 'claims', `${claims.length} claims`))- rows.push(text(ctx, 'bars: TTL left where expiresAt is set, else age (24 h scale); no claims tool sets a TTL today', { dimColor: true }))+ rows.push(picture(ctx, 'flow', `${claims.length} claims`))+ rows.push(text(ctx, 'lanes: open → claimed → working → done, and stealable · ╰─▶ a pending handoff', { dimColor: true }))+ rows.push(text(ctx, 'ring: TTL left where expiresAt is set, else age filling over 24 h (no claims tool sets a TTL today)', { dimColor: true }))claims.slice(0, 10).forEach(claim => {const isPicked = pick.claim?.issueId === claim.issueId@@ -55,8 +57,8 @@ export function claimsView(ctx: Ctx): RenderElement {if (ctx.columns >= 44) {rows.push(row(ctx, [- button(ctx, 'claim-prev', 'prev', ctx.act.claimPrev, { hotkey: 'j' }),- button(ctx, 'claim-next', 'next', ctx.act.claimNext, { hotkey: 'k' }),+ button(ctx, 'claim-prev', 'prev', () => ctx.act.select(-1), { hotkey: 'k' }),+ button(ctx, 'claim-next', 'next', () => ctx.act.select(1), { hotkey: 'j' }),button(ctx, 'agent-next', 'agent', ctx.act.agentNext, { hotkey: 'a' }),button(ctx, 'task-next', 'task', ctx.act.taskNext, { hotkey: 't' }),]),diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.tsindex e2e8c8996b..1e5c0fd5fa 100644--- a/plugins/ruflo-console/hooks/views/common.ts+++ b/plugins/ruflo-console/hooks/views/common.ts@@ -5,11 +5,11 @@*/import type { Elements, RenderChildren, RenderElement } from 'claude-code'-import type { ProbeResult, ViewId } from '../data/cli'+import type { ProbeResult } from '../data/cli'import type { Grid } from '../gfx/raster'-import type { State } from '../state'+import type { State, ViewId } from '../state'-export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Raster?: Elements['terminal']['Raster'] }+export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Raster?: Elements['terminal']['Raster']; Input?: Elements['terminal']['Input'] }/** What a button can ask for: every one a closure over the controller. */export type Actions = {@@ -17,16 +17,26 @@ export type Actions = {refresh: () => voidhelp: () => voidclose: () => void+ back: () => voidconfirm: () => voidcancel: () => void- claimPrev: () => void- claimNext: () => void+ /** j/k: moves the selection of the view in front. */+ select: (by: number) => voidagentNext: () => voidtaskNext: () => void+ /** Drills into the selected agent. */+ drill: () => voidclaim: () => voidrelease: () => voidhandoff: () => voidsteal: () => void+ palette: (context: 'all' | 'selection') => void+ paletteQuery: (text: string) => void+ paletteRun: (id: string) => void+ paletteSubmit: () => void+ run: (id: string, text?: string) => boolean+ /** Cycles the events view's filter. */+ filter: () => void}export type Ctx = {diff --git a/plugins/ruflo-console/hooks/views/cost.ts b/plugins/ruflo-console/hooks/views/cost.tsnew file mode 100644index 0000000000..0424abe55a--- /dev/null+++ b/plugins/ruflo-console/hooks/views/cost.ts@@ -0,0 +1,42 @@+import type { RenderElement } from 'claude-code'++import { col, kv, pct, picture, rule, text, THEME, type Ctx } from './common'++const LADDER = [0.5, 0.75, 0.9, 1] as const++/** The budget ladder as a text bar: marks at 50/75/90/100% of the limit, the spend filled to where it stands. */+export function ladder(usd: number, limit: number, width: number): string {+ const cells = Math.max(10, width)+ const at = Math.min(cells, Math.round((usd / limit) * cells))+ const marks = new Set(LADDER.map(step => Math.min(cells - 1, Math.round(step * cells) - 1)))++ return Array.from({ length: cells }, (_, i) => (marks.has(i) ? '│' : i < at ? '█' : '·')).join('')+}++/** This session's spend from Claude Code, against the ruflo-mods budget ladder where one is set, and its burn since load. */+export function costView(ctx: Ctx): RenderElement {+ const { state } = ctx+ const budget = state.ruflo.snapshot?.budget+ const spend = state.usage?.costUsd+ const rows: RenderElement[] = [rule(ctx, 'Cost', 'this session')]++ rows.push(picture(ctx, 'gauge', budget === undefined ? 'no budget set' : `$${(budget.usd ?? spend ?? 0).toFixed(2)} of $${budget.limit.toFixed(2)}`))+ rows.push(kv(ctx, 'session spend', spend === undefined ? 'n/a — Claude Code did not report a cost' : `$${spend.toFixed(3)}`))+ rows.push(kv(ctx, 'context', state.usage?.contextPercent === undefined ? 'n/a' : `${Math.round(state.usage.contextPercent)}% of the window`))++ if (budget === undefined) {+ rows.push(kv(ctx, 'budget', state.ruflo.snapshot === null ? 'n/a — ruflo-mods not seated' : 'none set (ruflo-mods costBudgetUsd = 0)'))+ } else {+ const used = budget.usd ?? spend+ const color = budget.level === 'OK' || budget.level === 'INFO' ? THEME.ok : budget.level === 'WARNING' ? THEME.warn : THEME.bad++ rows.push(kv(ctx, 'budget', `${budget.level} · ${used === undefined ? 'n/a' : `$${used.toFixed(2)}`} of $${budget.limit.toFixed(2)} (${used === undefined ? 'n/a' : pct(used / budget.limit)})`, color))+ if (used !== undefined) rows.push(text(ctx, `${' '.repeat(17)}${ladder(used, budget.limit, Math.min(40, ctx.columns - 20))} 50·75·90·100%`, { color }))+ }++ rows.push(rule(ctx, 'Burn', `${state.history.spend.length} samples since the console loaded`))+ rows.push(picture(ctx, 'burn', `spend since load: ${state.history.spend.map(sample => `$${sample.value.toFixed(2)}`).join(' ') || 'n/a'}`))+ rows.push(text(ctx, 'gauge: needle at spend / limit, arc green to 50%, amber to 90%, red past · burn: each change of spend Claude Code reported', { dimColor: true }))++ return col(ctx, rows, 'cost')+}diff --git a/plugins/ruflo-console/hooks/views/federation.ts b/plugins/ruflo-console/hooks/views/federation.tsindex 37940e4dbf..32e6b1b129 100644--- a/plugins/ruflo-console/hooks/views/federation.ts+++ b/plugins/ruflo-console/hooks/views/federation.ts@@ -1,7 +1,7 @@import type { RenderElement } from 'claude-code'import type { Channels, Peers, Roster } from '../data/cli'-import { ago, col, kv, live, rule, sourceLine, text, THEME, type Ctx } from './common'+import { ago, col, kv, live, picture, rule, sourceLine, text, THEME, type Ctx } from './common'/*** This node's federation standing from local state and local CLI answers only. The roster lives on the public relay,@@ -14,7 +14,11 @@ export function federationView(ctx: Ctx): RenderElement {const channels = live<Channels>(state.probes.get('channels'))const roster = live<Roster>(state.probes.get('roster'))const nodes = snap?.federationNodes ?? null- const rows: RenderElement[] = [rule(ctx, 'This node', 'local only')]+ const rows: RenderElement[] = [rule(ctx, 'Map', 'this node · peers · keys · channels · roster')]++ rows.push(picture(ctx, 'fedmap', 'map needs a terminal'))+ rows.push(text(ctx, '● pinned peer (solid) · own key (solid) · channel (dashed) · ○ roster member (sparse, unvetted) · a dot runs an edge for 2 s after a sync', { dimColor: true }))+ rows.push(rule(ctx, 'This node', 'local only'))rows.push(kv(diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.tsindex fd47ff858e..a82a2847f3 100644--- a/plugins/ruflo-console/hooks/views/frames.ts+++ b/plugins/ruflo-console/hooks/views/frames.ts@@ -1,94 +1,189 @@/*** The pictures of the view in front, by Raster key, for one instant. The render mounts them and the animation loop- * blits them, both through `picturesOf`, so a frame is always the mounted size.+ * blits them, both through `picturesOf`, so a frame is always the mounted size. Each picture's model is read from the+ * state here; the drawing itself is in ../gfx.*/-import type { HarnessScore } from '../data/cli'+import type { AuditTrend, HarnessScore, Intelligence } from '../data/cli'+import { recentByAgent } from '../data/events'import type { Snapshot } from '../data/snapshot'-import { activityPicture, claimsPicture, curvePicture, scorePicture, topologyPicture, type ClaimBar, type TopoModel } from '../gfx/pictures'+import type { Channels, Peers, Roster } from '../data/cli'+import { pipelinePicture, radarPicture, samplesPicture, trendPicture, gaugePicture, type Stage } from '../gfx/charts'+import { flowModelOf, flowPicture, flowRows } from '../gfx/flow'+import { federationPicture, ganttPicture, heatmapPicture, type FedNode, type HealthRow, type Lane } from '../gfx/maps'+import { activityPicture, curvePicture, headerPicture, PULSE_MS, topologyPicture, type TopoModel } from '../gfx/pictures'import type { Grid } from '../gfx/raster'+import { severityOf } from '../data/cli'+import { EXPECTED_IN_MARKET, RUFLO_MARKET } from '../data/snapshot'import type { State } from '../state'import { live } from './common'+import { openTasks } from './select'-export const MAX_NODES = 12-export const MAX_CLAIM_BARS = 8+export const MAX_NODES = 100+export const HEALTH_CHECKS = ['installed', 'enabled', 'in clone', 'mod'] as const+const TIMELINE_MS = 15 * 60_000/** The swarm as a graph: the hive's queen leads where there is one, else the swarm itself stands at the root. */-export function topoModelOf(snapshot: Snapshot | null): TopoModel | null {+export function topoModelOf(snapshot: Snapshot | null, pulses: Map<string, number> = new Map()): TopoModel | null {const swarm = snapshot?.swarm ?? null- if (snapshot === null || (swarm === null && snapshot.hive === null && snapshot.agents.length === 0)) {- return null- }+ if (snapshot === null || (swarm === null && snapshot.hive === null && snapshot.agents.length === 0)) return nullconst members = swarm !== null && swarm.agentIds.length > 0 ? snapshot.agents.filter(agent => swarm.agentIds.includes(agent.id)) : snapshot.agents- const leader = snapshot.hive?.queen !== undefined ? { id: snapshot.hive.queen, label: 'queen', status: 'leader', isLeader: true } : { id: swarm?.id ?? 'swarm', label: 'swarm', status: swarm?.status ?? 'unknown', isLeader: true }+ const leaderId = snapshot.hive?.queen ?? swarm?.id ?? 'swarm'+ const leaderPulse = pulses.get(leaderId)return {topology: swarm?.topology ?? snapshot.hive?.topology ?? 'hierarchical',- nodes: [leader, ...members.slice(0, MAX_NODES - 1).map(agent => ({ id: agent.id, label: agent.name ?? agent.type, status: agent.status, isLeader: false }))],+ nodes: [+ { id: leaderId, label: snapshot.hive?.queen !== undefined ? 'queen' : 'swarm', status: snapshot.hive?.queen !== undefined ? 'leader' : (swarm?.status ?? 'unknown'), isLeader: true, ...(leaderPulse !== undefined && { pulseAtMs: leaderPulse }) },+ ...members.slice(0, MAX_NODES - 1).map(agent => {+ const pulseAtMs = pulses.get(agent.id)++ return { id: agent.id, label: agent.name ?? agent.type, status: agent.status, isLeader: false, ...(pulseAtMs !== undefined && { pulseAtMs }) }+ }),+ ],}}-export function claimBarsOf(snapshot: Snapshot | null): ClaimBar[] {- return (snapshot?.claims ?? []).slice(0, MAX_CLAIM_BARS).map(claim => ({- label: claim.issueId,- isStealable: claim.isStealable,- ...(claim.claimedAtMs !== undefined && { claimedAtMs: claim.claimedAtMs }),- ...(claim.expiresAtMs !== undefined && { expiresAtMs: claim.expiresAtMs }),- ...(claim.progress !== undefined && { progress: claim.progress }),+/** Rows the topology graph takes: enough for a tree, more for a wide swarm or a circle. */+export const topologyRows = (columns: number, nodes: number): number => Math.min(24, Math.max(columns >= 90 ? 12 : 10, 8 + Math.ceil(nodes / Math.max(1, Math.floor(columns / 5))) * 3))++/** Each learning stage's count and source; null where nothing measures it. */+export function stagesOf(state: State): Stage[] {+ const snap = state.snapshot+ const intel = live<Intelligence>(state.probes.get('intelligence'))++ return [+ { name: 'RETRIEVE', count: snap?.neural?.trajectories ?? null, source: 'trajectories (neural/stats.json)' },+ { name: 'JUDGE', count: snap?.outcomes?.total ?? null, source: 'routed outcomes judged (routing-outcomes.json)' },+ { name: 'DISTILL', count: snap?.neural?.patterns ?? null, source: 'patterns learned (neural/stats.json)' },+ { name: 'CONSOLIDATE', count: intel?.ewcConsolidations ?? null, source: 'EWC consolidations (hooks_intelligence_stats)' },+ ]+}++/** Peers, own keys, channels and (when asked for) roster members, each with its trust. */+export function fedNodesOf(state: State): FedNode[] {+ const peers = live<Peers>(state.probes.get('peers'))?.peers ?? []+ const channels = live<Channels>(state.probes.get('channels'))?.channels ?? []+ const roster = state.options.federationNetwork ? (live<Roster>(state.probes.get('roster'))?.members ?? []) : []++ return [+ ...peers.map(peer => ({ label: peer.id, trust: 'pinned' as const, ...(peer.lastSyncMs !== undefined && { trafficAtMs: peer.lastSyncMs }) })),+ ...(state.snapshot?.federationNodes ?? []).map(node => ({ label: node, trust: 'key' as const })),+ ...channels.map(channel => ({ label: channel.name ?? channel.id, trust: 'channel' as const, ...(channel.atMs !== undefined && { trafficAtMs: channel.atMs }) })),+ ...roster.map(member => ({ label: member.name, trust: 'roster' as const })),+ ]+}++/** One row per ruflo plugin installed or offered: installed, enabled, in the clone, and (for mods) loaded here. */+export function healthRowsOf(state: State): HealthRow[] {+ const facts = state.snapshot?.plugins+ const installed = new Map((facts?.installed ?? []).filter(plugin => plugin.marketplace === RUFLO_MARKET).map(plugin => [plugin.name, plugin]))+ const names = [...new Set([...installed.keys(), ...(facts?.rufloOffered ?? []), ...EXPECTED_IN_MARKET])].sort()+ const mods: Record<string, boolean | null> = { 'ruflo-console': true, 'ruflo-mods': state.ruflo.snapshot !== null }++ return names.map(name => ({+ name: name.replace(/^ruflo-/, ''),+ cells: [installed.has(name), facts?.enabled.has(`${name}@${RUFLO_MARKET}`) ?? null, facts?.rufloOffered === null || facts === undefined ? null : facts.rufloOffered.includes(name), name in mods ? (mods[name] ?? null) : null],}))}-/** Running success of routed outcomes, oldest first. */-export const curvePointsOf = (snapshot: Snapshot | null): boolean[] => (snapshot?.outcomes?.points ?? []).map(point => point.ok)+/** The timeline's lanes over the last 15 minutes: ruflo agents' observed statuses and Claude Code's tool calls. */+export function lanesOf(state: State, nowMs: number): Lane[] {+ const from = nowMs - TIMELINE_MS+ const agents = (state.snapshot?.agents ?? []).slice(0, 24).map(agent => {+ const log = state.statusLog.get(agent.id) ?? []-/** Rows the topology graph takes at a width: enough for a tree, more for a circle. */-export const topologyRows = (columns: number): number => (columns >= 90 ? 12 : 10)+ return {+ label: agent.name ?? agent.type,+ spans: log.map((entry, i) => ({ fromMs: Math.max(from, entry.atMs), toMs: log[i + 1]?.atMs ?? nowMs, busy: /busy|active|working/i.test(entry.status) })).filter(span => span.toMs >= from),+ ticks: [],+ }+ })+ const claude = [...state.toolsByAgent].slice(0, 6).map(([who, calls]) => ({ label: who === 'main' ? 'claude (main)' : `cc ${who.slice(-6)}`, spans: [], ticks: calls.map(call => call.atMs).filter(at => at >= from) }))-/** When the score on screen was first drawn: the fill animates from there. Module-held, reset by a new value. */+ return [...claude, ...agents]+}++/** When the score on screen was first drawn: the radar grows from there. Module-held, reset by a new value. */const scoreShown = new WeakMap<object, number>()export function picturesOf(state: State, columns: number, nowMs: number, t: number): Map<string, Grid> {const pictures = new Map<string, Grid>()- const width = Math.max(20, Math.min(160, columns))+ const width = Math.max(20, Math.min(200, columns))const snapshot = state.snapshot+ pictures.set('header', headerPicture(`◆ ruflo · ${state.cwd.split('/').filter(Boolean).at(-1) ?? ''}`, Math.min(width, 40), t))+switch (state.view) {case 'overview':- pictures.set(- 'activity',- activityPicture(- [- { label: 'tool calls/5s', values: state.activity },- { label: 'state writes', values: state.writes },- ],- width,- t,- ),- )+ pictures.set('activity', activityPicture([{ label: 'tool calls/5s', values: state.activity }, { label: 'state writes', values: state.writes }], width, t))breakcase 'swarm': {- const model = topoModelOf(snapshot)+ const model = topoModelOf(snapshot, recentByAgent(state.events, nowMs, PULSE_MS + 600))- if (model !== null) pictures.set('topology', topologyPicture(model, width, topologyRows(width), t))+ if (model !== null) pictures.set('topology', topologyPicture(model, width, topologyRows(width, model.nodes.length), t))break}case 'claims': {- const bars = claimBarsOf(snapshot)+ const cards = flowModelOf(snapshot?.claims ?? [], openTasks(state))- if (bars.length > 0) pictures.set('claims', claimsPicture(bars, width, bars.length, nowMs))+ if (cards.length > 0) pictures.set('flow', flowPicture(cards, width, flowRows(cards), nowMs))break}- case 'learning':- pictures.set('curve', curvePicture(curvePointsOf(snapshot), width, 6, t))+ case 'federation':+ pictures.set('fedmap', federationPicture(snapshot?.hasNostrKey === true ? 'this node' : 'this node (no key)', fedNodesOf(state), width, 11, t))break+ case 'plugins': {+ const rows = healthRowsOf(state)++ pictures.set('health', heatmapPicture(rows, HEALTH_CHECKS, width, Math.min(26, Math.ceil(rows.length / 2) + 1)))+ break+ }+ case 'learning': {+ const stages = stagesOf(state)++ pictures.set('curve', curvePicture((snapshot?.outcomes?.points ?? []).map(point => point.ok), width, 6, t, state.curveGrewAtMs))+ pictures.set('pipeline', pipelinePicture(stages, width, t, stages.map((_, i) => (i === 2 ? (state.history.patterns.at(-1)?.atMs ?? null) : i === 1 ? state.curveGrewAtMs || null : null))))+ pictures.set('patterns', samplesPicture('patterns since load', state.history.patterns, width))+ break+ }case 'metaharness': {const score = live<HarnessScore>(state.probes.get('metaharness'))+ const audits = live<AuditTrend>(state.probes.get('audits'))if (score !== null) {if (!scoreShown.has(score)) scoreShown.set(score, t)- pictures.set('score', scorePicture(score.dims, width, t, scoreShown.get(score) ?? t))+ pictures.set('radar', radarPicture(score.dims, width, 13, t, scoreShown.get(score) ?? t))}++ pictures.set(+ 'trend',+ trendPicture(+ (audits?.points ?? []).flatMap(point => {+ const level = severityOf(point.worst)++ return level === null ? [] : [level]+ }),+ width,+ 4,+ 4,+ { top: 'critical', bottom: 'clean', empty: audits === null ? 'audit trend: n/a' : `${audits.total} stored audits: a trend needs two` },+ ),+ )+ break+ }+ case 'cost': {+ const budget = state.ruflo.snapshot?.budget++ pictures.set('gauge', gaugePicture(budget?.usd ?? state.usage?.costUsd ?? null, budget?.limit ?? null, Math.min(width, 60), 9))+ pictures.set('burn', samplesPicture('spend since load', state.history.spend, width))+ break+ }+ case 'timeline': {+ const lanes = lanesOf(state, nowMs)++ if (lanes.length > 0) pictures.set('gantt', ganttPicture(lanes, width, nowMs - TIMELINE_MS, nowMs, nowMs))break}default:diff --git a/plugins/ruflo-console/hooks/views/learning.ts b/plugins/ruflo-console/hooks/views/learning.tsindex dac4d52bca..07d1eefb57 100644--- a/plugins/ruflo-console/hooks/views/learning.ts+++ b/plugins/ruflo-console/hooks/views/learning.ts@@ -2,6 +2,7 @@ import type { RenderElement } from 'claude-code'import type { Intelligence } from '../data/cli'import { ago, col, count, kv, live, pct, picture, rule, sourceLine, text, THEME, type Ctx } from './common'+import { stagesOf } from './frames'/*** What ruflo has learned, from its own stores: the router's last pick and how routed tasks turned out, the model tier@@ -39,7 +40,7 @@ export function learningView(ctx: Ctx): RenderElement {),)rows.push(picture(ctx, 'curve', `running success rate over ${outcomes?.total ?? 0} outcomes`))- rows.push(text(ctx, 'running success rate of routed tasks, oldest left; the moving dot is decoration', { dimColor: true }))+ rows.push(text(ctx, 'running success rate of routed tasks, oldest left (router accuracy over N outcomes); new outcomes draw in', { dimColor: true }))rows.push(kv(ctx,@@ -50,6 +51,10 @@ export function learningView(ctx: Ctx): RenderElement {),)+ rows.push(rule(ctx, 'Pipeline', 'RETRIEVE → JUDGE → DISTILL → CONSOLIDATE'))+ rows.push(picture(ctx, 'pipeline', stagesOf(state).map(stage => `${stage.name} ${stage.count ?? 'n/a'}`).join(' → ')))+ for (const stage of stagesOf(state)) rows.push(text(ctx, ` ${stage.name.toLowerCase()}: ${stage.source}`, { dimColor: true }))+ rows.push(picture(ctx, 'patterns', `patterns since load: ${state.history.patterns.map(sample => sample.value).join(' ') || 'n/a'}`))rows.push(rule(ctx, 'SONA · ReasoningBank', 'neural/stats.json'))rows.push(kv(ctx, 'trajectories', neural === null ? 'n/a — no .claude-flow/neural/stats.json' : count(neural.trajectories)))rows.push(kv(ctx, 'patterns learned', neural === null ? 'n/a' : count(neural.patterns)))diff --git a/plugins/ruflo-console/hooks/views/manage.ts b/plugins/ruflo-console/hooks/views/manage.tsnew file mode 100644index 0000000000..0ca762468a--- /dev/null+++ b/plugins/ruflo-console/hooks/views/manage.ts@@ -0,0 +1,65 @@+/**+ * The management views: the agent timeline, the approvals queue and the event stream. Each acts through the palette's+ * entries (by id), so a button here runs exactly what the palette or `/ruflo run <id>` would.+ */+import type { RenderElement } from 'claude-code'++import { approvalsOf } from '../data/alerts'+import { ago, button, clip, col, picture, row, rule, text, THEME, type Ctx } from './common'++export function timelineView(ctx: Ctx): RenderElement {+ const agents = ctx.state.snapshot?.agents.length ?? 0+ const rows: RenderElement[] = [rule(ctx, 'Timeline', 'last 15 minutes · observed since the console loaded')]++ rows.push(picture(ctx, 'gantt', agents === 0 && ctx.state.toolsByAgent.size === 0 ? 'no agents and no tool calls seen yet' : `${agents} agents`))+ rows.push(text(ctx, '█ busy · ▁ idle (ruflo agent status, as each read saw it) · ▮ a tool call Claude Code made (main session and subagents)', { dimColor: true }))+ rows.push(text(ctx, "ruflo agents' own tool calls are not visible to Claude Code: their rows show status only", { dimColor: true }))++ return col(ctx, rows, 'timeline')+}++export function approvalsView(ctx: Ctx): RenderElement {+ const items = approvalsOf(ctx.state)+ const picked = items.length === 0 ? -1 : ((ctx.state.select.item % items.length) + items.length) % items.length+ const rows: RenderElement[] = [rule(ctx, 'Approvals', items.length === 0 ? 'nothing waiting' : `${items.length} waiting · j/k pick`)]++ if (items.length === 0) {+ rows.push(text(ctx, 'No hive-mind proposals, stealable claims, refused mods, permission denies or budget alerts waiting.', { dimColor: true }))+ }++ items.slice(0, 12).forEach((item, i) => {+ const isPicked = i === picked++ rows.push(text(ctx, `${isPicked ? '▸' : ' '} [${item.kind}] ${item.text}`, isPicked ? { bold: true, color: THEME.head } : { color: item.kind === 'policy-deny' || item.kind === 'mod-trust' ? THEME.bad : THEME.warn }))+ rows.push(text(ctx, ` ${item.detail}`, { dimColor: true }))++ if (isPicked && item.actions.length > 0 && ctx.columns >= 44) {+ rows.push(row(ctx, item.actions.map((action, a) => button(ctx, `approve-${a}`, action.label, () => void ctx.act.run(action.paletteId), a < 2 ? { hotkey: a === 0 ? 'v' : 'w' } : {}))))+ }+ })++ if (ctx.columns >= 44 && items.length > 1) rows.push(row(ctx, [button(ctx, 'item-prev', 'prev', () => ctx.act.select(-1), { hotkey: 'k' }), button(ctx, 'item-next', 'next', () => ctx.act.select(1), { hotkey: 'j' })]))++ rows.push(text(ctx, 'each action asks y/n before it runs; a permission deny is shown, never loosened from here', { dimColor: true }))++ return col(ctx, rows, 'approvals')+}++const KIND_COLOR: Record<string, string> = { swarm: THEME.info, claims: THEME.warn, federation: THEME.ok, learning: THEME.head, tools: THEME.info, mods: THEME.bad }++export function eventsView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const filter = state.eventFilter+ const shown = state.events.filter(event => filter === 'all' || event.kind === filter)+ const rows: RenderElement[] = [rule(ctx, 'Events', `${shown.length} · filter ${filter} (f)`)]++ if (shown.length === 0) rows.push(text(ctx, state.events.length === 0 ? 'Nothing has changed since the console loaded. Events are what changed between reads, and what this session did.' : `no ${filter} events`, { dimColor: true }))++ for (const event of shown.slice(-18).reverse()) {+ rows.push(row(ctx, [ctx.kit.Text({ dimColor: true, children: `${ago(event.atMs, nowMs).padStart(8)} ` }), ctx.kit.Text({ color: KIND_COLOR[event.kind] ?? THEME.info, children: `${event.kind.padEnd(10)} ` }), ctx.kit.Text({ wrap: 'truncate-end', children: clip(event.text, Math.max(10, ctx.columns - 21)) })]))+ }++ if (ctx.columns >= 44) rows.push(row(ctx, [button(ctx, 'filter', `Filter: ${filter}`, ctx.act.filter, { hotkey: 'f' })]))++ return col(ctx, rows, 'events')+}diff --git a/plugins/ruflo-console/hooks/views/memory.ts b/plugins/ruflo-console/hooks/views/memory.tsindex d237f3e148..ec40d48ce0 100644--- a/plugins/ruflo-console/hooks/views/memory.ts+++ b/plugins/ruflo-console/hooks/views/memory.ts@@ -1,26 +1,13 @@import type { RenderElement } from 'claude-code'import type { MemoryStats, Namespaces } from '../data/cli'-import { ago, col, count, kv, live, pct, rule, sourceLine, text, THEME, type Ctx } from './common'+import { ago, col, count, kv, live, rule, sourceLine, text, type Ctx } from './common'-const LADDER = [0.5, 0.75, 0.9, 1] as const--/** The budget ladder as a text bar: marks at 50/75/90/100% of the limit, the spend filled to where it stands. */-export function ladder(usd: number, limit: number, width: number): string {- const cells = Math.max(10, width)- const at = Math.min(cells, Math.round((usd / limit) * cells))- const marks = new Set(LADDER.map(step => Math.min(cells - 1, Math.round(step * cells) - 1)))-- return Array.from({ length: cells }, (_, i) => (marks.has(i) ? '│' : i < at ? '█' : '·')).join('')-}--/** AgentDB counts and namespaces from the ruflo CLI, and this session's spend against the ruflo-mods budget ladder. */+/** AgentDB counts and namespaces from the ruflo CLI. */export function memoryView(ctx: Ctx): RenderElement {const { state, nowMs } = ctxconst memory = live<MemoryStats>(state.probes.get('memory'))const spaces = live<Namespaces>(state.probes.get('namespaces'))- const budget = state.ruflo.snapshot?.budget- const spend = state.usage?.costUsdconst rows: RenderElement[] = [rule(ctx, 'AgentDB', memory?.backend ?? '')]if (memory === null) {@@ -48,20 +35,7 @@ export function memoryView(ctx: Ctx): RenderElement {rows.push(text(ctx, 'a sample: counts over the newest entries `memory list` returns, not the whole store', { dimColor: true }))}- rows.push(rule(ctx, 'Cost', 'this session'))- rows.push(kv(ctx, 'session spend', spend === undefined ? 'n/a — Claude Code did not report a cost' : `$${spend.toFixed(3)}`))- rows.push(kv(ctx, 'context', state.usage?.contextPercent === undefined ? 'n/a' : `${Math.round(state.usage.contextPercent)}% of the window`))-- if (budget === undefined) {- rows.push(kv(ctx, 'budget', state.ruflo.snapshot === null ? 'n/a — ruflo-mods not seated' : 'none set (ruflo-mods costBudgetUsd = 0)'))- } else {- const used = budget.usd ?? spend- const color = budget.level === 'OK' || budget.level === 'INFO' ? THEME.ok : budget.level === 'WARNING' ? THEME.warn : THEME.bad-- rows.push(kv(ctx, 'budget', `${budget.level} · ${used === undefined ? 'n/a' : `$${used.toFixed(2)}`} of $${budget.limit.toFixed(2)} (${used === undefined ? 'n/a' : pct(used / budget.limit)})`, color))-- if (used !== undefined) rows.push(text(ctx, `${' '.repeat(17)}${ladder(used, budget.limit, Math.min(40, ctx.columns - 20))} 50·75·90·100%`, { color }))- }+ rows.push(text(ctx, 'spend, budget gauge and burn: Cost (9)', { dimColor: true }))return col(ctx, rows, 'memory')}diff --git a/plugins/ruflo-console/hooks/views/metaharness.ts b/plugins/ruflo-console/hooks/views/metaharness.tsindex 6dcc20596c..604f2e87ba 100644--- a/plugins/ruflo-console/hooks/views/metaharness.ts+++ b/plugins/ruflo-console/hooks/views/metaharness.ts@@ -19,7 +19,7 @@ export function metaharnessView(ctx: Ctx): RenderElement {rows.push(text(ctx, state.probes.get('metaharness')?.error !== null && state.probes.get('metaharness')?.error !== undefined ? `${line.text} — optional (ADR-150), the console works without it` : line.text, { dimColor: true }))} else {- rows.push(picture(ctx, 'score', score.dims.map(dim => `${dim.name} ${dim.value}`).join(' · ')))+ rows.push(picture(ctx, 'radar', score.dims.map(dim => `${dim.name} ${dim.value}`).join(' · ')))rows.push(kv(ctx,@@ -27,7 +27,7 @@ export function metaharnessView(ctx: Ctx): RenderElement {`${score.costUsd === undefined ? 'n/a' : `$${score.costUsd.toFixed(3)}`} · hard constraints ${score.constraints ?? 'n/a'} · scaffold ${score.scaffoldReady === undefined ? 'n/a' : score.scaffoldReady ? 'ready' : 'not ready'} · scored ${ago(score.atMs, nowMs)}`,),)- rows.push(text(ctx, 'static readiness heuristics from `metaharness score`, 0-100 per dimension; the fill is decoration', { dimColor: true }))+ rows.push(text(ctx, 'static readiness heuristics from `metaharness score`, 0-100 per axis; the radar growing in is decoration', { dimColor: true }))}rows.push(rule(ctx, 'Flywheel', 'receipts ledger'))@@ -43,7 +43,9 @@ export function metaharnessView(ctx: Ctx): RenderElement {}rows.push(kv(ctx, 'active policy', policy === null ? 'n/a — no .claude-flow/harness-active-policy.json' : `${policy.champion.slice(0, 22)}… · ${policy.tier ?? 'n/a'} · ${policy.layer ?? 'n/a'} · applied ${ago(policy.appliedAtMs, nowMs)}`))- rows.push(text(ctx, 'audit trend: not polled (it needs two stored audits) — `npx ruflo metaharness audit-trend`', { dimColor: true }))+ rows.push(rule(ctx, 'Audit trend', 'worst severity per stored audit'))+ rows.push(picture(ctx, 'trend', 'audit trend needs a terminal'))+ rows.push(text(ctx, 'from `metaharness audit-list` (memory namespace metaharness-audit) · p → "run a MetaHarness audit" adds one', { dimColor: true }))return col(ctx, rows, 'metaharness')}diff --git a/plugins/ruflo-console/hooks/views/overview.ts b/plugins/ruflo-console/hooks/views/overview.tsindex 769c7c8b77..92e3da61e9 100644--- a/plugins/ruflo-console/hooks/views/overview.ts+++ b/plugins/ruflo-console/hooks/views/overview.ts@@ -1,5 +1,6 @@import type { RenderElement } from 'claude-code'+import { alertsOf } from '../data/alerts'import type { MemoryStats } from '../data/cli'import { ago, col, count, kv, live, picture, rule, sourceLine, text, THEME, type Ctx } from './common'@@ -68,6 +69,16 @@ export function overviewView(ctx: Ctx): RenderElement {rows.push(kv(ctx, 'function hooks', `on (this mod runs) · mods seen since it loaded: ${loaded} loaded, ${refused} refused`, refused > 0 ? THEME.warn : THEME.ok))rows.push(kv(ctx, 'swarm', swarm === null ? 'n/a — no swarm on disk' : `${swarm.id} · ${swarm.topology} · ${swarm.status} · ${swarm.agentIds.length || (snap?.agents.length ?? 0)} agents`))+ const alerts = alertsOf(state, nowMs, state.loadedAtMs)++ rows.push(rule(ctx, 'Health', alerts.length === 0 ? 'no alerts' : `${alerts.length} alert${alerts.length === 1 ? '' : 's'}`))++ for (const alert of alerts.slice(0, 5)) {+ rows.push(text(ctx, `${alert.level === 'bad' ? '✖' : alert.level === 'warn' ? '▲' : '●'} ${alert.text} — ${alert.fix}`, { color: alert.level === 'bad' ? THEME.bad : alert.level === 'warn' ? THEME.warn : THEME.info }))+ }++ if (alerts.length > 5) rows.push(text(ctx, `+${alerts.length - 5} more · approvals (q) lists what needs a decision`, { dimColor: true }))+rows.push(rule(ctx, 'Activity', 'measured'))rows.push(picture(ctx, 'activity', `tool calls/5s: ${state.activity.slice(-12).join(' ') || 'none yet'}`))rows.push(text(ctx, 'tool calls the console saw (5 s buckets) and ruflo files changed between reads; the glow is decoration', { dimColor: true }))diff --git a/plugins/ruflo-console/hooks/views/palette.ts b/plugins/ruflo-console/hooks/views/palette.tsnew file mode 100644index 0000000000..7d750e608c--- /dev/null+++ b/plugins/ruflo-console/hooks/views/palette.ts@@ -0,0 +1,55 @@+import type { RenderElement } from 'claude-code'++import { filterPalette, paletteEntries } from '../palette'+import { button, col, row, rule, text, THEME, type Ctx } from './common'++export const PALETTE_ROWS = 12++/**+ * The command palette over the view: a text field (typing filters, Enter runs the best match) and the matches as+ * buttons. `x` opens it scoped to the selection's actions. While it is open the view's own buttons are not drawn, so+ * Tab and the arrows walk the matches.+ */+export function paletteView(ctx: Ctx): RenderElement {+ const { state } = ctx+ const all = paletteEntries(state, ctx.nowMs)+ const matches = filterPalette(all, state.palette.query, state.palette.context)+ const rows: RenderElement[] = [rule(ctx, state.palette.context === 'selection' ? 'Actions for the selection' : 'Palette', `${matches.length} of ${all.length}`)]++ if (ctx.kit.Input !== undefined) {+ rows.push(+ ctx.kit.Input({+ key: 'palette-input',+ label: '› ',+ placeholder: 'type to filter: spawn, claim, vote, worker, route <words>, store <text>, search <query>…',+ value: state.palette.query,+ submitLabel: 'run best match',+ autoFocus: true,+ onInput: value => ctx.act.paletteQuery(value),+ onSubmit: value => {+ ctx.act.paletteQuery(value)+ ctx.act.paletteSubmit()+ },+ }),+ )+ } else {+ rows.push(text(ctx, 'this surface has no text field: pick an entry below, or use /ruflo run <entry> [text]', { dimColor: true }))+ }++ for (const entry of matches.slice(0, PALETTE_ROWS)) {+ rows.push(+ row(ctx, [+ ctx.kit.Text({ dimColor: true, children: `${entry.group.padEnd(12)}` }),+ ctx.kit.Button({ key: `pal-${entry.id}`, label: entry.label, plain: true, onPress: () => ctx.act.paletteRun(entry.id) }),+ ]),+ )+ }++ if (matches.length > PALETTE_ROWS) rows.push(text(ctx, `+${matches.length - PALETTE_ROWS} more: keep typing`, { dimColor: true }))+ if (matches.length === 0) rows.push(text(ctx, 'no match', { color: THEME.warn }))++ rows.push(row(ctx, [button(ctx, 'palette-close', 'Close palette', () => ctx.act.palette(state.palette.context), { hotkey: state.palette.context === 'selection' ? 'x' : 'p' })]))+ rows.push(text(ctx, 'changes ask y/n before they run · reads (logs, route, search, score) run at once · same entries: /ruflo run <id>', { dimColor: true }))++ return col(ctx, rows, 'palette')+}diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.tsindex 710060d130..6a2faffea0 100644--- a/plugins/ruflo-console/hooks/views/pane.ts+++ b/plugins/ruflo-console/hooks/views/pane.ts@@ -1,23 +1,29 @@/**- * The console pane's frame: the tab row, the view in front, the confirm row, and a footer that says how fresh the data- * is and whether the pane holds the keys. Below NARROW columns the pane is text only, one view at a time.+ * The console pane's frame: a title strip, the tab row, then the palette, the help or the view in front, the confirm+ * row and a footer that says how fresh the data is and whether the pane holds the keys. Below NARROW columns the pane+ * is text only, one view at a time.*/import type { RenderElement } from 'claude-code'-import { VIEWS } from '../state'+import { HELP } from '../commands'+import { VIEWS, type ViewId } from '../state'+import { agentView } from './agent'import { claimsView } from './claims'import { ago, button, clip, col, row, text, THEME, type Ctx } from './common'+import { costView } from './cost'import { federationView } from './federation'import { learningView } from './learning'+import { approvalsView, eventsView, timelineView } from './manage'import { memoryView } from './memory'import { metaharnessView } from './metaharness'import { overviewView } from './overview'+import { paletteView } from './palette'import { pluginsView } from './plugins'import { swarmView } from './swarm'export const NARROW = 44-const BODIES = {+const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {overview: overviewView,swarm: swarmView,claims: claimsView,@@ -26,24 +32,30 @@ const BODIES = {learning: learningView,metaharness: metaharnessView,memory: memoryView,-} as const+ cost: costView,+ timeline: timelineView,+ approvals: approvalsView,+ events: eventsView,+ agent: agentView,+}function tabs(ctx: Ctx): RenderElement {- const isShort = ctx.columns < 100-if (ctx.columns < NARROW) {const index = VIEWS.findIndex(view => view.id === ctx.state.view)+ const label = index < 0 ? 'Agent' : (VIEWS[index]?.label ?? '')- return text(ctx, `${index + 1}/${VIEWS.length} ${VIEWS[index]?.label ?? ''} · 1-8 switch · h help`, { bold: true, color: THEME.head })+ return text(ctx, `${index < 0 ? '·' : `${index + 1}/${VIEWS.length}`} ${label} · /ruflo help`, { bold: true, color: THEME.head })}+ const isShort = ctx.columns < 132+return ctx.kit.Box({flexDirection: 'row',gap: 1,key: 'tabs',children: VIEWS.map(view => {- const isCurrent = view.id === ctx.state.view- const label = isShort ? view.label.slice(0, view.id === 'metaharness' ? 4 : 5) : view.label+ const isCurrent = view.id === ctx.state.view || (ctx.state.view === 'agent' && view.id === ctx.state.back)+ const label = isShort ? view.short : view.labelreturn ctx.kit.Button({ key: `tab-${view.id}`, label: isCurrent ? `${label}◂` : label, hotkey: view.key, plain: true, ...(isCurrent ? {} : { dimColor: true }), onPress: () => ctx.act.view(view.id) })}),@@ -51,28 +63,13 @@ function tabs(ctx: Ctx): RenderElement {}function help(ctx: Ctx): RenderElement {- const lines = [- 'Keys (while the pane holds the keyboard; click it or press ctrl+x tab):',- ' 1-8 switch view: overview, swarms, claims, federation, plugins, learning, metaharness, memory',- ' r refresh now h this help x close the console',- ' claims view: j/k pick a claim, a pick an agent, t pick a task,',- ' c claim the task, l release, o hand off, s steal (each asks y/n first)',- 'Commands (work without focus):',- ' /ruflo-console [view] open, or switch to a view by name or number',- ' /ruflo-console close close /ruflo-console status one-line summary',- 'Sources: ruflo files under .claude-flow/ and .swarm/, Claude Code plugin records, and',- 'the ruflo CLI (local commands only). Anything not measured reads n/a, never 0.',- ]-- return col(ctx, [...lines.map((line, i) => text(ctx, line, i === 0 || i === 5 || i === 8 ? { bold: true } : { dimColor: i > 8 })), row(ctx, [button(ctx, 'help-close', 'Back (h)', ctx.act.help)])], 'help')+ return col(ctx, [...HELP.split('\n').map((line, i) => text(ctx, line || ' ', i === 0 ? { bold: true, color: THEME.head } : /^[A-Z]/.test(line) ? { bold: true } : { dimColor: i > 20 })), row(ctx, [button(ctx, 'help-close', 'Back', ctx.act.help, { hotkey: 'h' })])], 'help')}function confirmRow(ctx: Ctx): RenderElement | null {const pending = ctx.state.pending- if (pending === null) {- return null- }+ if (pending === null) return nullreturn col(ctx,@@ -90,21 +87,31 @@ function footer(ctx: Ctx): RenderElement {const outcome = state.outcomeconst parts: RenderElement[] = []- if (outcome !== null && nowMs - outcome.atMs < 60_000) {+ if (outcome !== null && nowMs - outcome.atMs < 90_000) {parts.push(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,}),)++ for (const line of (outcome.lines ?? []).slice(0, 8)) parts.push(text(ctx, ` ${line}`, { dimColor: true }))}const read = state.snapshot === null ? 'reading…' : `read ${ago(state.snapshot.readAtMs, nowMs)}`- const keys = state.pane.isFocused ? 'keys: on' : 'keys: off — click the pane or ctrl+x tab (or use /ruflo-console <view>)'+ const keys = state.pane.isFocused ? 'keys on' : 'keys off: click the pane or ctrl+x tab (or /ruflo …)'parts.push(row(ctx, [- text(ctx, `${clip(`${read} · ${keys}`, Math.max(10, ctx.columns - 34))} `, { dimColor: true }),- ...(ctx.columns >= NARROW ? [button(ctx, 'refresh', 'Refresh', ctx.act.refresh, { hotkey: 'r' }), button(ctx, 'help', 'Help', ctx.act.help, { hotkey: 'h' }), button(ctx, 'close', 'Close', ctx.act.close, { hotkey: 'x' })] : []),+ text(ctx, `${clip(`${read} · ${keys}`, Math.max(10, ctx.columns - 46))} `, { dimColor: true }),+ ...(ctx.columns >= NARROW+ ? [+ button(ctx, 'palette', 'Palette', () => ctx.act.palette('all'), { hotkey: 'p' }),+ ...(state.view === 'agent' || state.palette.isOpen ? [] : [button(ctx, 'actions', 'Actions', () => ctx.act.palette('selection'), { hotkey: 'x' })]),+ button(ctx, 'refresh', 'Refresh', ctx.act.refresh, { hotkey: 'r' }),+ button(ctx, 'help', 'Help', ctx.act.help, { hotkey: 'h' }),+ button(ctx, 'close', 'Close', ctx.act.close),+ ]+ : []),]),)@@ -113,8 +120,10 @@ function footer(ctx: Ctx): RenderElement {/** The whole pane for this frame. */export function paneView(ctx: Ctx): RenderElement {- const body = ctx.state.isHelp ? help(ctx) : BODIES[ctx.state.view](ctx)+ const body = ctx.state.palette.isOpen ? paletteView(ctx) : ctx.state.isHelp ? help(ctx) : BODIES[ctx.state.view](ctx)const confirm = confirmRow(ctx)+ const header = ctx.pictures.get('header')+ const title = header !== undefined && ctx.kit.Raster !== undefined ? [ctx.kit.Raster(header.toRaster('header'))] : []- return ctx.kit.Box({ flexDirection: 'column', children: [tabs(ctx), body, ...(confirm !== null ? [confirm] : []), footer(ctx)] })+ return ctx.kit.Box({ flexDirection: 'column', children: [...title, tabs(ctx), body, ...(confirm !== null ? [confirm] : []), footer(ctx)] })}diff --git a/plugins/ruflo-console/hooks/views/plugins.ts b/plugins/ruflo-console/hooks/views/plugins.tsindex 8c78d36891..421d434a24 100644--- a/plugins/ruflo-console/hooks/views/plugins.ts+++ b/plugins/ruflo-console/hooks/views/plugins.ts@@ -2,7 +2,7 @@ import type { RenderElement } from 'claude-code'import { EXPECTED_IN_MARKET, RUFLO_MARKET } from '../data/snapshot'import { PLUGIN_NAME } from '../state'-import { ago, clip, col, kv, rule, text, THEME, type Ctx } from './common'+import { ago, col, kv, picture, rule, text, THEME, type Ctx } from './common'const WEEK = 7 * 86_400_000@@ -45,17 +45,12 @@ export function pluginsView(ctx: Ctx): RenderElement {rows.push(rule(ctx, 'Installed', facts.installed === null ? 'n/a' : `${ruflo.length} ruflo · ${enabled} enabled · ${(facts.installed ?? []).length} total`))- const width = Math.max(10, Math.floor((ctx.columns - 2) / 2))- const cells = ruflo- .sort((a, b) => a.name.localeCompare(b.name))- .map(plugin => `${facts.enabled.has(plugin.id) ? '✓' : '·'} ${plugin.name.replace(/^ruflo-/, '')} ${plugin.version}${facts.rufloOffered !== null && !facts.rufloOffered.includes(plugin.name) ? ' (gone from clone)' : ''}`)+ rows.push(picture(ctx, 'health', `${ruflo.length} ruflo plugins installed`))+ rows.push(text(ctx, 'columns: I installed · E enabled · I in the marketplace clone · M mod loaded here — ■ yes (green) / no (red), · unknown', { dimColor: true }))- for (let i = 0; i < Math.min(cells.length, 24); i += 2) {- rows.push(text(ctx, `${clip(cells[i] ?? '', width - 1).padEnd(width)}${clip(cells[i + 1] ?? '', width - 1)}`))- }+ const gone = ruflo.filter(plugin => facts.rufloOffered !== null && !facts.rufloOffered.includes(plugin.name))- if (cells.length > 24) rows.push(text(ctx, `+${cells.length - 24} more`, { dimColor: true }))- if (cells.length === 0) rows.push(text(ctx, 'no ruflo plugins installed — /plugin install ruflo-core@ruflo', { dimColor: true }))+ if (gone.length > 0) rows.push(text(ctx, `installed but gone from the clone: ${gone.map(plugin => plugin.name).join(', ')}`, { color: THEME.warn }))rows.push(rule(ctx, 'Mods', 'function hooks'))rows.push(kv(ctx, PLUGIN_NAME, 'loaded (you are reading it)', THEME.ok))diff --git a/plugins/ruflo-console/hooks/views/swarm.ts b/plugins/ruflo-console/hooks/views/swarm.tsindex 628015b39a..688290ea2b 100644--- a/plugins/ruflo-console/hooks/views/swarm.ts+++ b/plugins/ruflo-console/hooks/views/swarm.ts@@ -1,75 +1,68 @@import type { RenderElement } from 'claude-code'-import { clip, col, kv, picture, rule, text, THEME, type Ctx } from './common'-import { MAX_NODES } from './frames'+import { button, clip, col, kv, picture, row, rule, text, THEME, type Ctx } from './common'+import { selection } from './select'const STATUS_COLOR = (status: string): string | undefined =>/busy|active|running/i.test(status) ? THEME.warn : /error|fail/i.test(status) ? THEME.bad : /stop|terminat|offline/i.test(status) ? undefined : THEME.info/**- * The swarm as ruflo wrote it: a graph of its members with the leader marked, the agents' states, and the hive's votes.- * The tile board with per-agent buttons is ruflo-swarm's pane; this view links to it rather than drawing a second one.+ * The swarm as ruflo wrote it: a graph of its members with the leader marked, the agents (pick one with j/k, open it+ * with d), and the hive's votes. The tile board is ruflo-swarm's pane (/ruflo swarm pane); this view does not redraw it.*/export function swarmView(ctx: Ctx): RenderElement {const snap = ctx.state.snapshotconst swarm = snap?.swarm ?? nullconst hive = snap?.hive ?? null- const agents = swarm !== null && swarm.agentIds.length > 0 ? (snap?.agents ?? []).filter(agent => swarm.agentIds.includes(agent.id)) : (snap?.agents ?? [])+ const agents = snap?.agents ?? []+ const picked = selection(ctx.state).agentconst rows: RenderElement[] = [rule(ctx, 'Swarm', swarm?.id ?? '')]- if (snap === null) {- return text(ctx, 'reading ruflo state…', { dimColor: true })- }+ if (snap === null) return text(ctx, 'reading ruflo state…', { dimColor: true })if (swarm === null && hive === null && agents.length === 0) {- rows.push(text(ctx, 'No swarm on disk here. `npx ruflo swarm init --topology hierarchical` starts one; it shows here within seconds.', { dimColor: true }))+ rows.push(text(ctx, 'No swarm on disk here. `npx ruflo swarm init --topology hierarchical` starts one (or p → "start a swarm").', { dimColor: true }))- return ctx.kit.Box({ flexDirection: 'column', key: 'swarm', children: rows })+ return col(ctx, rows, 'swarm')}rows.push(kv(ctx, 'topology', swarm === null ? `${hive?.topology ?? 'n/a'} (hive-mind)` : `${swarm.topology}${swarm.strategy !== undefined ? ` · ${swarm.strategy}` : ''} · ${swarm.status}${swarm.maxAgents !== undefined ? ` · max ${swarm.maxAgents}` : ''}`))rows.push(picture(ctx, 'topology', `graph needs a terminal: ${agents.length} agents`))- rows.push(text(ctx, '★ leader · ● idle (blue) · busy (yellow) · stopped (grey) — pulses run to agents ruflo marks busy; the leader breathing is decoration', { dimColor: true }))+ rows.push(text(ctx, '★ leader (its heartbeat is decoration) · ● idle / busy / stopped as ruflo wrote them · a white pulse = an event about that agent', { dimColor: true }))+ rows.push(rule(ctx, 'Agents', `${agents.length} · j/k pick · d open · x actions`))- rows.push(rule(ctx, 'Agents', `${agents.length}${agents.length > MAX_NODES - 1 ? `, graph shows ${MAX_NODES - 1}` : ''}`))+ for (const agent of agents.slice(0, 10)) {+ const isPicked = picked?.id === agent.id+ const color = STATUS_COLOR(agent.status)- for (const agent of agents.slice(0, 8)) {rows.push(- ctx.kit.Box({- flexDirection: 'row',- children: [- ctx.kit.Text({ color: STATUS_COLOR(agent.status) ?? 'suggestion', ...(STATUS_COLOR(agent.status) === undefined && { dimColor: true }), children: '● ' }),- ctx.kit.Text({- wrap: 'truncate-end',- children: clip(- `${(agent.name ?? agent.type).padEnd(12)} ${agent.type.padEnd(12)} ${agent.status.padEnd(10)} tasks ${agent.taskCount ?? 'n/a'} · health ${agent.health === undefined ? 'n/a' : `${Math.round(agent.health * 100)}%`} · ${agent.id}`,- ctx.columns - 2,- ),- }),- ],- }),+ row(ctx, [+ ctx.kit.Text({ ...(color === undefined ? { dimColor: true } : { color }), children: `${isPicked ? '▸' : ' '}● ` }),+ ctx.kit.Text({+ wrap: 'truncate-end',+ ...(isPicked && { bold: true }),+ children: clip(`${(agent.name ?? agent.type).padEnd(14)} ${agent.type.padEnd(12)} ${agent.status.padEnd(9)} tasks ${agent.taskCount ?? 'n/a'} · health ${agent.health === undefined ? 'n/a' : `${Math.round(agent.health * 100)}%`} · ${agent.id}`, ctx.columns - 3),+ }),+ ]),)}- if (agents.length > 8) rows.push(text(ctx, `+${agents.length - 8} more`, { dimColor: true }))+ if (agents.length > 10) rows.push(text(ctx, `+${agents.length - 10} more (j/k walks all of them)`, { dimColor: true }))++ if (ctx.columns >= 44 && agents.length > 0) {+ rows.push(row(ctx, [button(ctx, 'agent-prev', 'prev', () => ctx.act.select(-1), { hotkey: 'k' }), button(ctx, 'agent-next', 'next', () => ctx.act.select(1), { hotkey: 'j' }), button(ctx, 'drill', 'Open agent', ctx.act.drill, { hotkey: 'd' })]))+ }rows.push(rule(ctx, 'Hive-mind', hive === null ? 'not initialised' : `${hive.strategy ?? 'consensus'}${hive.queen !== undefined ? ` · queen ${hive.queen}` : ''}`))if (hive === null) {rows.push(text(ctx, 'n/a — `npx ruflo hive-mind init` for queen-led consensus', { dimColor: true }))} else {- for (const proposal of hive.pending.slice(-3)) {- rows.push(text(ctx, `◇ ${proposal.type} (${proposal.strategy}) ${proposal.status} · for ${proposal.votesFor} · against ${proposal.votesAgainst} · ${proposal.id}`, { color: THEME.warn }))- }-- for (const decision of hive.history.slice(-2)) {- rows.push(text(ctx, `◆ ${decision.type} → ${decision.result} · for ${decision.votesFor} · against ${decision.votesAgainst}`, { dimColor: true }))- }-+ for (const proposal of hive.pending.slice(-3)) rows.push(text(ctx, `◇ ${proposal.type} (${proposal.strategy}) ${proposal.status} · for ${proposal.votesFor} · against ${proposal.votesAgainst} · ${proposal.id}`, { color: THEME.warn }))+ for (const decision of hive.history.slice(-2)) rows.push(text(ctx, `◆ ${decision.type} → ${decision.result} · for ${decision.votesFor} · against ${decision.votesAgainst}`, { dimColor: true }))if (hive.pending.length === 0 && hive.history.length === 0) rows.push(text(ctx, 'no proposals yet', { dimColor: true }))+ if (hive.pending.length > 0) rows.push(text(ctx, 'vote from Approvals (q) or the palette (p → vote)', { dimColor: true }))}- rows.push(text(ctx, 'Tile board, agent buttons and voting: /ruflo-swarm-pane (ruflo-swarm)', { dimColor: true }))-return col(ctx, rows, 'swarm')}diff --git a/plugins/ruflo-console/scripts/bench.ts b/plugins/ruflo-console/scripts/bench.tsindex 35c9c39288..0cc1cbb457 100644--- a/plugins/ruflo-console/scripts/bench.ts+++ b/plugins/ruflo-console/scripts/bench.ts@@ -86,6 +86,27 @@ async function main() {console.log(`${view.id.padEnd(12)} render ${stats(renders)} · frame [${pictures}] ${stats(frames)}`)}++ // The frame budget is 4 ms at 100 agents: a synthetic 100-agent swarm (counts only, nothing shown as real data).+ const base = state.snapshot as Snapshot+ const agents = Array.from({ length: 100 }, (_, i) => ({ id: `agent-bench-${i}`, type: i % 2 === 0 ? 'coder' : 'tester', status: i % 3 === 0 ? 'busy' : 'idle' }))++ for (const [topology, columns] of [['hierarchical', 160], ['mesh', 160]] as const) {+ state.snapshot = { ...base, agents, swarm: { id: 'swarm-bench', topology, status: 'running', agentIds: agents.map(agent => agent.id) } }+ state.view = 'swarm'+ state.events = agents.slice(0, 30).map((agent, i) => ({ atMs: Date.now() - i * 40, kind: 'swarm' as const, text: 'bench', agentId: agent.id }))++ const frames: number[] = []++ for (let i = 0; i < N; i++) {+ const start = process.hrtime.bigint()++ for (const grid of picturesOf(state, columns, Date.now(), Date.now() + i * 83).values()) grid.encode()+ frames.push(ms(start))+ }++ console.log(`100 agents ${topology.padEnd(12)} frame [header,topology] ${stats(frames)} (budget 4 ms)`)+ }}void main()diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.shindex 71fe4ee862..59a4a46022 100755--- a/plugins/ruflo-console/scripts/smoke.sh+++ b/plugins/ruflo-console/scripts/smoke.sh@@ -43,10 +43,10 @@ step "7. private key files are never read paths"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"+step "8. mutations only through fixed argv (claims_* via JSON.stringify), 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"+ && [[ "$(grep -ohE "exec\('claims_[a-z-]+'" "$HOOKS/actions.ts" "$HOOKS/ops.ts" | sort -u | tr '\n' ' ')" == "exec('claims_claim' exec('claims_handoff' exec('claims_release' exec('claims_status' exec('claims_steal' " ]] \+ && grep -q "state.pending = " "$HOOKS/runner.ts" && ! grep -qE "'(sh|bash)', '-c'" -r "$HOOKS" && 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:")diff --git a/plugins/ruflo-console/tests/behaviour.test.ts b/plugins/ruflo-console/tests/behaviour.test.tsindex 10cc307df4..28af69b66f 100644--- a/plugins/ruflo-console/tests/behaviour.test.ts+++ b/plugins/ruflo-console/tests/behaviour.test.ts@@ -3,7 +3,7 @@ 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+const VIEWS = ['overview', 'swarm', 'claims', 'federation', 'plugins', 'learning', 'metaharness', 'memory', 'cost', 'timeline', 'approvals', 'events', 'agent'] as constdescribe('behaviour', () => {test('a tab hotkey switches the view and the choice is kept for this folder only', async ($, on) => {@@ -14,10 +14,10 @@ describe('behaviour', () => {const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })- expect(textOf(await pane.drawn())).toContain('Overview◂')+ expect(textOf(await pane.drawn())).toContain('Ovr◂')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(textOf(await pane.drawn())).toContain('Clm◂')+ expect(world.stored.get('ruflo-console/ui:/work')).toEqual({ view: 'claims', isClosedByPerson: false })expect(world.opened.length).toBeGreaterThanOrEqual(2)await pane.unmount()})@@ -135,7 +135,7 @@ describe('behaviour', () => {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')+ if (isNarrow) expect(textOf(tree)).toContain('3/12 Claims')await pane.unmount()}})@@ -177,7 +177,7 @@ describe('behaviour', () => {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(textOf(await pane.drawn())).toContain('keys off')expect(world.blits).toHaveLength(0)await pane.unmount()})diff --git a/plugins/ruflo-console/tests/diagrams.spec.ts b/plugins/ruflo-console/tests/diagrams.spec.tsnew file mode 100644index 0000000000..55c6acccc2--- /dev/null+++ b/plugins/ruflo-console/tests/diagrams.spec.ts@@ -0,0 +1,113 @@+/**+ * Every diagram keeps its size across time (a blit must match the mounted Raster), counts on the real clock where its+ * motion is data, and stays inside the frame budget at 100 agents. Pure: run with `npx vitest run plugins/ruflo-console`.+ */+import { describe, expect, it } from 'vitest'++import { gaugePicture, pipelinePicture, radarPicture, samplesPicture, trendPicture } from '../hooks/gfx/charts'+import { flowModelOf, flowPicture, flowRows, ringOf } from '../hooks/gfx/flow'+import { federationPicture, ganttPicture, heatmapPicture } from '../hooks/gfx/maps'+import { activityPicture, curvePicture, edges, headerPicture, layout, markPicture, topologyPicture, type TopoModel } from '../hooks/gfx/pictures'+import type { Grid } from '../hooks/gfx/raster'+import { parseClaims, type ClaimRecord } from '../hooks/data/parse'+import { RUFLO_FILES } from './fixtures/ruflo-run'++const glyphs = (grid: Grid, y = 0) => Array.from({ length: grid.columns }, (_, x) => String.fromCodePoint(grid.glyph(x, y))).join('')+const claims = parseClaims(RUFLO_FILES['.claude-flow/claims/claims.json'] ?? null)+const swarmOf = (n: number, topology: string, busyEvery = 3): TopoModel => ({+ topology,+ nodes: [{ id: 'q', label: 'queen', status: 'leader', isLeader: true }, ...Array.from({ length: n - 1 }, (_, i) => ({ id: `a${i}`, label: `agent-${i}`, status: i % busyEvery === 0 ? 'busy' : 'idle', isLeader: false, pulseAtMs: 1_000 }))],+})++/** Every diagram, drawn at instant `t`, at a fixed size per diagram. */+function all(t: number): [string, Grid, number, number][] {+ const cards = flowModelOf(claims, [])++ return [+ ['topology', topologyPicture(swarmOf(4, 'hierarchical'), 90, 12, t), 90, 12],+ ['topology-mesh', topologyPicture(swarmOf(8, 'mesh'), 90, 14, t), 90, 14],+ ['activity', activityPicture([{ label: 'a', values: [1, 2, 3] }, { label: 'b', values: [] }], 80, t), 80, 2],+ ['curve', curvePicture([true, false, true], 80, 6, t, 500), 80, 6],+ ['mark', markPicture(true, t), 2, 1],+ ['header', headerPicture('◆ ruflo · proj', 40, t), 40, 1],+ ['flow', flowPicture(cards, 100, flowRows(cards), t), 100, flowRows(cards)],+ ['pipeline', pipelinePicture([{ name: 'RETRIEVE', count: 30_797, source: '' }, { name: 'JUDGE', count: 9, source: '' }, { name: 'DISTILL', count: null, source: '' }, { name: 'CONSOLIDATE', count: 0, source: '' }], 100, t, [null, 900, null, null]), 100, 4],+ ['radar', radarPicture([42, 12, 35, 90, 6].map((value, i) => ({ name: `d${i}`, value })), 80, 13, t, 0), 80, 13],+ ['trend', trendPicture([0, 2, 1, 3], 80, 4, 4, { top: 'critical', bottom: 'clean', empty: 'n/a' }), 80, 4],+ ['gauge', gaugePicture(3.9, 5, 60, 9), 60, 9],+ ['burn', samplesPicture('spend', [{ value: 0.1 }, { value: 0.4 }], 80), 80, 1],+ ['fedmap', federationPicture('this node', [{ label: 'peer-a', trust: 'pinned', trafficAtMs: 0 }, { label: '#ops', trust: 'channel' }, { label: 'npub1x', trust: 'roster' }], 80, 11, t), 80, 11],+ ['health', heatmapPicture([{ name: 'core', cells: [true, true, true, null] }, { name: 'mods', cells: [false, null, false, true] }], ['installed', 'enabled', 'clone', 'mod'], 80, 5), 80, 5],+ ['gantt', ganttPicture([{ label: 'coder', spans: [{ fromMs: 0, toMs: 500, busy: true }], ticks: [200] }], 80, 0, 1_000, t), 80, 2],+ ]+}++describe('diagrams', () => {+ it('every diagram keeps its size across t, so every frame fits the mounted Raster', () => {+ for (const t of [0, 1_234, 99_999]) {+ for (const [name, grid, columns, rows] of all(t)) {+ expect([name, grid.columns, grid.rows]).toEqual([name, columns, rows])+ expect(grid.encode().length, name).toBe(Math.ceil((columns * rows * 12) / 3) * 4)+ }+ }+ })++ it('the topology lays out a tree, a ring and a mesh from the real topology, and wraps a large swarm into tiers', () => {+ expect(edges(swarmOf(5, 'hierarchical'))).toEqual([[0, 1], [0, 2], [0, 3], [0, 4]])+ expect(edges(swarmOf(4, 'ring'))).toEqual([[0, 1], [1, 2], [2, 3], [3, 0]])+ expect(edges(swarmOf(4, 'mesh'))).toHaveLength(6)+ expect(edges(swarmOf(100, 'mesh'))).toHaveLength(300)++ const tiers = new Set(layout(swarmOf(100, 'hierarchical'), 220, 96).slice(1).map(point => Math.round(point.y)))++ expect(tiers.size).toBeGreaterThan(1)+ })++ it('an event pulse is data: it runs only in the 1.4 s after its event, and the frames differ while it does', () => {+ const model = swarmOf(3, 'hierarchical', 99)+ const frame = (t: number) => topologyPicture(model, 60, 12, t).encode()++ expect(frame(1_300)).not.toBe(frame(1_900))+ // Before the event, at two instants where the heartbeat (decoration) rests: nothing else moves.+ expect(frame(0)).toBe(frame(Math.PI * 260))+ })++ it('claims fall in their lanes and a ring counts down a TTL on the real clock, else fills with age', () => {+ expect(flowModelOf(claims, []).map(card => [card.id, card.lane])).toEqual([+ ['console-demo-1', 'claimed'],+ ['console-demo-2', 'stealable'],+ ])++ const ttl = { id: 'c', owner: 'coder', lane: 'claimed' as const, claimedAtMs: 0, expiresAtMs: 100_000 }++ expect(ringOf(ttl, 10_000)).toMatchObject({ glyph: '●', words: 'ttl 90s', isExpired: false })+ expect(ringOf(ttl, 80_000)).toMatchObject({ glyph: '◔', isExpired: false })+ expect(ringOf(ttl, 200_000)).toMatchObject({ words: 'expired', isExpired: true })+ expect(ringOf({ ...ttl, expiresAtMs: undefined }, 12 * 3_600_000).glyph).toBe('◑')++ const handoff: ClaimRecord = { issueId: 'h1', status: 'handoff-pending', claimant: { kind: 'agent', id: 'a', agentType: 'coder' }, isStealable: false, handoffTo: 'tester-1' }++ expect(glyphs(flowPicture(flowModelOf([handoff], []), 100, 4, 0), 2)).toContain('╰─▶tester-1')+ })++ it('the gauge has no needle without a budget, and the learning stages print n/a for what nothing measures', () => {+ expect(glyphs(gaugePicture(1, null, 60, 9), 8)).toContain('no budget set')+ expect(glyphs(gaugePicture(3.9, 5, 60, 9), 8)).toContain('$3.90 of $5.00 (78%)')+ expect(glyphs(pipelinePicture([{ name: 'DISTILL', count: null, source: '' }], 40, 0, [null]), 2)).toContain('n/a')+ })++ it('a frame of the 100-agent topology stays within the 4 ms budget (median of 50)', () => {+ const model = swarmOf(100, 'hierarchical')+ const times: number[] = []++ for (let i = 0; i < 50; i++) {+ const start = performance.now()++ topologyPicture(model, 160, 24, i * 83).encode()+ times.push(performance.now() - start)+ }++ times.sort((a, b) => a - b)+ expect(times[25]).toBeLessThan(4)+ })+})diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.tsindex 204521d6d6..74bb3e29ce 100644--- a/plugins/ruflo-console/tests/fixtures/world.ts+++ b/plugins/ruflo-console/tests/fixtures/world.ts@@ -25,7 +25,7 @@ export const BAND: RenderInput<'AbovePrompt'> = {props: { hasSurvey: false, isWorking: false, maxRows: 6, bodyColumns: 120, scroll: { offset: 0, bodyRows: 6 }, view: {} },} as RenderInput<'AbovePrompt'>-export const command = (args = '') => ({ command: 'ruflo-console', args, origin: { kind: 'composer' as const }, presentation: { isFullscreen: true, columns: 180 } })+export const command = (args = '') => ({ command: 'ruflo', args, origin: { kind: 'composer' as const }, presentation: { isFullscreen: true, columns: 180 } })export type Answer = { exitCode: number; stdout: string; stderr: string } | { deny: string }@@ -34,6 +34,7 @@ export type World = {runs: string[][]blits: string[]opened: string[]+ openArgs: { id: string; focus?: true; rows?: number }[]stored: Map<string, unknown>panes: { id: string; isShown: boolean; isFocused: boolean; title: string; isPlaced: boolean }[]/** Answers a CLI run by its argv; the default answers each probe from the captured run. */@@ -71,6 +72,7 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, optionsruns: [],blits: [],opened: [],+ openArgs: [],stored: new Map(),panes: [],respond: cliAnswer,@@ -121,6 +123,7 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, optionsif (refuse) return { deny: 'panes withheld' } as neverworld.opened.push(e.id)+ world.openArgs.push({ id: e.id, ...(e.focus !== undefined && { focus: e.focus }), ...(e.rows !== undefined && { rows: e.rows }) })world.panes = [{ id: e.id, title: e.title ?? e.id, isShown: true, isFocused: e.focus === true, isPlaced: true }]return { value: { isPlaced: true } } as neverdiff --git a/plugins/ruflo-console/tests/logic.spec.ts b/plugins/ruflo-console/tests/logic.spec.tsnew file mode 100644index 0000000000..77f8f3bbfc--- /dev/null+++ b/plugins/ruflo-console/tests/logic.spec.ts@@ -0,0 +1,108 @@+/**+ * The console's pure logic: `/ruflo` parsing, the palette's entries and fuzzy filter, the event diff, and the alerts+ * and approvals derived from a snapshot. Run with `npx vitest run plugins/ruflo-console`.+ */+import { describe, expect, it } from 'vitest'++import { alertsOf, approvalsOf, STALL_MS } from '../hooks/data/alerts'+import { diffEvents, recentByAgent } from '../hooks/data/events'+import { readSnapshot, type Snapshot } from '../hooks/data/snapshot'+import { parseRuflo } from '../hooks/commands'+import { filterPalette, fuzzy, paletteEntries } from '../hooks/palette'+import { memoryStore, reroute, textArg } from '../hooks/ops'+import { newState } from '../hooks/state'+import { RUFLO_FILES } from './fixtures/ruflo-run'++async function snapshotOf(files: Record<string, string>): Promise<Snapshot> {+ const all = Object.fromEntries(Object.entries(files).map(([path, text]) => [`/work/${path}`, text]))+ const fs = {+ read: async (path: string) => all[path] ?? Promise.reject(new Error('ENOENT')),+ stat: async (path: string) => (all[path] !== undefined ? { mtimeMs: 1, size: (all[path] as string).length } : Promise.reject(new Error('ENOENT'))),+ list: async () => [],+ }++ return readSnapshot(fs, new Map(), '/work', null, {}, 0)+}++describe('/ruflo', () => {+ it('reads every subcommand into an intent; swarm alone is the view, swarm <sub> belongs to ruflo-swarm', () => {+ expect(parseRuflo('')).toEqual({ kind: 'open', view: null })+ expect(parseRuflo('3')).toEqual({ kind: 'open', view: 'claims' })+ expect(parseRuflo('cost')).toEqual({ kind: 'open', view: 'cost' })+ expect(parseRuflo('swarm')).toEqual({ kind: 'open', view: 'swarm' })+ expect(parseRuflo('swarm status json')).toEqual({ kind: 'delegate', owner: 'ruflo-swarm', words: 'status json' })+ expect(parseRuflo('mods')).toEqual({ kind: 'delegate', owner: 'ruflo-mods', words: '' })+ expect(parseRuflo('run route fix the login bug')).toEqual({ kind: 'run', paletteId: 'route', text: 'fix the login bug' })+ expect(parseRuflo('agent coder-1')).toEqual({ kind: 'agent', who: 'coder-1' })+ expect(parseRuflo('filter claims')).toEqual({ kind: 'filter', filter: 'claims' })+ expect(parseRuflo('yes')).toEqual({ kind: 'confirm', isYes: true })+ expect(parseRuflo('frobnicate')).toEqual({ kind: 'unknown', word: 'frobnicate' })+ })+})++describe('palette', () => {+ it('fuzzy matches letters in order, prefers word starts, and refuses a missing letter', () => {+ expect(fuzzy('spc', 'spawn a coder agent')).not.toBeNull()+ expect(fuzzy('xyz', 'spawn a coder agent')).toBeNull()+ expect(fuzzy('sw', 'stop the swarm') ?? 0).toBeGreaterThan(fuzzy('sw', 'show the logs of coder') ?? 0)+ })++ it('offers the selection actions, every spawn type, votes for each proposal, workers and views', async () => {+ const state = newState({})++ state.snapshot = await snapshotOf(RUFLO_FILES)++ const ids = paletteEntries(state, 0).map(entry => entry.id)++ expect(ids).toEqual(expect.arrayContaining(['agent-drill', 'agent-logs', 'claim-release', 'claim-handoff', 'spawn-coder', 'swarm-init', 'swarm-stop', 'vote-yes-proposal-1790903321981-23aov7', 'mh-audit', 'worker-testgaps', 'route', 'store', 'search', 'view-approvals']))+ expect(filterPalette(paletteEntries(state, 0), 'route fix the login bug', 'all').map(entry => entry.id)).toEqual(['route'])+ expect(filterPalette(paletteEntries(state, 0), '', 'selection').every(entry => entry.group === 'agent' || entry.group === 'claims')).toBe(true)+ })++ it('free text is one argv element and never a flag', () => {+ expect(textArg(' -rf / ')).toBeNull()+ expect(textArg('a\u001bb')).toBe('a b')+ expect(reroute('fix it')?.args).toEqual(['hooks', 'route', '--task', 'fix it', '--format', 'json'])+ expect(memoryStore('note; rm -rf ~', 7)?.args).toEqual(['memory', 'store', '--key', 'console-7', '--value', 'note; rm -rf ~', '--namespace', 'console'])+ })+})++describe('events, alerts, approvals', () => {+ it('the first read is a baseline; later reads yield what changed, tagged with the agent it concerns', async () => {+ const before = await snapshotOf(RUFLO_FILES)+ const store = JSON.parse(RUFLO_FILES['.claude-flow/agents/store.json'] ?? '{}') as { agents: Record<string, Record<string, unknown>> }++ ;(Object.values(store.agents)[0] as Record<string, unknown>).status = 'busy'++ const claims = JSON.parse(RUFLO_FILES['.claude-flow/claims/claims.json'] ?? '{}') as { claims: Record<string, unknown> }++ delete claims.claims['console-demo-1']++ const after = await snapshotOf({ ...RUFLO_FILES, '.claude-flow/agents/store.json': JSON.stringify(store), '.claude-flow/claims/claims.json': JSON.stringify(claims) })++ expect(diffEvents(null, after, 5)).toEqual([])++ const events = diffEvents(before, after, 5)++ expect(events.map(event => event.text)).toEqual(['agent coder: idle → busy', 'console-demo-1 released'])+ expect(recentByAgent(events, 10, 100).get('agent-1790903032181-97m25s')).toBe(5)+ })++ it('alerts name what they saw and the fix; approvals list proposals and stealable claims with their actions', async () => {+ const state = newState({})+ const store = JSON.parse(RUFLO_FILES['.claude-flow/agents/store.json'] ?? '{}') as { agents: Record<string, Record<string, unknown>> }++ ;(Object.values(store.agents)[0] as Record<string, unknown>).status = 'busy'+ state.snapshot = await snapshotOf({ ...RUFLO_FILES, '.claude-flow/agents/store.json': JSON.stringify(store) })++ const created = Date.parse('2026-10-02T01:03:52.181Z')+ const alerts = alertsOf(state, created + STALL_MS + 60_000, created)++ expect(alerts.map(alert => alert.id)).toEqual(expect.arrayContaining(['stalled-agent-1790903032181-97m25s', 'mods']))+ expect(alertsOf(state, created + 60_000, created).some(alert => alert.id.startsWith('stalled'))).toBe(false)+ expect(approvalsOf(state).map(item => [item.kind, item.actions.map(action => action.paletteId)])).toEqual([+ ['proposal', ['vote-yes-proposal-1790903321981-23aov7', 'vote-no-proposal-1790903321981-23aov7']],+ ['stealable', ['claim-steal']],+ ])+ })+})diff --git a/plugins/ruflo-console/tests/palette.test.ts b/plugins/ruflo-console/tests/palette.test.tsnew file mode 100644index 0000000000..a68dc570c5--- /dev/null+++ b/plugins/ruflo-console/tests/palette.test.ts@@ -0,0 +1,126 @@+import { describe, expect, mock, test } from 'claude-code/testing'++import { RUFLO_FILES } from './fixtures/ruflo-run'+import { command, elementsOf, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'++const runsOf = (runs: readonly string[][], word: string) => runs.filter(argv => argv.includes(word))++describe('palette and /ruflo', () => {+ test('p opens the palette; typing filters; a change asks first and runs one fixed argv on yes', 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), surface: 'terminal' as const, plugin: PLUGIN })++ await pane.press({ key: 'palette' })+ expect(elementsOf(await pane.drawn(), 'Input').map(keyOf)).toEqual(['palette-input'])++ await pane.input({ key: 'palette-input', text: 'spawn cod', kind: 'change' })++ const filtered = await pane.drawn()++ expect(elementsOf(filtered, 'Button').map(keyOf).filter(key => key.startsWith('pal-'))[0]).toBe('pal-spawn-coder')++ await pane.press({ key: 'pal-spawn-coder' })+ expect(textOf(await pane.drawn())).toMatch(/Confirm: spawn a coder agent named coder-\d+\?/)+ expect(runsOf(world.runs, 'spawn')).toHaveLength(0)++ await pane.press({ key: 'confirm' })++ const spawn = runsOf(world.runs, 'spawn')[0] ?? []++ expect(spawn.slice(4, 8)).toEqual(['agent', 'spawn', '--type', 'coder'])+ expect(spawn[8]).toBe('--name')+ await pane.unmount()+ })++ test('a read runs at once and shows its output: route <words> asks the router', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ mock.clock(on)+ world.respond = argv => (argv.includes('route') ? { exitCode: 0, stdout: '{\n "primaryAgent": {"type": "tester", "confidence": 0.8}\n}', stderr: '' } : { exitCode: 0, stdout: '{}', stderr: '' })+ await $.session.start(SESSION)++ const answer = await $.command.run(command('run route write the login tests'))++ expect(answer.text).toBe('route "write the login tests"')+ expect(runsOf(world.runs, 'route')[0]?.slice(4)).toEqual(['hooks', 'route', '--task', 'write the login tests', '--format', 'json'])++ const text = textOf(await $.ui.render(paneAt(110)))++ expect(text).toContain('"type": "tester"')+ })++ test('/ruflo run and /ruflo yes act without focus; a flag-shaped text is refused', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ expect((await $.command.run(command('run worker-audit'))).text).toBe('Asked: dispatch the audit worker. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.')+ expect((await $.command.run(command('yes'))).text).toMatch(/^✓ dispatch the audit worker/)+ expect(runsOf(world.runs, 'dispatch')[0]?.slice(4)).toEqual(['hooks', 'worker', 'dispatch', '--trigger', 'audit'])++ await $.command.run(command('run store --dangerous'))+ expect((await $.command.run(command('yes'))).text).toBe('Nothing is waiting for a confirm.')+ expect(runsOf(world.runs, 'store')).toHaveLength(0)+ expect((await $.command.run(command('run nope'))).text).toMatch(/^No palette entry "nope"/)+ })++ test('approvals: a hive proposal is voted on in place, as console-operator, after a confirm', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)+ await $.command.run(command('approvals'))++ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })++ await pane.press({ key: 'approve-0' })+ await pane.press({ key: 'confirm' })++ expect(runsOf(world.runs, 'consensus')[0]?.slice(4)).toEqual(['hive-mind', 'consensus', '--action', 'vote', '--proposal-id', 'proposal-1790903321981-23aov7', '--vote', 'yes', '--voter-id', 'console-operator'])+ await pane.unmount()+ })++ test('/ruflo help, an unknown word, and the hints when ruflo-mods or ruflo-swarm are not loaded', async ($, on) => {+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ expect((await $.command.run(command('help'))).text).toContain('/ruflo swarm pane|status|topology|claims|consensus')+ expect((await $.command.run(command('frobnicate'))).text).toMatch(/^Unknown: "frobnicate"/)+ expect((await $.command.run(command('mods'))).text).toMatch(/^ruflo-mods is not loaded in this session/)+ expect((await $.command.run(command('swarm status'))).text).toMatch(/^ruflo-swarm is not loaded in this session/)+ })++ test('/ruflo mods and /ruflo swarm <sub> are answered by the plugin beneath that owns them', async ($, on) => {+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ on('command.run', ($, e) => ({ text: `beneath answered: ${e.args}` }))+ await $.session.start(SESSION)++ expect((await $.command.run(command('mods'))).text).toBe('beneath answered: mods')+ expect((await $.command.run(command('swarm topology'))).text).toBe('beneath answered: swarm topology')+ expect((await $.command.run(command('swarm'))).text).toBe('ruflo console: Swarm')+ })++ test('panel auto opens the cockpit at session start without taking the keys; panel command does not', { options: { panel: 'auto' } }, async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ const clock = mock.clock(on)+ await $.session.start(SESSION)+ await clock.advance(100)++ expect(world.openArgs).toHaveLength(1)+ expect(world.openArgs[0]).toMatchObject({ id: 'ruflo-console' })+ expect(world.openArgs[0]?.focus).toBeUndefined()+ })++ test('panel command never opens unasked', { options: { panel: 'command' } }, async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ const clock = mock.clock(on)+ await $.session.start(SESSION)+ await clock.advance(500)++ expect(world.opened).toHaveLength(0)+ })+})diff --git a/plugins/ruflo-console/tests/pure.spec.ts b/plugins/ruflo-console/tests/pure.spec.tsindex 50b3d66471..7e3ad6e560 100644--- a/plugins/ruflo-console/tests/pure.spec.ts+++ b/plugins/ruflo-console/tests/pure.spec.ts@@ -10,11 +10,10 @@ import { parseMarketplaces, parseNeural, parseOutcomes, parseRouter } from '../himport { 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 { toBase64 } from '../hooks/gfx/raster'import { newState } from '../hooks/state'-import { picturesOf, topoModelOf } from '../hooks/views/frames'-import { ladder } from '../hooks/views/memory'+import { picturesOf } from '../hooks/views/frames'+import { ladder } from '../hooks/views/cost'import { CLI_OUT, HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'const at = (path: string) => RUFLO_FILES[path] ?? null@@ -138,40 +137,13 @@ describe('graphics', () => {}})- 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)+ expect([...picturesOf(state, 90, 0, 5).keys()]).toEqual(['header', 'curve', 'pipeline', 'patterns'])+ state.view = 'memory'+ expect([...picturesOf(state, 90, 0, 5).keys()]).toEqual(['header'])})it('the budget ladder marks 50/75/90/100% and fills to the spend', () => {diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.tsindex 011072c8d2..fe687fd483 100644--- a/plugins/ruflo-console/tests/views.test.ts+++ b/plugins/ruflo-console/tests/views.test.ts@@ -16,137 +16,164 @@ const HOME_FILES = {'.claude/plugins/marketplaces/ruflo/.claude-plugin/marketplace.json': JSON.stringify({ name: 'ruflo', plugins: [{ name: 'ruflo-core' }, { name: 'ruflo-swarm' }] }),}-/** Opens the console on `view` and answers its drawing once the probes for that view have run. */-async function drawn($: Parameters<TestBody>[0], view: string, columns = 110) {+type Engine = Parameters<TestBody>[0]++/** Opens the console on `view` via /ruflo, waits for its probes, and answers its drawing and its Raster keys. */+async function drawn($: Engine, view: string, columns = 110) {await $.command.run(command(view))await $.command.run(command('status'))- return mountedText($, columns)-}--async function mountedText($: Parameters<TestBody>[0], columns: number) {const pane = await $.ui.mount({ ...paneAt(columns), plugin: PLUGIN })const tree = await pane.drawn()await pane.unmount()- return { text: textOf(tree), tree }+ return { text: textOf(tree), tree, rasters: elementsOf(tree, 'Raster').map(keyOf) }}describe('views', () => {- test('overview: every subsystem from disk, the CLI or the engine, the activity raster, nothing invented', async ($, on) => {+ test('overview: every subsystem from disk, the CLI or the engine, health alerts, the activity raster', async ($, on) => {fakeRuflo().register(on, {})worldOf(on, RUFLO_FILES, { home: HOME_FILES })mock.clock(on)await $.session.start(SESSION)- const { text, tree } = await drawn($, 'overview')+ const { text, rasters } = await drawn($, 'overview')+ expect(rasters).toEqual(['header', 'activity'])expect(text).toContain('v3.50.0 (npx-offline)')expect(text).toContain('running per daemon-state.json')expect(text).toContain('1 ruflo server connected (claude-flow) · 2 tools callable now')- expect(text).toContain('1 entries')expect(text).toContain('manifest v3.32.24')- expect(text).toContain('signature not checked here')expect(text).toContain('seated · policy observe · routed 4')expect(text).toContain('swarm-1790903031804-y9rnjr · hierarchical · running · 2 agents')- expect(elementsOf(tree, 'Raster').map(keyOf)).toEqual(['activity'])+ expect(text).toContain('marketplace clone stale: no ruflo-mods — /plugin marketplace update ruflo')+ expect(text).toContain('budget WARNING: $3.90 of $5.00')})- test('swarms: the topology graph, agents, the hive with its proposal, and no hive token', async ($, on) => {+ test('swarm: the topology graph, selectable agents, the hive with its proposal, no hive token', async ($, on) => {worldOf(on, RUFLO_FILES)mock.clock(on)await $.session.start(SESSION)- const { text, tree } = await drawn($, 'swarm')+ const { text, rasters, tree } = await drawn($, 'swarm')- expect(elementsOf(tree, 'Raster').map(keyOf)).toEqual(['topology'])+ expect(rasters).toEqual(['header', 'topology'])expect(text).toContain('hierarchical · specialized · running · max 6')- expect(text).toMatch(/coder\s+coder\s+idle/)+ expect(text).toMatch(/▸● \ncoder\s+coder\s+idle/)expect(text).toContain('design (raft) pending · for 0 · against 0')- expect(text).toContain('/ruflo-swarm-pane')expect(text).not.toContain(HIVE_TOKEN)+ expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['agent-next', 'agent-prev', 'drill', 'palette', 'actions']))})- test('claims: the board with a stealable claim, TTL bars, and the act row', async ($, on) => {+ test('claims: the flow diagram with lanes and rings, the board, and the act row', async ($, on) => {worldOf(on, RUFLO_FILES)mock.clock(on)await $.session.start(SESSION)- const { text, tree } = await drawn($, 'claims')+ const { text, rasters, tree } = await drawn($, 'claims')+ expect(rasters).toEqual(['header', 'flow'])expect(text).toContain('1 active · 1 stealable · 0 handoff')- expect(text).toContain('console-demo-1')- expect(text).toMatch(/console-demo-2.*stealable/)expect(text).toContain('no claims tool sets a TTL today')- expect(elementsOf(tree, 'Raster').map(keyOf)).toEqual(['claims'])- expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['claim', 'release', 'handoff', 'steal', 'agent-next']))+ expect(text).toMatch(/console-demo-2.*stealable/)+ expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['claim', 'release', 'handoff', 'steal', 'agent-next', 'task-next']))})- test('federation: local identity and channels, the relay never asked while the network option is off', async ($, on) => {+ test('federation: the map, local identity and channels; the relay is never asked while the option is off', async ($, on) => {const world = worldOf(on, RUFLO_FILES)mock.clock(on)await $.session.start(SESSION)- const { text } = await drawn($, 'federation')+ const { text, rasters } = await drawn($, 'federation')+ expect(rasters).toEqual(['header', 'fedmap'])expect(text).toContain('agentbbs agentbbs-not-found')- expect(text).toContain('no channels joined')expect(text).toContain('Off: the roster is on the public relay')expect(world.runs.some(argv => argv.join(' ').includes('x_federation_roster'))).toBe(false)})- test('plugins: a marketplace clone that does not list ruflo-mods reads STALE with the fix named', async ($, on) => {+ test('plugins: the health matrix, and a clone without ruflo-mods reads STALE with the fix named', async ($, on) => {worldOf(on, RUFLO_FILES, { home: HOME_FILES })mock.clock(on)await $.session.start(SESSION)- const { text } = await drawn($, 'plugins')+ const { text, rasters } = await drawn($, 'plugins')+ expect(rasters).toEqual(['header', 'health'])expect(text).toContain('STALE: the clone does not list ruflo-mods')- expect(text).toContain('/plugin marketplace update ruflo')expect(text).toContain('2 ruflo · 1 enabled · 2 total')- expect(text).toContain('✓ core 0.2.6')})- test('learning: the last route, the outcome rate with its N, the curve, SONA counts', async ($, on) => {+ test('learning: last route, outcome rate with its N, the curve, the four-stage pipeline, pattern growth', async ($, on) => {fakeRuflo().register(on, {})worldOf(on, RUFLO_FILES)mock.clock(on)await $.session.start(SESSION)- const { text, tree } = await drawn($, 'learning')+ const { text, rasters } = await drawn($, 'learning')+ expect(rasters).toEqual(['header', 'curve', 'pipeline', 'patterns'])expect(text).toContain('tester 60% · keyword match')expect(text).toMatch(/\d+\/9 succeeded \(\d+% success rate, N=9\)/)- expect(text).toContain('30.8k')- expect(elementsOf(tree, 'Raster').map(keyOf)).toEqual(['curve'])+ expect(text).toContain('consolidate: EWC consolidations')})- test('metaharness: the five scores, the flywheel ledger and the active policy', async ($, on) => {+ test('metaharness: the radar, the audit trend, the flywheel ledger and the active policy', async ($, on) => {worldOf(on, RUFLO_FILES)mock.clock(on)await $.session.start(SESSION)- const { text, tree } = await drawn($, 'metaharness')+ const { text, rasters } = await drawn($, 'metaharness')- expect(elementsOf(tree, 'Raster').map(keyOf)).toEqual(['score'])+ expect(rasters).toEqual(['header', 'radar', 'trend'])expect(text).toContain('$0.024')expect(text).toContain('valid · 0 commits · 0 receipts')- expect(text).toContain('none promoted')})- test('memory: entries, a namespace sample, spend and the budget ladder from ruflo-mods', async ($, on) => {+ test('memory and cost: entries, a namespace sample; spend, the gauge, the ladder and the burn', async ($, on) => {fakeRuflo().register(on, {})worldOf(on, RUFLO_FILES)mock.clock(on)await $.session.start(SESSION)- const { text } = await drawn($, 'memory')+ const memory = await drawn($, 'memory')++ expect(memory.text).toContain('1 · 0 with vectors')+ expect(memory.text).toMatch(/console\s+█+ 1/)++ const cost = await drawn($, 'cost')++ expect(cost.rasters).toEqual(['header', 'gauge', 'burn'])+ expect(cost.text).toContain('$0.421')+ expect(cost.text).toContain('WARNING · $3.90 of $5.00 (78%)')+ })++ test('timeline, approvals and events draw from what was seen; the drill-down opens an agent', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ expect((await drawn($, 'timeline')).rasters).toEqual(['header', 'gantt'])++ const approvals = await drawn($, 'approvals')++ expect(approvals.text).toContain('[proposal] hive-mind proposal: design (raft)')+ expect(approvals.text).toContain('[stealable] claim console-demo-2 offered for stealing')++ const store = JSON.parse(RUFLO_FILES['.claude-flow/agents/store.json'] ?? '{}') as { agents: Record<string, Record<string, unknown>> }++ ;(Object.values(store.agents)[1] as Record<string, unknown>).status = 'busy'+ world.put('.claude-flow/agents/store.json', JSON.stringify(store))+ await $.command.run(command('status'))+ expect((await drawn($, 'events')).text).toContain('agent tester: idle → busy')++ await $.command.run(command('agent tester'))++ const agent = await drawn($, 'agent agent-1790903032591-x41b0y')- expect(text).toContain('1 · 0 with vectors')- expect(text).toMatch(/console\s+█+ 1/)- expect(text).toContain('$0.421')- expect(text).toContain('WARNING · $3.90 of $5.00 (78%)')+ expect(agent.text).toContain('tester · tester')+ expect(agent.text).toContain('console-demo-2 stealable')+ expect(world.runs.some(argv => argv.join(' ').includes('agent logs --id agent-1790903032591-x41b0y --tail 20'))).toBe(true)})})diff --git a/plugins/ruflo-mods/hooks/session.ts b/plugins/ruflo-mods/hooks/session.tsindex 41559b95eb..2a8e01fc01 100644--- a/plugins/ruflo-mods/hooks/session.ts+++ b/plugins/ruflo-mods/hooks/session.ts@@ -52,7 +52,7 @@ export function registerSession(on: On, state: ModState, options: ModOptions) {state.statusLine = options.statusLine && !hasClassicStatusLine(settings)redraw(state)await $.command- .register({ name: 'ruflo-mods', description: 'ruflo mods: what this session routed, recorded and tightened' })+ .register({ name: 'ruflo-mods', description: 'Deprecated, use /ruflo mods (ruflo-console): what this session routed, recorded and tightened' }).catch(() => undefined)const heartbeat = { startedAt: new Date().toISOString(), owned: [...state.owned], statusLine: state.statusLine }await $.fs.write(under(state, HEARTBEAT_PATH), `${JSON.stringify(heartbeat, null, 2)}\n`).catch(() => undefined)@@ -73,4 +73,9 @@ export function registerSession(on: On, state: ModState, options: ModOptions) {})on('command.run', { command: 'ruflo-mods' }, () => ({ text: report(state) }))++ // `/ruflo` is ruflo-console's one command for every ruflo mod; its `mods` subcommand is this report. The console+ // registers `/ruflo`; this hook answers `mods` wherever it sits in the chain and passes every other word on.+ // `/ruflo-mods` above stays registered for one release as a deprecated alias.+ on('command.run', { command: 'ruflo' }, ($, e, next) => (e.args.trim().split(/\s+/)[0]?.toLowerCase() === 'mods' ? { text: report(state) } : next(e)))}diff --git a/plugins/ruflo-mods/tests/register.test.ts b/plugins/ruflo-mods/tests/register.test.tsindex ef7c0c46b4..1aa6ae4b58 100644--- a/plugins/ruflo-mods/tests/register.test.ts+++ b/plugins/ruflo-mods/tests/register.test.ts@@ -130,4 +130,19 @@ describe('register', () => {expect(text).toContain('owns: route, post-edit')expect(text).toContain('last devops (60%, matched)')})++ test('/ruflo mods answers the same report; other /ruflo words pass on to the console', async ($, on) => {+ world(on)+ on('prompt.submit', ($, e) => ({ text: e.text }))+ on('command.run', ($, e) => ({ text: `beneath: ${e.args}` }))+ await $.session.start(START)+ await $.prompt.submit(prompt('deploy with docker'))++ const run = (args: string) => $.command.run({ command: 'ruflo', args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } })+ const alias = await $.command.run({ command: 'ruflo-mods', args: '', origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 100 } })++ expect((await run('mods')).text).toBe(alias.text)+ expect((await run('mods')).text).toContain('owns: route, post-edit')+ expect((await run('claims')).text).toBe('beneath: claims')+ })})diff --git a/plugins/ruflo-swarm/.claude-plugin/plugin.json b/plugins/ruflo-swarm/.claude-plugin/plugin.jsonindex cf339853be..42d9de687d 100644--- a/plugins/ruflo-swarm/.claude-plugin/plugin.json+++ b/plugins/ruflo-swarm/.claude-plugin/plugin.json@@ -26,8 +26,8 @@"panel": {"type": "string","title": "Swarm pane",- "description": "auto opens the pane when a ruflo swarm is on disk and the layout docks panes; command opens it only with /ruflo-swarm-pane or /ruflo-swarm:watch; off never opens it.",- "default": "auto",+ "description": "command (default) opens the pane only with /ruflo swarm pane (or the deprecated /ruflo-swarm-pane, or /ruflo-swarm:watch); auto also opens it when a ruflo swarm is on disk and the layout docks panes (ruflo-console's cockpit is the pane that opens by itself now); off never opens it.",+ "default": "command","options": ["auto","command",diff --git a/plugins/ruflo-swarm/hooks/commands.ts b/plugins/ruflo-swarm/hooks/commands.tsindex 348fd9e6f7..028d9b74aa 100644--- a/plugins/ruflo-swarm/hooks/commands.ts+++ b/plugins/ruflo-swarm/hooks/commands.ts@@ -8,17 +8,24 @@ import type { State } from './state'import { paneModelOf } from './views/model'/**- * The commands this module serves. Each name is prefixed with the plugin's so it never stands in for a built-in- * (`/diff`, `/status`) or for the plugin's own markdown commands (`/ruflo-swarm:swarm`, `/ruflo-swarm:watch`).+ * The commands this module registers: since ruflo-console's `/ruflo`, each is a deprecated alias of `/ruflo swarm+ * <sub>`, kept for one release. Each name is prefixed with the plugin's so it never stands in for a built-in.*/export const COMMANDS: readonly CommandSpec[] = [- { name: 'ruflo-swarm-pane', description: 'Show or hide the live swarm pane', argumentHint: '[open|close]', immediate: true },- { name: 'ruflo-swarm-status', description: 'The swarm as ruflo has it on disk: agents, tasks, claims, router and usage', argumentHint: '[json]', immediate: true },- { name: 'ruflo-swarm-topology', description: 'The swarm topology, its leader and members', immediate: true },- { name: 'ruflo-swarm-claims', description: 'Who has claimed which task, and what is stealable', immediate: true },- { name: 'ruflo-swarm-consensus', description: 'Hive-mind proposals, votes and recent decisions', immediate: true },+ { name: 'ruflo-swarm-pane', description: 'Deprecated, use /ruflo swarm pane: show or hide the live swarm pane', argumentHint: '[open|close]', immediate: true },+ { name: 'ruflo-swarm-status', description: 'Deprecated, use /ruflo swarm status: the swarm as ruflo has it on disk', argumentHint: '[json]', immediate: true },+ { name: 'ruflo-swarm-topology', description: 'Deprecated, use /ruflo swarm topology: the topology, its leader and members', immediate: true },+ { name: 'ruflo-swarm-claims', description: 'Deprecated, use /ruflo swarm claims: who has claimed which task', immediate: true },+ { name: 'ruflo-swarm-consensus', description: 'Deprecated, use /ruflo swarm consensus: hive-mind proposals and votes', immediate: true },]+/** The subcommands of `/ruflo swarm` this module answers; the old `/ruflo-swarm-<sub>` names are their aliases. */+export const SWARM_SUBS = ['pane', 'status', 'topology', 'claims', 'consensus'] as const++export type SwarmSub = (typeof SWARM_SUBS)[number]++export const isSwarmSub = (word: string): word is SwarmSub => (SWARM_SUBS as readonly string[]).includes(word)+const NO_SWARM = 'No ruflo swarm on disk in this folder. Start one with /ruflo-swarm:swarm init.'function missingLine(snapshot: Snapshot): string {diff --git a/plugins/ruflo-swarm/hooks/register.ts b/plugins/ruflo-swarm/hooks/register.tsindex fabe2e6ffd..bc7de0dd75 100644--- a/plugins/ruflo-swarm/hooks/register.ts+++ b/plugins/ruflo-swarm/hooks/register.ts@@ -2,7 +2,7 @@ import type { EngineInterface, On, PluginOptions } from 'claude-code'import { paneActionsOf, type Controller } from './actions/controller'import { AUDIT_FLUSH_MS, auditRow, noteAudit, takeFlush } from './audit'-import { claimsText, COMMANDS, consensusText, spawnNote, statusText, topologyText } from './commands'+import { claimsText, COMMANDS, consensusText, isSwarmSub, spawnNote, statusText, SWARM_SUBS, topologyText, type SwarmSub } from './commands'import type { Host, OpenResult } from './host'import { isAnimating, LEAD, newActivity, noteCall, noteDone, noteListed, noteResult, noteSpawn } from './model/members'import { parseRoute, plain } from './reader/parse'@@ -305,74 +305,72 @@ export function register(on: On, raw: PluginOptions) {// -------------------------------------------------------------- commands- on('command.run', { command: 'ruflo-swarm-pane' }, async ($, e, next) => {- if (host === null) {- return next(e)- }+ /** The five swarm commands, each by its subcommand word: what `/ruflo swarm <sub>` and the old names both answer. */+ async function answer(sub: SwarmSub, args: string): Promise<{ text: string }> {+ const bound = host as Host- const arg = e.args.trim().toLowerCase()-- if (arg === 'close' || (arg === '' && state.pane.isOpen)) {- state.pane.isOpen = false- state.pane.isClosedByPerson = true- persist()- await host.closePane(PANE_ID).catch(() => undefined)+ switch (sub) {+ case 'pane': {+ const arg = args.trim().toLowerCase()- return { text: 'Swarm pane hidden' }- }-- const opened = await openPane()+ if (arg === 'close' || (arg === '' && state.pane.isOpen)) {+ state.pane.isOpen = false+ state.pane.isClosedByPerson = true+ persist()+ await bound.closePane(PANE_ID).catch(() => undefined)- return { text: opened.isPlaced ? 'Swarm pane shown' : `The swarm pane could not be shown: ${opened.reason}` }- })+ return { text: 'Swarm pane hidden' }+ }- /** The plugin's markdown `/ruflo-swarm:watch` still runs as it always has; with the mod it opens the pane as well. */- on('command.run', { command: 'ruflo-swarm:watch' }, async ($, e, next) => {- if (host !== null && state.options.panel !== 'off') {- await openPane()- }+ const opened = await openPane()- return next(e)- })+ return { text: opened.isPlaced ? 'Swarm pane shown' : `The swarm pane could not be shown: ${opened.reason}` }+ }+ case 'status':+ await refresh()- on('command.run', { command: 'ruflo-swarm-status' }, async ($, e, next) => {- if (host === null) {- return next(e)- }+ return { text: statusText(state, Date.now(), args.trim().toLowerCase() === 'json') }+ case 'topology':+ await refresh()- await refresh()+ return { text: topologyText(state, Date.now()) }+ case 'claims':+ await refresh()- return { text: statusText(state, Date.now(), e.args.trim().toLowerCase() === 'json') }- })+ return { text: claimsText(state) }+ case 'consensus':+ await refresh()- on('command.run', { command: 'ruflo-swarm-topology' }, async ($, e, next) => {- if (host === null) {- return next(e)+ return { text: consensusText(state) }}+ }- await refresh()-- return { text: topologyText(state, Date.now()) }- })+ /**+ * `/ruflo swarm <pane|status|topology|claims|consensus>`: ruflo-console registers `/ruflo` for every ruflo mod, and+ * this hook answers its swarm subcommands wherever it sits in the chain, passing every other word on.+ */+ on('command.run', { command: 'ruflo' }, async ($, e, next) => {+ const [head = '', sub = '', ...rest] = e.args.trim().split(/\s+/)- on('command.run', { command: 'ruflo-swarm-claims' }, async ($, e, next) => {- if (host === null) {+ if (host === null || head.toLowerCase() !== 'swarm' || !isSwarmSub(sub.toLowerCase())) {return next(e)}- await refresh()-- return { text: claimsText(state) }+ return answer(sub.toLowerCase() as SwarmSub, rest.join(' '))})- on('command.run', { command: 'ruflo-swarm-consensus' }, async ($, e, next) => {- if (host === null) {- return next(e)- }+ // The old names stay registered for one release as deprecated aliases of `/ruflo swarm <sub>`.+ for (const sub of SWARM_SUBS) {+ on('command.run', { command: `ruflo-swarm-${sub}` }, async ($, e, next) => (host === null ? next(e) : answer(sub, e.args)))+ }- await refresh()+ /** The plugin's markdown `/ruflo-swarm:watch` still runs as it always has; with the mod it opens the pane as well. */+ on('command.run', { command: 'ruflo-swarm:watch' }, async ($, e, next) => {+ if (host !== null && state.options.panel !== 'off') {+ await openPane()+ }- return { text: consensusText(state) }+ return next(e)})// ----------------------------------------------------------------- turnsdiff --git a/plugins/ruflo-swarm/hooks/state.ts b/plugins/ruflo-swarm/hooks/state.tsindex ea2543de01..4ed4ee1e05 100644--- a/plugins/ruflo-swarm/hooks/state.ts+++ b/plugins/ruflo-swarm/hooks/state.ts@@ -41,7 +41,8 @@ const PANELS = new Set(['auto', 'command', 'off'])/** The options as the settings hold them, each one checked: a value the plugin does not know is its default. */export function optionsOf(raw: PluginOptions): Options {const value = (raw ?? {}) as Record<string, unknown>- const panel = typeof value.panel === 'string' && PANELS.has(value.panel) ? (value.panel as Options['panel']) : 'auto'+ // `command` by default since ruflo-console: its cockpit is the pane that opens by itself, and two would crowd the dock.+ const panel = typeof value.panel === 'string' && PANELS.has(value.panel) ? (value.panel as Options['panel']) : 'command'const cli = typeof value.cli === 'string' && value.cli in CLI_PREFIXES ? (value.cli as CliChoice) : 'npx-offline'const threshold = typeof value.routeThreshold === 'number' ? value.routeThreshold : Number(value.routeThreshold)diff --git a/plugins/ruflo-swarm/tests/register.test.ts b/plugins/ruflo-swarm/tests/register.test.tsindex 86f703e209..a1a0520eba 100644--- a/plugins/ruflo-swarm/tests/register.test.ts+++ b/plugins/ruflo-swarm/tests/register.test.ts@@ -15,7 +15,7 @@ describe('register', () => {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) => {+ test('with panel auto and a swarm on disk the pane opens once the fullscreen hint draws; on the main screen it waits', { options: { panel: 'auto' } }, async ($, on) => {const world = worldOf(on, RUFLO_RUN)const clock = mock.clock(on)@@ -32,7 +32,35 @@ describe('register', () => {expect(world.opened).toEqual([PLUGIN])})- test('with no swarm on disk nothing opens, and the pane says how to start one', async ($, on) => {+ test('by default (panel command) nothing opens unasked, swarm or not: ruflo-console owns auto-start', 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(HINT)+ await clock.advance(200)+ expect(world.opened).toEqual([])+ })++ test('/ruflo swarm <sub> answers as the deprecated names do; other /ruflo words pass on', async ($, on) => {+ worldOf(on, RUFLO_RUN)+ mock.clock(on)+ on('command.run', ($, e) => ({ text: `beneath: ${e.args}` }))+ await $.session.start(SESSION)++ const ruflo = (args: string) => $.command.run({ ...command('ruflo'), args })++ for (const sub of ['status', 'topology', 'claims', 'consensus'] as const) {+ expect((await ruflo(`swarm ${sub}`)).text).toBe((await $.command.run(command(`ruflo-swarm-${sub}`))).text)+ }++ expect((await ruflo('swarm pane')).text).toBe('Swarm pane shown')+ expect((await ruflo('swarm')).text).toBe('beneath: swarm')+ expect((await ruflo('mods')).text).toBe('beneath: mods')+ })++ test('with no swarm on disk nothing opens, and the pane says how to start one', { options: { panel: 'auto' } }, async ($, on) => {const world = worldOf(on, { 'README.md': 'x' })const clock = mock.clock(on)diff --git a/scripts/ci-test-baseline.txt b/scripts/ci-test-baseline.txtindex 21edeb280f..ae4afe2720 100644--- a/scripts/ci-test-baseline.txt+++ b/scripts/ci-test-baseline.txt@@ -160,4 +160,5 @@ 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.tsplugins/ruflo-console/tests/behaviour.test.ts+plugins/ruflo-console/tests/palette.test.tsplugins/ruflo-console/tests/views.test.ts