🌊 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): cockpit mod with eight views, band, claims actions (WIP)
ruvd9bbe88ded25
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.jsonnew file mode 100644index 0000000000..f72e7bd728--- /dev/null+++ b/plugins/ruflo-console/.claude-plugin/plugin.json@@ -0,0 +1,46 @@+{+ "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.",+ "version": "0.1.0",+ "author": {+ "name": "ruvnet",+ "url": "https://github.com/ruvnet"+ },+ "homepage": "https://github.com/ruvnet/ruflo",+ "license": "MIT",+ "keywords": ["ruflo", "mods", "function-hooks", "pane", "console", "dashboard", "swarm", "claims", "federation", "metaharness"],+ "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"]+ },+ "refreshSeconds": {+ "type": "number",+ "title": "Disk refresh (seconds)",+ "description": "How often ruflo's files are re-read (2 to 60). Unchanged files are not read again. CLI probes keep their own slower cadence and run only for the view in front.",+ "default": 3+ },+ "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.",+ "default": 8+ },+ "bar": {+ "type": "string",+ "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"]+ },+ "federationNetwork": {+ "type": "boolean",+ "title": "Ask the federation relay",+ "description": "Lets the federation view ask the public relay (wss://relay.ruv.io) for the roster. Off by default: without it the console makes no network request.",+ "default": false+ }+ }+}diff --git a/plugins/ruflo-console/.gitignore b/plugins/ruflo-console/.gitignorenew file mode 100644index 0000000000..04f42e62f5--- /dev/null+++ b/plugins/ruflo-console/.gitignore@@ -0,0 +1,2 @@+# Claude Code writes its declarations here on load or validate (early access, regenerate per release)+.claude-plugin/types/diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.tsnew file mode 100644index 0000000000..ca354c085d--- /dev/null+++ b/plugins/ruflo-console/hooks/actions.ts@@ -0,0 +1,95 @@+/**+ * What the claims buttons ask ruflo to do, as fixed argv for `ruflo mcp exec -t claims_* -p <json>`: ids pass `idOf`,+ * the claimant strings are built here from parsed records, and the one JSON argument is `JSON.stringify`'s (an argv+ * element, never a shell string). Each spec says how the disk shows that it took, checked after the CLI exits.+ */+import { idOf, type AgentRecord, type ClaimRecord, type Claimant, type TaskRecord } from './data/parse'+import type { Snapshot } from './data/snapshot'++export type ActionSpec = {+ label: string+ args: readonly string[]+ expect: string+ verify: (snapshot: Snapshot) => boolean+}++const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const+const 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. */+export function claimantOf(who: Claimant): string | null {+ const id = idOf(who.id)+ const tail = who.kind === 'agent' ? who.agentType : who.name++ return id === null || id.includes(':') || tail === undefined || !SAFE_WORD.test(tail) ? null : `${who.kind}:${id}:${tail}`+}++export const agentClaimant = (agent: AgentRecord): string | null => claimantOf({ kind: 'agent', id: agent.id, agentType: agent.type })++export function claimTask(task: TaskRecord, agent: AgentRecord): ActionSpec | null {+ const issueId = idOf(task.id)+ const who = agentClaimant(agent)++ return issueId === null || who === null+ ? null+ : {+ label: `claim ${issueId} for ${agent.name ?? agent.type}`,+ args: exec('claims_claim', { issueId, claimant: who }),+ expect: 'the claim in .claude-flow/claims/claims.json',+ verify: snapshot => snapshot.claims.some(claim => claim.issueId === issueId && claim.claimant.id === agent.id),+ }+}++export function releaseClaim(claim: ClaimRecord): ActionSpec | null {+ const issueId = idOf(claim.issueId)+ const who = claimantOf(claim.claimant)++ return issueId === null || who === null+ ? null+ : {+ label: `release ${issueId} held by ${claim.claimant.agentType ?? claim.claimant.name ?? claim.claimant.id}`,+ args: exec('claims_release', { issueId, claimant: who, reason: 'released from ruflo-console' }),+ expect: 'the claim gone from claims.json',+ verify: snapshot => !snapshot.claims.some(entry => entry.issueId === issueId),+ }+}++export function handoffClaim(claim: ClaimRecord, to: AgentRecord): ActionSpec | null {+ const issueId = idOf(claim.issueId)+ const from = claimantOf(claim.claimant)+ const target = agentClaimant(to)++ return issueId === null || from === null || target === null || claim.claimant.id === to.id+ ? null+ : {+ label: `hand ${issueId} to ${to.name ?? to.type}`,+ args: exec('claims_handoff', { issueId, from, to: target, reason: 'handed off from ruflo-console' }),+ expect: 'a pending handoff on the claim',+ verify: snapshot => snapshot.claims.some(entry => entry.issueId === issueId && (entry.handoffTo === to.id || entry.claimant.id === to.id)),+ }+}++export function stealClaim(claim: ClaimRecord, by: AgentRecord): ActionSpec | null {+ const issueId = idOf(claim.issueId)+ const stealer = agentClaimant(by)++ return issueId === null || stealer === null || !claim.isStealable || claim.claimant.id === by.id+ ? null+ : {+ label: `steal ${issueId} for ${by.name ?? by.type}`,+ args: exec('claims_steal', { issueId, stealer }),+ expect: 'the claim held by the picked agent',+ verify: snapshot => snapshot.claims.some(entry => entry.issueId === issueId && entry.claimant.id === by.id),+ }+}++/** Why a button has nothing to act on, in the words the footer shows. */+export function whyNot(action: 'claim' | 'release' | 'handoff' | 'steal', claim: ClaimRecord | null, agent: AgentRecord | null, task: TaskRecord | null): string {+ if (action === 'claim') return task === null ? 'no unclaimed task to claim' : agent === null ? 'no agent to claim it for' : 'that task id or agent cannot be passed to ruflo'+ if (claim === null) return 'no claim picked'+ if (action === 'release') return 'that claimant cannot be named to ruflo'+ if (agent === null) return 'no agent picked (a)'+ if (agent.id === claim.claimant.id) return 'the picked agent already holds it'++ return action === 'steal' && !claim.isStealable ? 'the claim is not marked stealable' : 'that claim cannot be passed to ruflo'+}diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.tsnew file mode 100644index 0000000000..6587c6c780--- /dev/null+++ b/plugins/ruflo-console/hooks/controller.ts@@ -0,0 +1,378 @@+/**+ * 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.+ */+import { claimTask, handoffClaim, releaseClaim, stealClaim, whyNot, type ActionSpec } from './actions'+import { PROBES, type ProbeResult } from './data/cli'+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 type { Actions } from './views/common'+import { picturesOf } from './views/frames'+import { selection, openTasks } from './views/select'++const ACTIVITY_BUCKET_MS = 5_000+const PANE_WATCH_MS = 1_000+const PENDING_TTL_MS = 30_000+const MAX_PARALLEL_PROBES = 2++export type Controller = {+ refresh: () => Promise<void>+ probe: (force?: boolean) => Promise<void>+ start: () => void+ /** Restarts the pane's watch after a reload left the pane up and the timers gone. */+ resume: () => void+ stop: () => void+ open: (focus?: boolean) => Promise<{ isPlaced: boolean; reason: string }>+ close: () => Promise<void>+ setView: (view: State['view']) => void+ animate: () => void+ noteToolCall: () => void+ actions: Actions+ /** Blits the band's mark while Claude works; the band calls it with its requestId. */+ markFrame: (requestId: string, isWorking: boolean) => void+}++/** With the band off, the console's words ride ruflo-mods' status line instead: claims and a stale marketplace only. */+export function segmentOf(state: State): string | null {+ const claims = state.snapshot?.claims ?? []+ const parts = [claims.length > 0 ? `${claims.length} claims` : '', state.snapshot?.plugins.missingFromClone.length ? 'marketplace stale' : ''].filter(Boolean)++ return parts.length === 0 ? null : parts.join(' · ')+}++const sorted = (values: readonly number[]) => [...values].sort((a, b) => a - b)++export const median = (values: readonly number[]) => sorted(values)[Math.floor(values.length / 2)] ?? 0+export const p95 = (values: readonly number[]) => sorted(values)[Math.min(values.length - 1, Math.floor(values.length * 0.95))] ?? 0++export function createController(state: State, host: Host): Controller {+ let activityCount = 0+ let pendingSpec: ActionSpec | null = null+ let markRequest: string | null = null+ let lastSegment: string | null | undefined+ const lastAttempt = new Map<string, number>()++ const persist = () => void host.storeSet(storeKeyOf(state.cwd), { view: state.view }).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+ })++ return inflight+ }++ async function readAll(): Promise<void> {+ state.isRefreshing = true++ const started = Date.now()++ try {+ const [settings, usage, snapshot, route] = await Promise.all([+ host.settings().catch(() => null),+ host.usage().catch(() => null),+ host.rufloSnapshot().catch((error: unknown) => {+ state.ruflo.error = plain(String(error), 120)++ return null+ }),+ host.rufloRoute().catch(() => null),+ ])++ 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)++ if (state.options.bar === 'off') {+ const text = segmentOf(state)++ if (text !== lastSegment) {+ lastSegment = text+ void host.rufloSegment(text).catch(() => undefined)+ }+ }+ } catch (error) {+ state.ruflo.error = plain(String(error), 120)+ } finally {+ state.isRefreshing = false+ push(state.stats.refreshes, Date.now() - started, 200)+ host.invalidate()+ }+ }++ async function runProbe(probe: (typeof PROBES)[number]): Promise<void> {+ const held: ProbeResult = state.probes.get(probe.id) ?? { value: null, okAtMs: null, error: null, errorAtMs: null, isRunning: false }++ state.probes.set(probe.id, { ...held, isRunning: true })+ lastAttempt.set(probe.id, Date.now())++ try {+ const result = await host.run([...CLI_PREFIXES[state.options.cli], ...probe.args], probe.timeoutMs)+ const value = result.exitCode === 0 ? (probe.parse(result.stdout) as unknown) : null++ state.probes.set(+ probe.id,+ value !== null+ ? { value, okAtMs: Date.now(), error: null, errorAtMs: held.errorAtMs, isRunning: false }+ : {+ ...held,+ isRunning: false,+ errorAtMs: Date.now(),+ error: result.exitCode !== 0 ? `exit ${result.exitCode}: ${plain(result.stderr.split('\n').find(line => line.trim() !== '') ?? '', 100) || 'no message'}` : 'no JSON in the CLI output',+ },+ )+ } catch (error) {+ state.probes.set(probe.id, { ...held, isRunning: false, errorAtMs: Date.now(), error: plain(error instanceof Error ? error.message : String(error), 100) || 'refused' })+ } finally {+ host.invalidate()+ }+ }++ /** Runs the probes the view in front draws, each no more often than its cadence; `force` ignores the cadence. */+ async function probe(force = false): Promise<void> {+ const now = Date.now()+ const due = PROBES.filter(+ entry =>+ (isVisible() || force) &&+ entry.views.includes(state.view) &&+ (!entry.isNetwork || state.options.federationNetwork) &&+ state.probes.get(entry.id)?.isRunning !== true &&+ (force || now - (lastAttempt.get(entry.id) ?? 0) >= entry.everyMs),+ )++ for (let i = 0; i < due.length; i += MAX_PARALLEL_PROBES) {+ await Promise.all(due.slice(i, i + MAX_PARALLEL_PROBES).map(entry => runProbe(entry)))+ }+ }++ function every(name: string, ms: number, fn: () => void): void {+ if (!state.timers.has(name)) {+ state.timers.set(name, host.every(ms, fn))+ }+ }++ function cancel(name: string): void {+ state.timers.get(name)?.cancel()+ state.timers.delete(name)+ }++ /** 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) {+ const mounted = state.mounted.get(key)++ if (mounted !== undefined && mounted.columns === grid.columns && mounted.rows === grid.rows) {+ host.blit({ requestId: PANE_ID, key, cells: grid.encode(), columns: grid.columns, rows: grid.rows })+ }+ }++ push(state.stats.frames, Date.now() - started, 200)+ }++ /** 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) {+ cancel('frames')++ return+ }++ every('frames', Math.round(1000 / state.options.fps), frame)+ }++ /** Watches whether the pane is shown and focused, so the loop stops behind another tab and resumes in front. */+ async function watchPane(): Promise<void> {+ const panes = await host.panes().catch(() => null)+ const mine = panes?.find(pane => pane.id === PANE_ID)++ if (panes !== null) {+ state.pane.isOpen = mine !== undefined+ state.pane.isShown = mine?.isShown === true+ state.pane.isFocused = mine?.isFocused === true+ }++ if (!state.pane.isOpen) {+ cancel('watch')+ }++ animate()+ }++ function start(): void {+ every('refresh', state.options.refreshSeconds * 1000, () => {+ void refresh().then(() => probe())+ })+ every('activity', ACTIVITY_BUCKET_MS, () => {+ push(state.activity, activityCount)+ activityCount = 0+ })+ }++ function resume(): void {+ every('watch', PANE_WATCH_MS, () => void watchPane())+ }++ function stop(): void {+ for (const timer of state.timers.values()) timer.cancel()+ state.timers.clear()+ }++ 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 isPlaced = result === undefined || result.isPlaced !== false++ state.pane.isOpen = isPlaced+ state.pane.isShown = isPlaced+ every('watch', PANE_WATCH_MS, () => void watchPane())+ void refresh().then(() => probe(true))++ return { isPlaced, reason: result?.reason ?? '' }+ } catch (error) {+ return { isPlaced: false, reason: plain(error instanceof Error ? error.message : String(error), 160) }+ }+ }++ async function close(): Promise<void> {+ state.pane.isOpen = false+ state.pane.isShown = false+ cancel('frames')+ cancel('watch')+ await host.closePane(PANE_ID).catch(() => undefined)+ }++ function setView(view: State['view']): void {+ if (view !== state.view) {+ state.view = view+ state.isHelp = false+ state.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)+ 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()+ }++ 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) {+ 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 refresh()++ 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()+ }+ }++ const step = (key: keyof State['select'], by: number) => () => {+ state.select[key] += by+ host.invalidate()+ }++ const actions: Actions = {+ view: setView,+ refresh: () => void refresh().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))+ },+ }++ function markFrame(requestId: string, isWorking: boolean): void {+ markRequest = requestId++ if (isWorking && state.options.fps > 0) {+ every('mark', 120, () => {+ if (markRequest !== null) host.blit({ requestId: markRequest, key: 'mark', cells: markPicture(true, Date.now()).encode(), columns: 2, rows: 1 })+ })+ } else {+ cancel('mark')+ }+ }++ return { refresh, probe, start, resume, stop, open, close, setView, animate, noteToolCall: () => void (activityCount += 1), actions, markFrame }+}diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.tsnew file mode 100644index 0000000000..ddc8ae0e7f--- /dev/null+++ b/plugins/ruflo-console/hooks/data/cli.ts@@ -0,0 +1,327 @@+/**+ * The facts that are not on disk, asked of the ruflo CLI with fixed argv and read from its JSON. Every probe here was run+ * against @claude-flow/cli 3.50.0 and is local: none reaches the network except `roster`, which runs only when the+ * person turns `federationNetwork` on. `plugins list` is never run (it fetches the IPFS registry), nor `verify` (it+ * fetches a manifest from GitHub).+ */+import { jsonObject, msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'++export type ViewId = 'overview' | 'swarm' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory'++export type Probe<T> = {+ id: string+ args: readonly string[]+ /** The views that draw it: a probe runs only while one of them is in front (the overview's run with the bar too). */+ views: readonly ViewId[]+ everyMs: number+ timeoutMs: number+ isNetwork?: boolean+ parse: (stdout: string) => T | null+}++/** The JSON a CLI run printed: after `Result:` for `mcp exec`, else from the first line that opens an object or array. */+export function jsonAfter(stdout: string): unknown {+ const text = stdout.length > 1_000_000 ? stdout.slice(0, 1_000_000) : stdout+ const marker = text.indexOf('Result:')+ const from = marker >= 0 ? marker + 7 : 0+ const line = /^[ \t]*[[{]/m.exec(text.slice(from))+ const start = line === null ? -1 : from + line.index++ if (start < 0) {+ return null+ }++ const end = Math.max(text.lastIndexOf('}'), text.lastIndexOf(']'))++ try {+ return JSON.parse(text.slice(start, end + 1))+ } catch {+ return null+ }+}++const objectOf = (stdout: string) => recordOf(jsonAfter(stdout))+const exec = (tool: string, params: Record<string, unknown>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const++export const versionProbe: Probe<string> = {+ id: 'version',+ args: ['--version'],+ views: ['overview'],+ everyMs: 600_000,+ timeoutMs: 30_000,+ parse: stdout => /v?(\d+\.\d+\.\d+[\w.-]*)/.exec(stdout)?.[1] ?? null,+}++export type MemoryStats = { backend: string; total?: number; vectors?: number; storage?: string; oldestMs?: number; newestMs?: number }++export const memoryProbe: Probe<MemoryStats> = {+ id: 'memory',+ args: ['memory', 'stats', '--format', 'json'],+ views: ['overview', 'memory'],+ everyMs: 30_000,+ timeoutMs: 30_000,+ parse: stdout => {+ const value = objectOf(stdout)++ if (value === null) {+ return null+ }++ const entries = recordOf(value.entries)+ const stats: MemoryStats = { backend: stringOf(value.backend, 60) ?? 'unknown' }+ const total = numberOf(entries?.total)+ const vectors = numberOf(entries?.vectors)+ const storage = stringOf(recordOf(value.storage)?.total, 30)+ const oldestMs = msOf(value.oldestEntry)+ const newestMs = msOf(value.newestEntry)++ if (total !== undefined) stats.total = total+ if (vectors !== undefined) stats.vectors = vectors+ if (storage !== undefined) stats.storage = storage+ if (oldestMs !== undefined) stats.oldestMs = oldestMs+ if (newestMs !== undefined) stats.newestMs = newestMs++ return stats+ },+}++export type Namespaces = { sampled: number; byName: { name: string; count: number }[] }++/** Namespaces of the newest 500 entries: a sample, and the view says so. */+export const namespacesProbe: Probe<Namespaces> = {+ id: 'namespaces',+ args: ['memory', 'list', '--format', 'json', '--limit', '500'],+ views: ['memory'],+ everyMs: 60_000,+ timeoutMs: 30_000,+ parse: stdout => {+ const value = jsonAfter(stdout)++ if (!Array.isArray(value)) {+ return null+ }++ const counts = new Map<string, number>()++ for (const entry of value.slice(0, 500)) {+ const name = stringOf(recordOf(entry)?.namespace, 40) ?? '(none)'++ counts.set(name, (counts.get(name) ?? 0) + 1)+ }++ return { sampled: Math.min(500, value.length), byName: [...counts].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count).slice(0, 12) }+ },+}++export type HarnessScore = { dims: { name: string; value: number }[]; costUsd?: number; archetype?: string; scaffoldReady?: boolean; constraints?: string; atMs?: number }++const DIMS = ['harnessFit', 'compileConfidence', 'taskCoverage', 'toolSafety', 'memoryUsefulness'] as const++export const scoreProbe: Probe<HarnessScore> = {+ id: 'metaharness',+ args: ['metaharness', 'score', '--format', 'json'],+ views: ['metaharness'],+ everyMs: 120_000,+ timeoutMs: 60_000,+ parse: stdout => {+ const value = objectOf(stdout)+ const dims = DIMS.flatMap(name => {+ const score = numberOf(value?.[name])++ return score === undefined ? [] : [{ name, value: Math.max(0, Math.min(100, score)) }]+ })++ if (value === null || dims.length === 0) {+ return null+ }++ const score: HarnessScore = { dims }+ const costUsd = numberOf(value.estCostPerRunUsd)+ const archetype = stringOf(value.archetype, 40)+ const constraints = stringOf(value.hardConstraints, 10)+ const atMs = msOf(value.generatedAt)++ if (costUsd !== undefined) score.costUsd = costUsd+ if (archetype !== undefined) score.archetype = archetype+ if (typeof value.scaffoldReady === 'boolean') score.scaffoldReady = value.scaffoldReady+ if (constraints !== undefined) score.constraints = constraints+ if (atMs !== undefined) score.atMs = atMs++ return score+ },+}++export type Flywheel = { isLedgerValid: boolean; commits: number; receipts: number; champion?: string; epoch?: number; errors: string[] }++export const flywheelProbe: Probe<Flywheel> = {+ id: 'flywheel',+ args: exec('metaharness_flywheel', { op: 'receipts' }),+ views: ['metaharness'],+ everyMs: 60_000,+ timeoutMs: 30_000,+ parse: stdout => {+ const data = recordOf(objectOf(stdout)?.data)+ const state = recordOf(data?.state)+ const ledger = recordOf(data?.ledger)++ if (data === null || ledger === null) {+ return null+ }++ const flywheel: Flywheel = {+ isLedgerValid: ledger.valid === true,+ commits: numberOf(ledger.commits) ?? 0,+ receipts: Object.keys(recordOf(state?.receiptStates) ?? {}).length,+ errors: (Array.isArray(ledger.errors) ? ledger.errors : []).slice(0, 3).map(error => plain(error, 100)),+ }+ const champion = stringOf(state?.activeChampionRef, 80)+ const epoch = numberOf(state?.servingEpoch)++ if (champion !== undefined) flywheel.champion = champion+ if (epoch !== undefined) flywheel.epoch = epoch++ return flywheel+ },+}++export type Intelligence = { trajectories?: number; patterns?: number; successRate?: number; moeDecisions?: number; ewcConsolidations?: number; routerDecisions?: number; routerConfidence?: number; neuralRouter?: string }++export const intelligenceProbe: Probe<Intelligence> = {+ id: 'intelligence',+ args: exec('hooks_intelligence_stats', {}),+ views: ['learning'],+ everyMs: 30_000,+ timeoutMs: 30_000,+ parse: stdout => {+ const value = objectOf(stdout)++ if (value === null) {+ return null+ }++ const sona = recordOf(value.sona)+ const router = recordOf(value.modelRouter)+ const neural = recordOf(value.neuralRouter)+ const routerDecisions = numberOf(router?.totalDecisions)+ const out: Intelligence = {}+ const trajectories = numberOf(sona?.trajectoriesTotal)+ const patterns = numberOf(sona?.patternsLearned)+ const successRate = numberOf(sona?.successRate)+ const moeDecisions = numberOf(recordOf(value.moe)?.routingDecisions)+ const ewc = numberOf(recordOf(value.ewc)?.consolidations)++ if (trajectories !== undefined) out.trajectories = trajectories+ if (patterns !== undefined) out.patterns = patterns+ if (successRate !== undefined && (trajectories ?? 0) > 0) out.successRate = successRate+ if (moeDecisions !== undefined) out.moeDecisions = moeDecisions+ if (ewc !== undefined) out.ewcConsolidations = ewc+ if (routerDecisions !== undefined) out.routerDecisions = routerDecisions+ // The tool answers a default confidence before the first decision: only a measured one is kept.+ if (routerDecisions !== undefined && routerDecisions > 0 && numberOf(router?.avgConfidence) !== undefined) out.routerConfidence = numberOf(router?.avgConfidence) as number+ if (neural !== null) out.neuralRouter = neural.enabled === true ? 'on' : `off (${plain(neural.reason, 40) || 'not enabled'})`++ return out+ },+}++export type Peers = { peers: { id: string; lastSyncMs?: number }[]; degraded?: string }++export const peersProbe: Probe<Peers> = {+ id: 'peers',+ args: exec('federation_bbs_peers', {}),+ views: ['federation'],+ everyMs: 60_000,+ timeoutMs: 30_000,+ parse: stdout => {+ const value = objectOf(stdout)++ if (value === null) {+ return null+ }++ const list = Array.isArray(value.peers) ? value.peers : valuesOf(value.peers)+ const peers = list.slice(0, 50).flatMap(entry => {+ const peer = recordOf(entry)+ const id = stringOf(peer?.nodeId ?? peer?.id ?? peer?.name, 40)+ const lastSyncMs = msOf(peer?.lastSyncAt ?? peer?.lastSync)++ return id === undefined ? [] : [{ id, ...(lastSyncMs !== undefined && { lastSyncMs }) }]+ })++ return value.degraded === true ? { peers, degraded: stringOf(value.reason, 60) ?? 'degraded' } : { peers }+ },+}++export type Channels = { channels: { id: string; name?: string; atMs?: number }[] }++/** The channel list answers ids, names and dates; the keys stay in ~/.ruflo/channels.json, which the console never reads. */+export const channelsProbe: Probe<Channels> = {+ id: 'channels',+ args: exec('x_federation_channel_list', {}),+ views: ['federation'],+ everyMs: 60_000,+ timeoutMs: 30_000,+ parse: stdout => {+ const value = objectOf(stdout)++ if (value === null || !Array.isArray(value.channels)) {+ return null+ }++ return {+ channels: value.channels.slice(0, 50).flatMap(entry => {+ const channel = recordOf(entry)+ const id = stringOf(channel?.channel, 24)+ const name = stringOf(channel?.name, 40)+ const atMs = msOf(channel?.at)++ return id === undefined ? [] : [{ id, ...(name !== undefined && { name }), ...(atMs !== undefined && { atMs }) }]+ }),+ }+ },+}++export type Roster = { members: { name: string; detail?: string }[]; relay?: string; atMs?: number }++/** Reaches wss://relay.ruv.io: runs only with `federationNetwork` on. What it returns is third parties' text. */+export const rosterProbe: Probe<Roster> = {+ id: 'roster',+ args: exec('x_federation_roster', {}),+ views: ['federation'],+ everyMs: 120_000,+ timeoutMs: 45_000,+ isNetwork: true,+ parse: stdout => {+ const value = objectOf(stdout)++ if (value === null) {+ return null+ }++ const data = value.data+ const rows = Array.isArray(data) ? data : Object.entries(recordOf(data) ?? {}).map(([name, detail]) => ({ name, detail }))+ const relay = stringOf(value.relay, 60)+ const atMs = msOf(value.retrievedAt)++ return {+ members: rows.slice(0, 40).flatMap(entry => {+ const row = recordOf(entry)+ const name = stringOf(row?.name ?? row?.pubkey ?? row?.id, 32)+ const detail = typeof row?.detail === 'string' ? plain(row.detail, 60) : stringOf(recordOf(row?.detail)?.about, 60)++ return name === undefined ? [] : [{ name, ...(detail !== undefined && detail !== '' && { detail }) }]+ }),+ ...(relay !== undefined && { relay }),+ ...(atMs !== undefined && { atMs }),+ }+ },+}++export const PROBES = [versionProbe, memoryProbe, namespacesProbe, scoreProbe, flywheelProbe, intelligenceProbe, peersProbe, channelsProbe, rosterProbe] as const++export type ProbeId = (typeof PROBES)[number]['id']++/** What a probe came to: the last good value and when, and the last error, so a failing source is never drawn as live. */+export type ProbeResult<T = unknown> = { value: T | null; okAtMs: number | null; error: string | null; errorAtMs: number | null; isRunning: boolean }++export const emptyResult = (): ProbeResult => ({ value: null, okAtMs: null, error: null, errorAtMs: null, isRunning: false })diff --git a/plugins/ruflo-console/hooks/data/facts.ts b/plugins/ruflo-console/hooks/data/facts.tsnew file mode 100644index 0000000000..dae9e8e470--- /dev/null+++ b/plugins/ruflo-console/hooks/data/facts.ts@@ -0,0 +1,246 @@+/**+ * Readers for the non-swarm facts on disk: self-learning stores, the daemon's state, MetaHarness's active policy, the+ * helpers manifest, and Claude Code's own plugin records. Same rules as ./parse: any shape tolerated, nothing guessed,+ * every string cleaned. A value a file does not hold is absent, and the view says n/a.+ */+import { jsonObject, msOf, numberOf, plain, recordOf, stringOf } from './parse'++export type NeuralStats = { trajectories?: number; patterns?: number; signals?: number; lastAdaptationMs?: number }++/** `.claude-flow/neural/stats.json`, written by the hooks' learning pass. */+export function parseNeural(text: string | null): NeuralStats | null {+ const value = jsonObject(text)++ if (value === null) {+ return null+ }++ const stats: NeuralStats = {}+ const trajectories = numberOf(value.trajectoriesRecorded)+ const patterns = numberOf(value.patternsLearned)+ const signals = numberOf(value.signalsProcessed)+ const last = msOf(value.lastAdaptation)++ if (trajectories !== undefined) stats.trajectories = trajectories+ if (patterns !== undefined) stats.patterns = patterns+ if (signals !== undefined) stats.signals = signals+ if (last !== undefined) stats.lastAdaptationMs = last++ return stats+}++export type RouterState = { decisions?: number; distribution: { model: string; count: number }[]; avgConfidence?: number; updatedMs?: number; history: { ok: boolean; atMs: number }[] }++/** `.swarm/model-router-state.json`: the model tier router's tallies and its recent outcomes. */+export function parseRouter(text: string | null): RouterState | null {+ const value = jsonObject(text)++ if (value === null) {+ return null+ }++ const distribution = Object.entries(recordOf(value.modelDistribution) ?? {})+ .slice(0, 12)+ .flatMap(([model, count]) => (numberOf(count) !== undefined ? [{ model: plain(model, 20), count: numberOf(count) as number }] : []))+ const history = (Array.isArray(value.learningHistory) ? value.learningHistory : []).slice(-200).flatMap(entry => {+ const row = recordOf(entry)+ const atMs = msOf(row?.timestamp)++ return row === null || atMs === undefined || typeof row.outcome !== 'string' ? [] : [{ ok: row.outcome === 'success', atMs }]+ })+ const state: RouterState = { distribution, history }+ const decisions = numberOf(value.totalDecisions)+ const confidence = numberOf(value.avgConfidence)+ const updated = msOf(value.lastUpdated)++ if (decisions !== undefined) state.decisions = decisions+ if (confidence !== undefined) state.avgConfidence = confidence+ if (updated !== undefined) state.updatedMs = updated++ return state+}++export type Outcomes = { total: number; successes: number; points: { ok: boolean; quality?: number; agent: string; atMs: number }[] }++/** `.claude-flow/routing-outcomes.json`: what each routed task came to, oldest first. */+export function parseOutcomes(text: string | null): Outcomes | null {+ const value = jsonObject(text)++ if (value === null || !Array.isArray(value.outcomes)) {+ return null+ }++ const points = value.outcomes.slice(-500).flatMap(entry => {+ const row = recordOf(entry)+ const atMs = msOf(row?.timestamp)++ if (row === null || atMs === undefined || typeof row.success !== 'boolean') {+ return []+ }++ const quality = numberOf(row.quality)++ return [{ ok: row.success, agent: stringOf(row.agent, 30) ?? '?', atMs, ...(quality !== undefined && { quality }) }]+ })++ points.sort((a, b) => a.atMs - b.atMs)++ return { total: points.length, successes: points.filter(point => point.ok).length, points }+}++/** `.swarm/sona-patterns.json`: how many routing patterns SONA keeps. */+export function parseSona(text: string | null): { patterns: number } | null {+ const value = jsonObject(text)++ return value === null ? null : { patterns: Object.keys(recordOf(value.patterns) ?? {}).length }+}++export type Daemon = { running: boolean; savedAtMs?: number; workers: { name: string; runs: number; failures: number; lastRunMs?: number }[] }++/** `.claude-flow/daemon-state.json`: what the daemon last wrote. `running` is its own word, as of `savedAtMs`. */+export function parseDaemon(text: string | null): Daemon | null {+ const value = jsonObject(text)++ if (value === null) {+ return null+ }++ const workers = Object.entries(recordOf(value.workers) ?? {})+ .slice(0, 24)+ .flatMap(([name, entry]) => {+ const worker = recordOf(entry)+ const lastRunMs = msOf(worker?.lastRun)++ return worker === null+ ? []+ : [{ name: plain(name, 20), runs: numberOf(worker.runCount) ?? 0, failures: numberOf(worker.failureCount) ?? 0, ...(lastRunMs !== undefined && { lastRunMs }) }]+ })+ const daemon: Daemon = { running: value.running === true, workers }+ const savedAtMs = msOf(value.savedAt) ?? msOf(value.startedAt)++ if (savedAtMs !== undefined) daemon.savedAtMs = savedAtMs++ return daemon+}++/** `.claude-flow/harness-active-policy.json`: the MetaHarness champion this project serves, by its own word. */+export function parseHarnessPolicy(text: string | null): { champion: string; tier?: string; layer?: string; appliedAtMs?: number } | null {+ const value = jsonObject(text)+ const champion = stringOf(value?.championId, 90)++ if (value === null || champion === undefined) {+ return null+ }++ const tier = stringOf(value.provenanceTier, 40)+ const layer = stringOf(value.layer, 40)+ const appliedAtMs = msOf(value.appliedAt)++ return { champion, ...(tier !== undefined && { tier }), ...(layer !== undefined && { layer }), ...(appliedAtMs !== undefined && { appliedAtMs }) }+}++/** `.claude/helpers/helpers.manifest.json`: the signed list of helper files. The console reads it; it does not verify the signature. */+export function parseHelpers(text: string | null): { version: string; files: string[]; algorithm?: string; isSigned: boolean } | null {+ const value = jsonObject(text)+ const manifest = recordOf(value?.manifest)++ if (value === null || manifest === null) {+ return null+ }++ const files = Object.keys(recordOf(manifest.files) ?? {})+ .filter(name => /^[A-Za-z0-9._-]{1,80}$/.test(name))+ .slice(0, 40)+ const algorithm = stringOf(value.algorithm, 20)++ return { version: stringOf(manifest.version, 20) ?? 'unknown', files, isSigned: typeof value.signature === 'string' && value.signature.length > 20, ...(algorithm !== undefined && { algorithm }) }+}++export type Installed = { id: string; name: string; marketplace: string; version: string; scope: string; updatedMs?: number }++/** `~/.claude/plugins/installed_plugins.json` (version 2): every installed plugin, `name@marketplace`. */+export function parseInstalled(text: string | null): Installed[] | null {+ const value = jsonObject(text)+ const plugins = recordOf(value?.plugins)++ if (value === null || plugins === null) {+ return null+ }++ return Object.entries(plugins)+ .slice(0, 400)+ .flatMap(([id, entries]) => {+ const [name, marketplace] = id.split('@')+ const entry = recordOf(Array.isArray(entries) ? entries[0] : entries)++ if (entry === null || name === undefined || marketplace === undefined || !/^[A-Za-z0-9._-]{1,80}$/.test(name) || !/^[A-Za-z0-9._-]{1,80}$/.test(marketplace)) {+ return []+ }++ const updatedMs = msOf(entry.lastUpdated)++ return [{ id: `${name}@${marketplace}`, name, marketplace, version: stringOf(entry.version, 30) ?? '?', scope: stringOf(entry.scope, 12) ?? '?', ...(updatedMs !== undefined && { updatedMs }) }]+ })+}++export type Marketplace = { name: string; location?: string; updatedMs?: number; isAutoUpdate: boolean }++/** `~/.claude/plugins/known_marketplaces.json`: each marketplace clone, where it is and when it was last pulled. */+export function parseMarketplaces(text: string | null): Marketplace[] | null {+ const value = jsonObject(text)++ if (value === null) {+ return null+ }++ return Object.entries(value)+ .slice(0, 50)+ .flatMap(([name, entry]) => {+ const market = recordOf(entry)+ const location = typeof market?.installLocation === 'string' ? market.installLocation : undefined+ const updatedMs = msOf(market?.lastUpdated)+ // Only an absolute path with no `..` is followed to the clone's manifest.+ const safeLocation = location !== undefined && location.startsWith('/') && !location.split('/').includes('..') && location.length < 400 ? location : undefined++ return market === null || !/^[A-Za-z0-9._-]{1,80}$/.test(name)+ ? []+ : [{ name, isAutoUpdate: market.autoUpdate === true, ...(safeLocation !== undefined && { location: safeLocation }), ...(updatedMs !== undefined && { updatedMs }) }]+ })+}++/** A marketplace clone's `.claude-plugin/marketplace.json`: the plugin names it offers. */+export function parseMarketplaceManifest(text: string | null): string[] | null {+ const value = jsonObject(text)++ if (value === null || !Array.isArray(value.plugins)) {+ return null+ }++ return value.plugins.slice(0, 400).flatMap(entry => {+ const name = recordOf(entry)?.name++ return typeof name === 'string' && /^[A-Za-z0-9._-]{1,80}$/.test(name) ? [name] : []+ })+}++/** The plugins `enabledPlugins` in the merged settings turns on, as `name@marketplace`. */+export function enabledOf(settings: unknown): Set<string> {+ const enabled = recordOf(recordOf(settings)?.enabledPlugins) ?? {}++ return new Set(Object.entries(enabled).flatMap(([id, on]) => (on === true && /^[A-Za-z0-9._-]{1,80}@[A-Za-z0-9._-]{1,80}$/.test(id) ? [id] : [])))+}++/** `.swarm/state.json` from `swarm start` names an objective and an agent plan; `.claude-flow/metrics/swarm-activity.json` a count. */+export function parseActivity(text: string | null): { agentCount?: number; isActive: boolean; atMs?: number } | null {+ const value = jsonObject(text)+ const swarm = recordOf(value?.swarm)++ if (value === null || swarm === null) {+ return null+ }++ const agentCount = numberOf(swarm.agent_count)+ const atMs = msOf(value.timestamp)++ return { isActive: swarm.active === true, ...(agentCount !== undefined && { agentCount }), ...(atMs !== undefined && { atMs }) }+}diff --git a/plugins/ruflo-console/hooks/data/files.ts b/plugins/ruflo-console/hooks/data/files.tsnew file mode 100644index 0000000000..91de7c8439--- /dev/null+++ b/plugins/ruflo-console/hooks/data/files.ts@@ -0,0 +1,131 @@+/**+ * The files the console reads, and one bounded, cached reader for them. Paths in PROJECT are relative to the session's+ * working directory; paths in HOME to the person's home directory. Every read may be refused, a refusal is a missing+ * fact, and a file over READ_MAX bytes is never read (`.claude-flow/policy/state.json` reaches 40 MB in a busy project).+ *+ * Never listed here, never read: `.claude-flow/federation/key-*.json`, `~/.ruflo/nostr.key` and `~/.ruflo/channels.json`+ * hold private keys. The console names the first by listing the folder and the second by `stat` alone.+ */++/** The `$.fs` calls a reader makes; each may reject. */+export type ReaderFs = {+ read: (path: string) => Promise<string>+ stat: (path: string) => Promise<{ mtimeMs?: number; size?: number } | undefined>+ list: (path: string) => Promise<readonly { name: string; kind?: string; size?: number; mtimeMs?: number }[]>+}++/** Larger files are not read: the engine refuses past 4 MiB, and parsing one this size on a timer stalls a hook. */+export const READ_MAX = 2_000_000++export const PROJECT = {+ swarm: '.claude-flow/swarm/swarm-state.json',+ pointer: '.swarm/state.json',+ agents: '.claude-flow/agents/store.json',+ tasks: '.claude-flow/tasks/store.json',+ claims: '.claude-flow/claims/claims.json',+ hive: '.claude-flow/hive-mind/state.json',+ activity: '.claude-flow/metrics/swarm-activity.json',+ daemon: '.claude-flow/daemon-state.json',+ neural: '.claude-flow/neural/stats.json',+ router: '.swarm/model-router-state.json',+ outcomes: '.claude-flow/routing-outcomes.json',+ sona: '.swarm/sona-patterns.json',+ harnessPolicy: '.claude-flow/harness-active-policy.json',+ helpersManifest: '.claude/helpers/helpers.manifest.json',+ helpersVersion: '.claude/helpers/.helpers-version',+ config: '.claude-flow/config.yaml',+} as const++export type ProjectKey = keyof typeof PROJECT++export const HOME = {+ installed: '.claude/plugins/installed_plugins.json',+ marketplaces: '.claude/plugins/known_marketplaces.json',+} as const++/** Folders listed by name only: the federation keys' node ids, never their content. */+export const FEDERATION_DIR = '.claude-flow/federation'+export const NOSTR_KEY = '.ruflo/nostr.key'++/** What one read came to: the text, or why there is none. */+export type Read = { text: string; mtimeMs: number } | { text: null; reason: 'missing' | 'too-large' | 'refused'; size?: number }++/** The text of each file as last read, by path, with the mtime and size it was read at. */+export type ReadCache = Map<string, { mtimeMs: number; size: number; text: string }>++/** Reads one file, unless its mtime and size match what was read last; stats first, so a huge file is never read. */+export async function readBounded(fs: ReaderFs, cache: ReadCache, path: string): Promise<Read> {+ let stat: { mtimeMs?: number; size?: number } | undefined++ try {+ stat = await fs.stat(path)+ } catch {+ cache.delete(path)++ return { text: null, reason: 'missing' }+ }++ const mtimeMs = stat?.mtimeMs ?? -1+ const size = stat?.size ?? -1++ if (size > READ_MAX) {+ cache.delete(path)++ return { text: null, reason: 'too-large', size }+ }++ const held = cache.get(path)++ if (held !== undefined && mtimeMs >= 0 && held.mtimeMs === mtimeMs && held.size === size) {+ return { text: held.text, mtimeMs }+ }++ try {+ const text = await fs.read(path)++ cache.set(path, { mtimeMs, size, text })++ return { text, mtimeMs }+ } catch {+ cache.delete(path)++ return { text: null, reason: 'refused' }+ }+}++/** Joins a root and a relative path with one slash. */+export const under = (root: string, path: string): string => `${root.replace(/\/+$/, '')}/${path}`++/** Every file the console reads, as text or the reason it has none, and how many changed since the last pass. */+export type DiskRead = { project: Record<ProjectKey, Read>; home: Record<keyof typeof HOME, Read>; changed: number; federationNodes: string[] | null; hasNostrKey: boolean | null }++/** Reads every file in parallel; nothing here rejects. `home` is null when the home directory is unknown. */+export async function readDisk(fs: ReaderFs, cache: ReadCache, cwd: string, home: string | null): Promise<DiskRead> {+ const before = new Map([...cache].map(([path, held]) => [path, held.mtimeMs]))+ const projectKeys = Object.keys(PROJECT) as ProjectKey[]+ const homeKeys = Object.keys(HOME) as (keyof typeof HOME)[]+ const missingHome: Read = { text: null, reason: 'missing' }+ const [projectReads, homeReads, federationNodes, hasNostrKey] = await Promise.all([+ Promise.all(projectKeys.map(key => readBounded(fs, cache, under(cwd, PROJECT[key])))),+ Promise.all(homeKeys.map(key => (home === null ? Promise.resolve(missingHome) : readBounded(fs, cache, under(home, HOME[key]))))),+ fs+ .list(under(cwd, FEDERATION_DIR))+ .then(entries => entries.flatMap(entry => (/^key-[A-Za-z0-9._-]{1,64}\.json$/.test(entry.name) ? [entry.name.slice(4, -5)] : [])).slice(0, 50))+ .catch(() => null),+ home === null ? Promise.resolve(null) : fs.stat(under(home, NOSTR_KEY)).then(() => true, () => false),+ ])+ const project = Object.fromEntries(projectKeys.map((key, i) => [key, projectReads[i] as Read])) as Record<ProjectKey, Read>+ const homeRecord = Object.fromEntries(homeKeys.map((key, i) => [key, homeReads[i] as Read])) as Record<keyof typeof HOME, Read>+ let changed = 0++ for (const [path, held] of cache) {+ if (before.get(path) !== held.mtimeMs) {+ changed += 1+ }+ }++ return { project, home: homeRecord, changed: before.size === 0 ? 0 : changed, federationNodes, hasNostrKey }+}++/** The text of a read, or null. */+export const textOf = (read: Read | undefined): string | null => (read !== undefined && read.text !== null ? read.text : null)diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.tsnew file mode 100644index 0000000000..d6e95a9406--- /dev/null+++ b/plugins/ruflo-console/hooks/data/parse.ts@@ -0,0 +1,306 @@+/**+ * Readers for the swarm files ruflo writes under `.claude-flow/` and `.swarm/`.+ *+ * Vendored from plugins/ruflo-swarm/hooks/reader/parse.ts (a mod may import only its own files), cut to what the console+ * draws, with the claim record extended by its timestamps and context. Every one takes text another process wrote, so+ * each tolerates any shape: what it cannot read is left out, never guessed. Nothing here keeps the hive's `hiveToken`.+ */++/** Text longer than this is not parsed: a store that size is not one the CLI wrote, and parsing it would stall a hook. */+export const MAX_TEXT = 4_000_000+/** At most this many records of one kind are kept; the rest are counted, not drawn. */+export const MAX_RECORDS = 1_000++const ID = /^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/++/** Plain printable text of at most `max` characters: no control or bidi-override characters reach the terminal. */+export function plain(value: unknown, max = 200): string {+ if (typeof value !== 'string') {+ return ''+ }++ const cleaned = value.replace(/[\u0000-\u001f\u007f-\u009f---]/g, ' ').replace(/\s+/g, ' ').trim()++ return cleaned.length <= max ? cleaned : `${cleaned.slice(0, Math.max(0, max - 1))}…`+}++/** An id as ruflo mints them (`agent-…`, `swarm-…`, `proposal-…`), or null: only such a string ever reaches an argv. */+export function idOf(value: unknown): string | null {+ return typeof value === 'string' && ID.test(value) ? value : null+}++export const numberOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)+export const stringOf = (value: unknown, max = 80): string | undefined => (typeof value === 'string' && value !== '' ? plain(value, max) || undefined : undefined)+export const recordOf = (value: unknown): Record<string, unknown> | null =>+ value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null++/** JSON text to a plain object, or null for anything else (too long, malformed, an array, a scalar). */+export function jsonObject(text: string | null | undefined): Record<string, unknown> | null {+ if (typeof text !== 'string' || text.length > MAX_TEXT) {+ return null+ }++ try {+ return recordOf(JSON.parse(text))+ } catch {+ return null+ }+}++export const valuesOf = (value: unknown): unknown[] => {+ const record = recordOf(value)++ return record === null ? [] : Object.values(record).slice(0, MAX_RECORDS)+}++/** An ISO time to epoch milliseconds, or undefined. */+export const msOf = (value: unknown): number | undefined => {+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {+ return value+ }++ const parsed = typeof value === 'string' ? Date.parse(value) : Number.NaN++ return Number.isFinite(parsed) ? parsed : undefined+}++export type SwarmInfo = { id: string; topology: string; status: string; maxAgents?: number; strategy?: string; agentIds: string[]; updatedAt?: string }+export type AgentRecord = { id: string; type: string; name?: string; status: string; health?: number; taskCount?: number; createdAtMs?: number }+export type TaskRecord = { id: string; type: string; description: string; status: string; assignedTo: string[] }+export type Claimant = { kind: 'agent' | 'human'; id: string; agentType?: string; name?: string }+export type ClaimRecord = {+ issueId: string+ status: string+ claimant: Claimant+ progress?: number+ handoffTo?: string+ isStealable: boolean+ claimedAtMs?: number+ changedAtMs?: number+ /** ruflo's claim type declares `expiresAt`, but no claims tool sets it today: absent means no TTL, not an expired one. */+ expiresAtMs?: number+ context?: string+}+export type Proposal = { id: string; type: string; status: string; strategy: string; votesFor: number; votesAgainst: number }+export type Decision = { id: string; type: string; result: string; votesFor: number; votesAgainst: number }+export type HiveInfo = { topology: string; strategy?: string; queen?: string; workers: string[]; pending: Proposal[]; history: Decision[] }++/** `.claude-flow/swarm/swarm-state.json`: the running swarm, else the one updated last. */+export function parseSwarmStore(text: string | null): SwarmInfo | null {+ const swarms = valuesOf(jsonObject(text)?.swarms).flatMap(entry => {+ const swarm = recordOf(entry)+ const id = idOf(swarm?.swarmId)++ if (swarm === null || id === null) {+ return []+ }++ const config = recordOf(swarm.config)+ const info: SwarmInfo = {+ id,+ topology: stringOf(swarm.topology, 40) ?? 'unknown',+ status: stringOf(swarm.status, 40) ?? 'unknown',+ agentIds: (Array.isArray(swarm.agents) ? swarm.agents : []).slice(0, MAX_RECORDS).flatMap(agent => {+ const agentId = idOf(agent) ?? idOf(recordOf(agent)?.agentId) ?? idOf(recordOf(agent)?.id)++ return agentId !== null ? [agentId] : []+ }),+ }+ const maxAgents = numberOf(swarm.maxAgents)+ const strategy = stringOf(config?.strategy, 40)+ const updatedAt = stringOf(swarm.updatedAt, 40)++ if (maxAgents !== undefined) info.maxAgents = maxAgents+ if (strategy !== undefined) info.strategy = strategy+ if (updatedAt !== undefined) info.updatedAt = updatedAt++ return [info]+ })+ const byRecency = (a: SwarmInfo, b: SwarmInfo) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')++ return [...swarms.filter(swarm => swarm.status === 'running')].sort(byRecency)[0] ?? [...swarms].sort(byRecency)[0] ?? null+}++/** `.swarm/state.json`: the pointer `swarm init` (or `swarm start`) leaves. */+export function parseSwarmPointer(text: string | null): { id: string; topology?: string; strategy?: string; status?: string } | null {+ const value = jsonObject(text)+ const id = idOf(value?.id) ?? idOf(value?.swarmId)++ if (value === null || id === null) {+ return null+ }++ const pointer: { id: string; topology?: string; strategy?: string; status?: string } = { id }+ const topology = stringOf(value.topology, 40)+ const strategy = stringOf(value.strategy, 40)+ const status = stringOf(value.status, 40)++ if (topology !== undefined) pointer.topology = topology+ if (strategy !== undefined) pointer.strategy = strategy+ if (status !== undefined) pointer.status = status++ return pointer+}++/** `.claude-flow/agents/store.json`. */+export function parseAgents(text: string | null): AgentRecord[] {+ return valuesOf(jsonObject(text)?.agents).flatMap(entry => {+ const agent = recordOf(entry)+ const id = idOf(agent?.agentId)++ if (agent === null || id === null) {+ return []+ }++ const record: AgentRecord = { id, type: stringOf(agent.agentType, 40) ?? 'agent', status: stringOf(agent.status, 20) ?? 'unknown' }+ const name = stringOf(agent.name, 40)+ const health = numberOf(agent.health)+ const taskCount = numberOf(agent.taskCount)+ const createdAtMs = msOf(agent.createdAt)++ if (name !== undefined) record.name = name+ if (health !== undefined) record.health = health+ if (taskCount !== undefined) record.taskCount = taskCount+ if (createdAtMs !== undefined) record.createdAtMs = createdAtMs++ return [record]+ })+}++/** `.claude-flow/tasks/store.json`. */+export function parseTasks(text: string | null): TaskRecord[] {+ return valuesOf(jsonObject(text)?.tasks).flatMap(entry => {+ const task = recordOf(entry)+ const id = idOf(task?.taskId)++ return task === null || id === null+ ? []+ : [+ {+ id,+ type: stringOf(task.type, 40) ?? 'task',+ description: plain(task.description, 200),+ status: stringOf(task.status, 20) ?? 'unknown',+ assignedTo: (Array.isArray(task.assignedTo) ? task.assignedTo : []).slice(0, 50).flatMap(agent => (idOf(agent) !== null ? [agent as string] : [])),+ },+ ]+ })+}++function claimantOf(value: unknown): Claimant | null {+ const claimant = recordOf(value)++ if (claimant === null) {+ return null+ }++ const isAgent = claimant.type === 'agent'+ const id = idOf(isAgent ? claimant.agentId : claimant.userId)++ if (id === null) {+ return null+ }++ const who: Claimant = { kind: isAgent ? 'agent' : 'human', id }+ const agentType = stringOf(claimant.agentType, 40)+ const name = stringOf(claimant.name, 40)++ if (agentType !== undefined) who.agentType = agentType+ if (name !== undefined) who.name = name++ return who+}++/** `.claude-flow/claims/claims.json`: issue claims (who works on what), not the authorization file `.claude-flow/claims.json`. */+export function parseClaims(text: string | null): ClaimRecord[] {+ const store = jsonObject(text)+ const stealable = recordOf(store?.stealable) ?? {}++ return valuesOf(store?.claims).flatMap(entry => {+ const claim = recordOf(entry)+ const issueId = idOf(claim?.issueId)+ const claimant = claimantOf(claim?.claimant)++ if (claim === null || issueId === null || claimant === null) {+ return []+ }++ const handoff = recordOf(claim.handoffTo)+ const handoffTo = idOf(handoff?.agentId ?? handoff?.userId)+ const record: ClaimRecord = {+ issueId,+ status: stringOf(claim.status, 30) ?? 'unknown',+ claimant,+ isStealable: claim.status === 'stealable' || Object.hasOwn(stealable, issueId),+ }+ const progress = numberOf(claim.progress)+ const claimedAtMs = msOf(claim.claimedAt)+ const changedAtMs = msOf(claim.statusChangedAt)+ const expiresAtMs = msOf(claim.expiresAt)+ const context = stringOf(claim.context, 120)++ if (progress !== undefined) record.progress = Math.max(0, Math.min(100, progress))+ if (handoffTo !== null) record.handoffTo = handoffTo+ if (claimedAtMs !== undefined) record.claimedAtMs = claimedAtMs+ if (changedAtMs !== undefined) record.changedAtMs = changedAtMs+ if (expiresAtMs !== undefined) record.expiresAtMs = expiresAtMs+ if (context !== undefined) record.context = context++ return [record]+ })+}++const votesOf = (value: unknown): { votesFor: number; votesAgainst: number } => {+ const votes = valuesOf(value)++ return { votesFor: votes.filter(vote => vote === true).length, votesAgainst: votes.filter(vote => vote === false).length }+}++/** `.claude-flow/hive-mind/state.json`, without its capability token. */+export function parseHive(text: string | null): HiveInfo | null {+ const hive = jsonObject(text)++ if (hive === null || hive.initialized !== true) {+ return null+ }++ const queen = idOf(recordOf(hive.queen)?.agentId)+ const consensus = recordOf(hive.consensus)+ const pending = (Array.isArray(consensus?.pending) ? consensus.pending : []).slice(-50).flatMap(entry => {+ const proposal = recordOf(entry)+ const id = idOf(proposal?.proposalId)++ return proposal === null || id === null+ ? []+ : [+ {+ id,+ type: stringOf(proposal.type, 40) ?? 'proposal',+ status: stringOf(proposal.status, 20) ?? 'pending',+ strategy: stringOf(proposal.strategy, 20) ?? 'unknown',+ ...votesOf(proposal.votes),+ },+ ]+ })+ const history = (Array.isArray(consensus?.history) ? consensus.history : []).slice(-50).flatMap(entry => {+ const decision = recordOf(entry)+ const id = idOf(decision?.proposalId)+ const votes = recordOf(decision?.votes)++ return decision === null || id === null+ ? []+ : [{ id, type: stringOf(decision.type, 40) ?? 'proposal', result: stringOf(decision.result, 20) ?? 'unknown', votesFor: numberOf(votes?.for) ?? 0, votesAgainst: numberOf(votes?.against) ?? 0 }]+ })+ const info: HiveInfo = {+ topology: stringOf(hive.topology, 40) ?? 'unknown',+ workers: (Array.isArray(hive.workers) ? hive.workers : []).slice(0, MAX_RECORDS).flatMap(worker => (idOf(worker) !== null ? [worker as string] : [])),+ pending,+ history,+ }+ const strategy = stringOf(hive.consensusStrategy, 30)++ if (strategy !== undefined) info.strategy = strategy+ if (queen !== null) info.queen = queen++ return info+}diff --git a/plugins/ruflo-console/hooks/data/snapshot.ts b/plugins/ruflo-console/hooks/data/snapshot.tsnew file mode 100644index 0000000000..39ce085d83--- /dev/null+++ b/plugins/ruflo-console/hooks/data/snapshot.ts@@ -0,0 +1,125 @@+/**+ * One snapshot of everything the console draws from disk: the files read (./files), parsed (./parse, ./facts), plus the+ * ruflo marketplace clone's manifest. A fact a file does not hold is null and its read's reason says why; the views+ * draw that as n/a, missing or too large, never as zero.+ */+import {+ enabledOf,+ parseActivity,+ parseDaemon,+ parseHarnessPolicy,+ parseHelpers,+ parseInstalled,+ parseMarketplaceManifest,+ parseMarketplaces,+ parseNeural,+ parseOutcomes,+ parseRouter,+ parseSona,+ type Daemon,+ type Installed,+ type Marketplace,+ type NeuralStats,+ type Outcomes,+ type RouterState,+} from './facts'+import { readBounded, readDisk, textOf, type ProjectKey, type Read, type ReadCache, type ReaderFs } from './files'+import {+ parseAgents,+ parseClaims,+ parseHive,+ parseSwarmPointer,+ parseSwarmStore,+ parseTasks,+ type AgentRecord,+ type ClaimRecord,+ type HiveInfo,+ type SwarmInfo,+ type TaskRecord,+} from './parse'++/** The marketplace this repository publishes, and the plugins a current clone of it must list. */+export const RUFLO_MARKET = 'ruflo'+export const EXPECTED_IN_MARKET = ['ruflo-core', 'ruflo-mods', 'ruflo-swarm'] as const++export type PluginsFacts = {+ installed: Installed[] | null+ enabled: Set<string>+ markets: Marketplace[] | null+ /** The ruflo clone's plugin names, or null when the clone or its manifest is not readable. */+ rufloOffered: string[] | null+ /** Expected plugins the clone does not list: non-empty means the clone is stale. */+ missingFromClone: string[]+}++export type Snapshot = {+ reads: Record<ProjectKey, ReadStatus>+ swarm: SwarmInfo | null+ agents: AgentRecord[]+ tasks: TaskRecord[]+ claims: ClaimRecord[]+ hive: HiveInfo | null+ activity: ReturnType<typeof parseActivity>+ daemon: Daemon | null+ neural: NeuralStats | null+ router: RouterState | null+ outcomes: Outcomes | null+ sona: { patterns: number } | null+ harnessPolicy: ReturnType<typeof parseHarnessPolicy>+ helpers: ReturnType<typeof parseHelpers>+ helpersVersion: string | null+ isRufloProject: boolean+ federationNodes: string[] | null+ hasNostrKey: boolean | null+ plugins: PluginsFacts+ changed: number+ readAtMs: number+}++export type ReadStatus = 'ok' | 'missing' | 'too-large' | 'refused'++const statusOf = (read: Read): ReadStatus => (read.text !== null ? 'ok' : read.reason)++/** Reads and parses everything; never rejects. `settings` is the merged settings, for `enabledPlugins`. */+export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string, home: string | null, settings: unknown, nowMs: number): Promise<Snapshot> {+ const disk = await readDisk(fs, cache, cwd, home)+ const text = (key: ProjectKey) => textOf(disk.project[key])+ const stored = parseSwarmStore(text('swarm'))+ const pointer = parseSwarmPointer(text('pointer'))+ const swarm: SwarmInfo | null =+ stored ?? (pointer !== null ? { id: pointer.id, topology: pointer.topology ?? 'unknown', status: pointer.status ?? 'unknown', agentIds: [], ...(pointer.strategy !== undefined && { strategy: pointer.strategy }) } : null)+ const markets = parseMarketplaces(textOf(disk.home.marketplaces))+ const location = markets?.find(market => market.name === RUFLO_MARKET)?.location+ const offered = location === undefined ? null : parseMarketplaceManifest(textOf(await readBounded(fs, cache, `${location}/.claude-plugin/marketplace.json`)))+ const reads = Object.fromEntries((Object.keys(disk.project) as ProjectKey[]).map(key => [key, statusOf(disk.project[key])])) as Snapshot['reads']++ return {+ reads,+ swarm,+ agents: parseAgents(text('agents')),+ tasks: parseTasks(text('tasks')),+ claims: parseClaims(text('claims')),+ hive: parseHive(text('hive')),+ activity: parseActivity(text('activity')),+ daemon: parseDaemon(text('daemon')),+ neural: parseNeural(text('neural')),+ router: parseRouter(text('router')),+ outcomes: parseOutcomes(text('outcomes')),+ sona: parseSona(text('sona')),+ harnessPolicy: parseHarnessPolicy(text('harnessPolicy')),+ helpers: parseHelpers(text('helpersManifest')),+ helpersVersion: text('helpersVersion')?.trim().slice(0, 20) ?? null,+ isRufloProject: text('config') !== null || swarm !== null || text('claims') !== null || text('daemon') !== null,+ federationNodes: disk.federationNodes,+ hasNostrKey: disk.hasNostrKey,+ plugins: {+ installed: parseInstalled(textOf(disk.home.installed)),+ enabled: enabledOf(settings),+ markets,+ rufloOffered: offered,+ missingFromClone: offered === null ? [] : EXPECTED_IN_MARKET.filter(name => !offered.includes(name)),+ },+ changed: disk.changed,+ readAtMs: nowMs,+ }+}diff --git a/plugins/ruflo-console/hooks/gfx/pictures.ts b/plugins/ruflo-console/hooks/gfx/pictures.tsnew file mode 100644index 0000000000..3ed54dac6d--- /dev/null+++ b/plugins/ruflo-console/hooks/gfx/pictures.ts@@ -0,0 +1,277 @@+/**+ * 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.+ */+import { Braille, COLOR, Grid, mix, ramp, sparkline } from './raster'++export type TopoNode = { id: string; label: string; status: string; isLeader: boolean }+export type TopoModel = { topology: string; nodes: TopoNode[] }++const 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 {+ if (node.isLeader) return COLOR.accent+ if (isDown(node.status)) return /error|fail/i.test(node.status) ? COLOR.bad : COLOR.dim+ if (isBusy(node.status)) return COLOR.warn++ return COLOR.info+}++/** Where each node sits, in braille dots, by topology: a tree for hierarchical and star, a circle for mesh and ring. */+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)++ if (n === 0) {+ return []+ }++ if (isTree || isHybrid) {+ const workers = Math.max(1, n - 1)++ 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) },+ )+ }++ const cx = width / 2+ const cy = height / 2+ const r = Math.max(4, Math.min(width / 2 - 6, height / 2 - 3))++ return model.nodes.map((_, i) => {+ const angle = -Math.PI / 2 + (i / n) * Math.PI * 2++ return { x: cx + Math.cos(angle) * r * 1.6, y: cy + Math.sin(angle) * r }+ })+}++/** The edges a topology draws between node indexes. */+export function edges(model: TopoModel): [number, number][] {+ const n = model.nodes.length+ const out: [number, number][] = []+ const topology = model.topology.toLowerCase()++ if (n < 2) {+ return out+ }++ if (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])+ } 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])+ }+ }++ return out.slice(0, 200)+}++/**+ * 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.+ */+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)++ for (const [a, b] of links) {+ const p = points[a]+ const q = points[b]++ 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+ }++ for (const lag of [0, 0.5]) {+ const k = (((t / 1400 + i * 0.13 + lag) % 1) + 1) % 1++ canvas.dot(p.x + (q.x - p.x) * k, p.y + (q.y - p.y) * k, COLOR.warn)+ }+ })++ canvas.blitInto(grid, 0, 0)++ points.forEach((point, i) => {+ const node = model.nodes[i]++ if (node === undefined) return++ 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))++ 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))+ })++ return grid+}++/**+ * Two measured series as sparklines with their labels: tool calls the console saw per 5 s, and ruflo state files that+ * changed per refresh. The newest bar glows while the pane animates: decoration over measured bars.+ */+export function activityPicture(series: readonly { label: string; values: readonly number[] }[], columns: number, t: number): Grid {+ const grid = new Grid(columns, Math.max(1, series.length))+ const labelWidth = Math.min(18, Math.max(8, ...series.map(entry => entry.label.length + 1)))+ const width = Math.max(4, columns - labelWidth)++ series.forEach((entry, row) => {+ grid.text(0, row, entry.label.slice(0, labelWidth - 1), COLOR.dim)+ sparkline(grid, labelWidth, row, width, entry.values, v => ramp(0.3 + v * 0.7))++ const 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))+ }+ })++ return grid+}++/**+ * 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.+ */+export function curvePicture(points: readonly boolean[], columns: number, rows: number, t: number): Grid {+ const grid = new Grid(columns, rows)+ const canvas = new Braille(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)+ }++ if (n === 0) {+ grid.text(6, Math.floor(rows / 2), 'no routed outcomes on disk yet', COLOR.dim)++ return grid+ }++ let ok = 0+ const rates = points.map((point, i) => {+ ok += point ? 1 : 0++ return ok / (i + 1)+ })+ const xOf = (i: number) => (n === 1 ? canvas.width / 2 : (i / (n - 1)) * (canvas.width - 1))+ const yOf = (rate: number) => (1 - rate) * (canvas.height - 1)++ 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))++ 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)}`++ grid.text(labelWidth + barWidth + 1, row, words.slice(0, textWidth), hasTtl && left <= 0 ? COLOR.bad : COLOR.dim)+ })++ 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)++ const filled = (dim.value / 100) * barWidth * eased++ 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))+ })++ 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/gfx/raster.ts b/plugins/ruflo-console/hooks/gfx/raster.tsnew file mode 100644index 0000000000..7cc56e473e--- /dev/null+++ b/plugins/ruflo-console/hooks/gfx/raster.ts@@ -0,0 +1,194 @@+/**+ * Cell graphics for the terminal's `Raster` element: a grid of glyphs with 24-bit colours, packed as base64 of+ * little-endian u32 triplets `[codePoint, fg, bg]`, row-major. Pure: no `$`, no Node (base64 is encoded by hand).+ */++/** The terminal's own colour, foreground or background. */+export const DEFAULT = 0x01000000++const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'++export function toBase64(bytes: Uint8Array): string {+ let out = ''+ let i = 0++ for (; i + 2 < bytes.length; i += 3) {+ const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8) | (bytes[i + 2] as number)++ out += (B64[(n >> 18) & 63] as string) + (B64[(n >> 12) & 63] as string) + (B64[(n >> 6) & 63] as string) + (B64[n & 63] as string)+ }++ if (bytes.length - i === 1) {+ const n = (bytes[i] as number) << 16++ out += `${B64[(n >> 18) & 63]}${B64[(n >> 12) & 63]}==`+ } else if (bytes.length - i === 2) {+ const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8)++ out += `${B64[(n >> 18) & 63]}${B64[(n >> 12) & 63]}${B64[(n >> 6) & 63]}=`+ }++ return out+}++export class Grid {+ readonly cells: Uint32Array++ constructor(+ readonly columns: number,+ readonly rows: number,+ ) {+ this.cells = new Uint32Array(Math.max(1, columns * rows) * 3)++ for (let i = 0; i < columns * rows; i++) {+ this.cells[i * 3] = 0x20+ this.cells[i * 3 + 1] = DEFAULT+ this.cells[i * 3 + 2] = DEFAULT+ }+ }++ set(x: number, y: number, ch: number | string, fg = DEFAULT, bg?: number): void {+ const cx = Math.floor(x)+ const cy = Math.floor(y)++ if (cx < 0 || cy < 0 || cx >= this.columns || cy >= this.rows) {+ return+ }++ const at = (cy * this.columns + cx) * 3++ this.cells[at] = typeof ch === 'number' ? ch : (ch.codePointAt(0) ?? 0x20)+ this.cells[at + 1] = fg >>> 0++ if (bg !== undefined) {+ this.cells[at + 2] = bg >>> 0+ }+ }++ glyph(x: number, y: number): number {+ return x < 0 || y < 0 || x >= this.columns || y >= this.rows ? 0x20 : (this.cells[(y * this.columns + x) * 3] as number)+ }++ /** Writes text left to right, clipped at the grid's edge. */+ text(x: number, y: number, text: string, fg = DEFAULT, bg?: number): void {+ let cx = x++ for (const ch of text) {+ this.set(cx, y, ch, fg, bg)+ cx += 1+ }+ }++ toRaster(key: string): { key: string; columns: number; rows: number; cells: string } {+ return { key, columns: this.columns, rows: this.rows, cells: this.encode() }+ }++ encode(): string {+ return toBase64(new Uint8Array(this.cells.buffer, this.cells.byteOffset, this.cells.byteLength))+ }+}++/** Linear blend of two 0xRRGGBB colours, `t` in 0..1. */+export function mix(a: number, b: number, t: number): number {+ const k = Math.max(0, Math.min(1, t))+ const channel = (shift: number) => Math.round(((a >> shift) & 255) * (1 - k) + ((b >> shift) & 255) * k)++ return (channel(16) << 16) | (channel(8) << 8) | channel(0)+}++/** A perceptual ramp for dark and light themes alike: indigo, cyan, emerald, amber. */+const RAMP = [0x3b3f9e, 0x2fa4c9, 0x2bb673, 0xe0a526] as const++export function ramp(t: number): number {+ const k = Math.max(0, Math.min(1, t)) * (RAMP.length - 1)+ const i = Math.min(RAMP.length - 2, Math.floor(k))++ return mix(RAMP[i] as number, RAMP[i + 1] as number, k - i)+}++export const COLOR = {+ accent: 0x8b7cf6,+ ok: 0x2bb673,+ warn: 0xe0a526,+ bad: 0xe5534b,+ info: 0x2fa4c9,+ dim: 0x6b7280,+ line: 0x4b5563,+} as const++const BARS = ' ▁▂▃▄▅▆▇█'++/** A one-row bar sparkline of `values` (newest right), scaled to its own max; an empty series draws the baseline. */+export function sparkline(grid: Grid, x: number, y: number, width: number, values: readonly number[], color: (t: number) => number): void {+ const shown = values.slice(-width)+ const max = Math.max(1, ...shown)+ const offset = width - shown.length++ for (let i = 0; i < width; i++) {+ const value = i < offset ? 0 : (shown[i - offset] ?? 0)+ const level = value <= 0 ? 0 : Math.max(1, Math.round((value / max) * 8))++ grid.set(x + i, y, level === 0 ? '▁' : (BARS[level] as string), level === 0 ? COLOR.line : color(value / max))+ }+}++/** A canvas of braille dots over a grid region: each cell is 2 dots wide and 4 high. */+export class Braille {+ readonly bits: Uint8Array+ readonly colors: Uint32Array++ constructor(+ readonly columns: number,+ readonly rows: number,+ ) {+ this.bits = new Uint8Array(columns * rows)+ this.colors = new Uint32Array(columns * rows)+ }++ get width(): number {+ return this.columns * 2+ }++ get height(): number {+ return this.rows * 4+ }++ dot(px: number, py: number, color: number): void {+ const x = Math.round(px)+ const y = Math.round(py)++ if (x < 0 || y < 0 || x >= this.width || y >= this.height) {+ return+ }++ const cell = Math.floor(y / 4) * this.columns + Math.floor(x / 2)+ const dx = x % 2+ const dy = y % 4+ const bit = dy < 3 ? (dx === 0 ? [0x01, 0x02, 0x04][dy] : [0x08, 0x10, 0x20][dy]) : dx === 0 ? 0x40 : 0x80++ this.bits[cell] = (this.bits[cell] as number) | (bit as number)+ this.colors[cell] = color+ }++ line(x0: number, y0: number, x1: number, y1: number, color: number): void {+ const steps = Math.max(1, Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0))))++ for (let i = 0; i <= steps; i++) {+ this.dot(x0 + ((x1 - x0) * i) / steps, y0 + ((y1 - y0) * i) / steps, color)+ }+ }++ /** Paints the dots into `grid` at (x, y); cells with no dot are left as they are. */+ blitInto(grid: Grid, x: number, y: number): void {+ for (let row = 0; row < this.rows; row++) {+ for (let col = 0; col < this.columns; col++) {+ const i = row * this.columns + col+ const bits = this.bits[i] as number++ if (bits !== 0) {+ grid.set(x + col, y + row, 0x2800 + bits, this.colors[i] as number)+ }+ }+ }+ }+}diff --git a/plugins/ruflo-console/hooks/hooks.json b/plugins/ruflo-console/hooks/hooks.jsonnew file mode 100644index 0000000000..5368975934--- /dev/null+++ b/plugins/ruflo-console/hooks/hooks.json@@ -0,0 +1,4 @@+{+ "description": "The ruflo console: a live cockpit pane (overview, swarms, claims, federation, plugins, self-learning, MetaHarness, memory and cost) and a one-line band above the prompt. Without function hooks nothing here loads.",+ "modules": ["./register.ts"]+}diff --git a/plugins/ruflo-console/hooks/host.ts b/plugins/ruflo-console/hooks/host.tsnew file mode 100644index 0000000000..19f0f07766--- /dev/null+++ b/plugins/ruflo-console/hooks/host.ts@@ -0,0 +1,35 @@+import type { CommandSpec, PaneOpenArgs, ProcessRunResult, Timer, UiBlitArgs } from 'claude-code'++import type { ReaderFs } from './data/files'+import type { RufloRoute, RufloSnapshot } from '../types'++/** What `$.ui.open` answers: drawn, or held back with the reason. A build that answers nothing has drawn it. */+export type OpenResult = { isPlaced: boolean; reason?: string } | void++/**+ * The engine as `session.start` bound it. Every later hook, timer and button reaches the engine through this, so the+ * controller is plain functions over an interface a test can stand in for. Any member may be refused (an administrator+ * removed the affordance, a policy mod said no): every caller catches, and a refusal is a missing fact, never a crash.+ */+export type Host = {+ fs: ReaderFs+ every: (ms: number, fn: () => void) => Timer+ storeGet: (key: string) => Promise<unknown>+ storeSet: (key: string, value: unknown) => Promise<void>+ invalidate: () => void+ /** Fire and forget: a blit resolves only once painted, and blits between frames fold anyway. */+ blit: (args: UiBlitArgs) => void+ openPane: (pane: PaneOpenArgs) => Promise<OpenResult>+ closePane: (id: string) => Promise<void>+ panes: () => Promise<readonly { id: string; isShown: boolean; isFocused: boolean }[]>+ registerCommand: (spec: CommandSpec) => Promise<unknown>+ run: (argv: readonly string[], timeoutMs: number) => Promise<ProcessRunResult>+ usage: () => Promise<{ costUsd?: number; contextPercent?: number }>+ /** How many ruflo / claude-flow MCP tools the model can call now. */+ rufloTools: () => Promise<number>+ settings: () => Promise<unknown>+ home: () => Promise<string | undefined>+ rufloSnapshot: () => Promise<RufloSnapshot>+ rufloRoute: () => Promise<RufloRoute | null>+ rufloSegment: (text: string | null) => Promise<void>+}diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.tsnew file mode 100644index 0000000000..8a9bfbc52f--- /dev/null+++ b/plugins/ruflo-console/hooks/register.ts@@ -0,0 +1,209 @@+import type { EngineInterface, PluginOptions, Register } from 'claude-code'++import { createController, median, p95, type Controller } from './controller'+import { plain } from './data/parse'+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 type { Kit } from './views/common'+import { picturesOf } from './views/frames'+import { NARROW, paneView } from './views/pane'++const RUFLO_TOOL = /^mcp__(?:claude-flow|ruflo|plugin_ruflo[\w-]*)__/++/**+ * Binds a Host from `$`, every member spelled `$.noun.method(...)` here and nowhere else, so the engine reads what+ * the module calls off this one place. Calls that answer nothing are wrapped: a refused draw is not a crashed hook.+ */+function hostOf($: EngineInterface, cwd: string): Host {+ const rooted = (path: string) => (path.startsWith('/') ? path : `${cwd.replace(/\/+$/, '')}/${path}`)+ const quietly = (fn: () => unknown) => {+ try {+ const result = fn()++ if (result instanceof Promise) result.catch(() => undefined)+ } catch {+ // Refused: there is nothing to do about a draw nobody may make.+ }+ }++ 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),+ storeGet: async key => $.store.get(key),+ storeSet: async (key, value) => $.store.set(key, value as never),+ invalidate: () => quietly(() => $.ui.invalidate('ui.render')),+ blit: args => quietly(() => $.ui.blit(args)),+ openPane: async pane => $.ui.open(pane),+ closePane: async id => $.ui.close({ id }),+ panes: async () => $.ui.panes(),+ registerCommand: async spec => $.command.register(spec),+ run: async (argv, timeoutMs) => $.process.run(argv, { cwd, timeoutMs }),+ usage: async () => {+ const usage = await $.session.usage()++ return { ...(usage.cost?.usd !== undefined && { costUsd: usage.cost.usd }), ...(usage.context?.percent !== undefined && { contextPercent: usage.context.percent }) }+ },+ rufloTools: async () => (await $.tool.list()).filter(tool => RUFLO_TOOL.test(tool.name)).length,+ settings: async () => $.settings.read(),+ home: async () => $.env.get('HOME'),+ // `$.ruflo` exists only where ruflo-mods is seated; validate refuses feature-detecting a noun, so these are+ // async: a missing noun throws inside the promise and every caller's catch sees a rejection.+ rufloSnapshot: async () => $.ruflo.snapshot(),+ rufloRoute: async () => $.ruflo.lastRoute(),+ rufloSegment: async text => $.ruflo.segment({ id: 'console', text }),+ }+}++/** 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.+ */+export const register: Register = (on, raw: PluginOptions) => {+ const state = newState(raw)+ let host: Host | null = null+ let control: Controller | null = null++ on('session.start', async ($, e, next) => {+ control?.stop()+ host = hostOf($, e.cwd)+ state.cwd = e.cwd+ control = createController(state, host)++ const bound = host++ state.home = await bound.home().catch(() => undefined) ?? null+ await Promise.all([+ bound.registerCommand({ name: 'ruflo-console', description: 'ruflo console: swarms, claims, federation, plugins, learning, MetaHarness, memory', argumentHint: '[view|close|status]' }).catch(() => undefined),+ bound.storeGet(storeKeyOf(e.cwd)).then(value => restore(state, value), () => undefined),+ bound.rufloTools().then(n => void (state.rufloTools = n), () => undefined),+ ])+ control.start()+ void control.refresh()++ return next(e)+ })++ on('session.end', async ($, e, next) => {+ control?.stop()++ 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()++ 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}` }+ })++ on('ui.render', { component: 'Pane', requestId: PANE_ID }, ($, e, next) => {+ if (control === null) {+ return next(e)+ }++ const started = Date.now()+ const table = $.ui.resolve(e) as unknown as Kit+ const 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++ state.pane.isOpen = true+ state.pane.isFocused = e.props.isFocused === true+ state.pane.columns = columns+ state.pane.placement = e.props.placement+ // A reload while the pane stayed up: timers are gone, so resume them from here.+ if (!state.timers.has('watch')) control.resume()++ const pictures = isNarrow ? new Map() : picturesOf(state, columns, Date.now(), Date.now())++ state.mounted = new Map([...pictures].map(([key, grid]) => [key, { columns: grid.columns, rows: grid.rows }]))+ control.animate()++ const tree = paneView({ kit, state, nowMs: Date.now(), columns, pictures, act: control.actions })++ state.stats.renders.push(Date.now() - started)+ if (state.stats.renders.length > 200) state.stats.renders.shift()++ return tree+ })++ on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {+ const show = state.options.bar === 'on' || (state.options.bar === 'auto' && state.snapshot?.isRufloProject === true)++ if (control === null || e.props.hasSurvey || !show) {+ return next(e)+ }++ const table = $.ui.resolve(e) as unknown as Kit+ const bound = control+ const mark = table.Raster !== undefined ? table.Raster(markPicture(e.props.isWorking, Date.now()).toRaster(BAR_KEY)) : null++ bound.markFrame(e.requestId, e.props.isWorking && mark !== null)++ return barView(table, state, Math.floor(Number(e.props.bodyColumns) || 80), mark, () => void bound.open())+ })++ on('ui.close', async ($, e, next) => {+ const result = await next(e)++ if (e.id === PANE_ID && result.deny === undefined) {+ state.pane.isOpen = false+ state.pane.isShown = false+ control?.animate()+ }++ return result+ })++ /** Observes only: every call goes on unchanged; the count feeds the activity sparkline. */+ on('tool.call', ($, e, next) => {+ control?.noteToolCall()++ return next(e)+ })++ /** 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()++ return result+ })+}diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.tsnew file mode 100644index 0000000000..250a0b284d--- /dev/null+++ b/plugins/ruflo-console/hooks/state.ts@@ -0,0 +1,160 @@+import type { PluginOptions, Timer } from 'claude-code'++import type { ProbeResult, ViewId } from './data/cli'+import type { ReadCache } from './data/files'+import type { Snapshot } from './data/snapshot'+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 const viewOf = (word: string): ViewId | null => {+ const lower = word.trim().toLowerCase()++ return VIEWS.find(view => view.id === lower || view.key === lower || view.label.toLowerCase() === lower || (lower.length >= 3 && view.id.startsWith(lower)))?.id ?? null+}++/**+ * `$.store` is the plugin's, not the folder's: the key carries the working directory, so a view chosen in one project+ * never follows the person into another (the ruflo-swarm leak).+ */+export const storeKeyOf = (cwd: string): string => `ruflo-console/ui:${cwd}`++/** How actions reach the ruflo CLI: each a fixed argv prefix. Only `npx` may download. */+export const CLI_PREFIXES = {+ 'npx-offline': ['npx', '--offline', '-y', '@claude-flow/cli@latest'],+ npx: ['npx', '-y', '@claude-flow/cli@latest'],+ ruflo: ['ruflo'],+ 'claude-flow': ['claude-flow'],+} as const satisfies Record<string, readonly string[]>++export type CliChoice = keyof typeof CLI_PREFIXES++export type Options = {+ cli: CliChoice+ /** How often the disk is re-read while the pane or bar shows (seconds, 2-60). */+ refreshSeconds: number+ /** The animation's frame cap while the pane is shown and focused (0 turns motion off). */+ fps: number+ /** `auto`: the band above the prompt shows in a ruflo project; `on`: always; `off`: never. */+ bar: 'auto' | 'on' | 'off'+ /** Lets the federation view ask the public relay for the roster. Off by default: no network without consent. */+ federationNetwork: boolean+}++const num = (value: unknown, fallback: number, lo: number, hi: number): number => {+ const n = typeof value === 'number' ? value : Number(value)++ return Number.isFinite(n) ? Math.min(Math.max(Math.round(n), lo), hi) : fallback+}++/** 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 | undefined): Options {+ const value = (raw ?? {}) as Record<string, unknown>++ 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),+ bar: value.bar === 'on' || value.bar === 'off' ? value.bar : 'auto',+ federationNetwork: value.federationNetwork === true,+ }+}++/** 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 }++/** 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 }++export type State = {+ options: Options+ cwd: string+ home: string | null+ view: ViewId+ isHelp: boolean+ snapshot: Snapshot | null+ cache: ReadCache+ probes: Map<string, ProbeResult>+ ruflo: { snapshot: RufloSnapshot | null; route: RufloRoute | null; error: string | null }+ usage: { costUsd?: number; contextPercent?: number } | null+ rufloTools: number | null+ mods: ModSeen[]+ /** Tool calls the console saw, per 5 s bucket, newest last: a measured series. */+ activity: number[]+ /** ruflo state files that changed per refresh, newest last: a measured series. */+ writes: number[]+ pane: { isOpen: boolean; isShown: boolean; isFocused: boolean; columns: number; rows: number; placement: 'dock' | 'inline' }+ /** 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 }+ pending: Pending | null+ outcome: Outcome | null+ isActing: boolean+ isRefreshing: boolean+ timers: Map<string, Timer>+ stats: { renders: number[]; refreshes: number[]; frames: number[] }+}++export function newState(raw: PluginOptions | undefined): State {+ return {+ options: optionsOf(raw),+ cwd: '',+ home: null,+ view: 'overview',+ isHelp: false,+ snapshot: null,+ cache: new Map(),+ probes: new Map(),+ ruflo: { snapshot: null, route: null, error: null },+ usage: null,+ rufloTools: null,+ mods: [],+ activity: [],+ writes: [],+ pane: { isOpen: false, isShown: false, isFocused: false, columns: 0, rows: 0, placement: 'inline' },+ mounted: new Map(),+ select: { claim: 0, agent: 0, task: 0 },+ pending: null,+ outcome: null,+ isActing: false,+ isRefreshing: false,+ timers: new Map(),+ stats: { renders: [], refreshes: [], frames: [] },+ }+}++/** Keeps the newest `max` samples of a series. */+export function push(series: number[], value: number, max = 120): void {+ series.push(value)++ if (series.length > max) {+ series.splice(0, series.length - max)+ }+}++/** What is written to `$.store`: the person's choices only. */+export type Persisted = { view: ViewId }++export function restore(state: State, value: unknown): void {+ const held = value !== null && typeof value === 'object' ? (value as Partial<Persisted>) : {}++ if (typeof held.view === 'string' && VIEWS.some(view => view.id === held.view)) {+ state.view = held.view+ }+}diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.tsnew file mode 100644index 0000000000..eb1707e7ed--- /dev/null+++ b/plugins/ruflo-console/hooks/views/bar.ts@@ -0,0 +1,48 @@+/**+ * The band above the prompt: one row naming what ruflo is doing here, with a mark that pulses while Claude works.+ * Each part is a fact on disk or n/a; a part with nothing to say is left out rather than shown as zero.+ */+import type { RenderElement } from 'claude-code'++import type { State } from '../state'+import { clip, count, type Kit } from './common'++export const BAR_KEY = 'mark'++/** The band's words, shortest-first droppable parts last. */+export function barText(state: State): string {+ const snap = state.snapshot+ const parts = ['ruflo']++ if (snap?.swarm != null) parts.push(`${snap.swarm.topology} ${snap.agents.filter(agent => /busy|active/i.test(agent.status)).length}/${snap.swarm.agentIds.length || snap.agents.length} busy`)++ const claims = snap?.claims ?? []++ if (claims.length > 0) {+ const stealable = claims.filter(claim => claim.isStealable).length++ parts.push(`${claims.length} claim${claims.length === 1 ? '' : 's'}${stealable > 0 ? ` (${stealable} stealable)` : ''}`)+ }++ if (snap?.neural?.patterns !== undefined) parts.push(`${count(snap.neural.patterns)} patterns`)+ if (state.ruflo.route !== null) parts.push(`→ ${state.ruflo.route.agent}`)+ if (snap?.plugins.missingFromClone.length) parts.push('marketplace STALE')+ if (state.usage?.costUsd !== undefined) parts.push(`$${state.usage.costUsd.toFixed(2)}`)++ return parts.join(' · ')+}++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)++ return kit.Box({+ flexDirection: 'row',+ children: [+ ...(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: ' ' }),+ 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.tsnew file mode 100644index 0000000000..2760e5e2a2--- /dev/null+++ b/plugins/ruflo-console/hooks/views/claims.ts@@ -0,0 +1,75 @@+import type { RenderElement } from 'claude-code'++import type { ClaimRecord } from '../data/parse'+import { button, clip, col, picture, row, rule, text, THEME, type Ctx } from './common'+import { selection } from './select'++const who = (claim: ClaimRecord): string => (claim.claimant.kind === 'agent' ? `${claim.claimant.agentType ?? 'agent'} ${claim.claimant.id}` : `human ${claim.claimant.name ?? claim.claimant.id}`)++/**+ * The claims board: who holds what, for how long, what may be stolen, and what is being handed off. The buttons act+ * through ruflo's own claims tools (`ruflo mcp exec -t claims_*`), each after a y/n confirm.+ */+export function claimsView(ctx: Ctx): RenderElement {+ const snap = ctx.state.snapshot+ const claims = snap?.claims ?? []+ const pick = selection(ctx.state)+ const stealable = claims.filter(claim => claim.isStealable).length+ const handoffs = claims.filter(claim => claim.handoffTo !== undefined || claim.status === 'handoff-pending').length+ const active = claims.filter(claim => claim.status === 'active').length+ const rows: RenderElement[] = [rule(ctx, 'Claims', `${active} active · ${stealable} stealable · ${handoffs} handoff`)]++ if (snap === null) {+ return text(ctx, 'reading ruflo state…', { dimColor: true })+ }++ 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 }))+ } 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 }))++ claims.slice(0, 10).forEach(claim => {+ const isPicked = pick.claim?.issueId === claim.issueId+ const flags = [claim.isStealable ? 'stealable' : '', claim.handoffTo !== undefined ? `→ ${claim.handoffTo}` : ''].filter(Boolean).join(' ')++ rows.push(+ text(ctx, clip(`${isPicked ? '▸' : ' '} ${claim.issueId.padEnd(22)} ${who(claim).padEnd(34)} ${claim.status.padEnd(9)} ${claim.progress ?? 0}% ${flags}`, ctx.columns), {+ ...(isPicked ? { bold: true, color: THEME.head } : claim.isStealable ? { color: THEME.warn } : {}),+ }),+ )+ })++ if (claims.length > 10) rows.push(text(ctx, `+${claims.length - 10} more`, { dimColor: true }))+ }++ rows.push(rule(ctx, 'Act', ctx.state.isActing ? 'running…' : ''))+ rows.push(+ text(+ ctx,+ `claim ${pick.claim?.issueId ?? 'n/a'} · agent ${pick.agent !== null ? `${pick.agent.name ?? pick.agent.type} (${pick.agent.id})` : 'n/a — no agents on disk'} · task ${pick.task?.id ?? 'n/a — every task is claimed'}`,+ { dimColor: true },+ ),+ )++ 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, 'agent-next', 'agent', ctx.act.agentNext, { hotkey: 'a' }),+ button(ctx, 'task-next', 'task', ctx.act.taskNext, { hotkey: 't' }),+ ]),+ )+ rows.push(+ row(ctx, [+ button(ctx, 'claim', 'Claim task', ctx.act.claim, { hotkey: 'c' }),+ button(ctx, 'release', 'Release', ctx.act.release, { hotkey: 'l' }),+ button(ctx, 'handoff', 'Hand off', ctx.act.handoff, { hotkey: 'o' }),+ button(ctx, 'steal', 'Steal', ctx.act.steal, { hotkey: 's' }),+ ]),+ )+ }++ return col(ctx, rows, 'claims')+}diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.tsnew file mode 100644index 0000000000..e2e8c8996b--- /dev/null+++ b/plugins/ruflo-console/hooks/views/common.ts@@ -0,0 +1,132 @@+/**+ * Shared drawing helpers. Views are pure: `(ctx) => tree`, built from the surface's element table, reading the state+ * and the pictures computed for this frame. They call nothing on the engine; buttons call the closures in `ctx.act`.+ * Text colours are theme names only, so nothing fades on a light background.+ */+import type { Elements, RenderChildren, RenderElement } from 'claude-code'++import type { ProbeResult, ViewId } from '../data/cli'+import type { Grid } from '../gfx/raster'+import type { State } from '../state'++export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Raster?: Elements['terminal']['Raster'] }++/** What a button can ask for: every one a closure over the controller. */+export type Actions = {+ view: (id: ViewId) => void+ refresh: () => void+ help: () => void+ close: () => void+ confirm: () => void+ cancel: () => void+ claimPrev: () => void+ claimNext: () => void+ agentNext: () => void+ taskNext: () => void+ claim: () => void+ release: () => void+ handoff: () => void+ steal: () => void+}++export type Ctx = {+ kit: Kit+ state: State+ nowMs: number+ columns: number+ /** Every picture of this view, by Raster key, already drawn for this frame. */+ pictures: Map<string, Grid>+ act: Actions+}++export const THEME = { head: 'claude', ok: 'success', bad: 'error', warn: 'warning', info: 'suggestion' } as const++export const clip = (text: string, width: number): string => (text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…`)++export function ago(atMs: number | null | undefined, nowMs: number): string {+ if (atMs === null || atMs === undefined || !Number.isFinite(atMs)) return 'n/a'++ const s = Math.max(0, Math.round((nowMs - atMs) / 1000))++ if (s < 60) return `${s}s ago`+ if (s < 3600) return `${Math.floor(s / 60)}m ago`+ if (s < 86_400) return `${Math.floor(s / 3600)}h ago`++ return `${Math.floor(s / 86_400)}d ago`+}++/** A count as people read it (12.3k), or n/a for a value nobody measured. */+export function count(value: number | null | undefined): string {+ if (value === null || value === undefined || !Number.isFinite(value)) return 'n/a'+ if (Math.abs(value) >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`+ if (Math.abs(value) >= 10_000) return `${(value / 1000).toFixed(1)}k`++ return String(Math.round(value * 100) / 100)+}++export const pct = (value: number | null | undefined): string => (value === null || value === undefined || !Number.isFinite(value) ? 'n/a' : `${Math.round(value * 100)}%`)++export function text(ctx: Ctx, children: string, props: { color?: string; bold?: boolean; dimColor?: boolean } = {}): RenderElement {+ return ctx.kit.Text({ wrap: 'truncate-end', ...props, children: clip(children, Math.max(4, ctx.columns)) })+}++export function row(ctx: Ctx, parts: readonly RenderChildren[], key?: string): RenderElement {+ return ctx.kit.Box({ flexDirection: 'row', ...(key !== undefined && { key }), children: [...parts] })+}++export function col(ctx: Ctx, parts: readonly RenderChildren[], key?: string): RenderElement {+ return ctx.kit.Box({ flexDirection: 'column', ...(key !== undefined && { key }), children: [...parts] })+}++/** A section title with a rule to the right edge. */+export function rule(ctx: Ctx, title: string, right = ''): RenderElement {+ const fill = Math.max(1, ctx.columns - title.length - right.length - 3)++ return row(ctx, [ctx.kit.Text({ bold: true, color: THEME.head, children: title }), ctx.kit.Text({ dimColor: true, children: ` ${'─'.repeat(fill)} ` }), ctx.kit.Text({ dimColor: true, children: right })])+}++/** A label and its value; the value dims when it is n/a. */+export function kv(ctx: Ctx, label: string, value: string, color?: string): RenderElement {+ const isNa = value === 'n/a' || value.startsWith('n/a ') || value === 'missing'++ return row(ctx, [+ ctx.kit.Text({ dimColor: true, children: `${label.padEnd(16)} ` }),+ ctx.kit.Text({ wrap: 'truncate-end', ...(isNa ? { dimColor: true } : color !== undefined ? { color } : {}), children: clip(value, Math.max(4, ctx.columns - 18)) }),+ ])+}++/** A Raster for a picture of this frame, or a dim note where the surface has no Raster. */+export function picture(ctx: Ctx, key: string, fallback: string): RenderElement {+ const grid = ctx.pictures.get(key)++ if (grid === undefined || ctx.kit.Raster === undefined) {+ return text(ctx, fallback, { dimColor: true })+ }++ return ctx.kit.Raster(grid.toRaster(key))+}++export function button(ctx: Ctx, key: string, label: string, onPress: () => void, options: { hotkey?: string; primary?: boolean } = {}): RenderElement {+ return ctx.kit.Button({ key, label, onPress, ...(options.hotkey !== undefined && { hotkey: options.hotkey }), ...(options.primary === true && { variant: 'primary' as const }) })+}++/** How a CLI-sourced fact reads: its value's age, running, failing with a stale value, or never measured. */+export function sourceLine(result: ProbeResult | undefined, nowMs: number, what: string): { text: string; color?: string } {+ if (result === undefined || (result.okAtMs === null && result.error === null)) {+ return { text: result?.isRunning === true ? `${what}: asking the ruflo CLI…` : `${what}: not asked yet` }+ }++ if (result.error !== null && (result.errorAtMs ?? 0) >= (result.okAtMs ?? 0)) {+ return { text: `${what}: ${clip(result.error, 80)}${result.okAtMs !== null ? ` (last good ${ago(result.okAtMs, nowMs)}, not shown as live)` : ''}`, color: THEME.warn }+ }++ return { text: `${what}: ruflo CLI, ${ago(result.okAtMs, nowMs)}` }+}++/** The value of a probe only while it is the newest answer: a value older than the latest failure is stale. */+export function live<T>(result: ProbeResult | undefined): T | null {+ if (result === undefined || result.value === null) return null+ if (result.error !== null && (result.errorAtMs ?? 0) >= (result.okAtMs ?? 0)) return null++ return result.value as T+}diff --git a/plugins/ruflo-console/hooks/views/federation.ts b/plugins/ruflo-console/hooks/views/federation.tsnew file mode 100644index 0000000000..37940e4dbf--- /dev/null+++ b/plugins/ruflo-console/hooks/views/federation.ts@@ -0,0 +1,71 @@+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'++/**+ * This node's federation standing from local state and local CLI answers only. The roster lives on the public relay,+ * so it is asked for only when the person turns `federationNetwork` on, and what it returns is labelled third-party.+ */+export function federationView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const snap = state.snapshot+ const peers = live<Peers>(state.probes.get('peers'))+ 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')]++ rows.push(+ kv(+ ctx,+ 'nostr identity',+ snap?.hasNostrKey === true ? '~/.ruflo/nostr.key present (never read here)' : snap?.hasNostrKey === false ? 'none — `npx ruflo federation join` makes one' : 'n/a',+ snap?.hasNostrKey === true ? THEME.ok : undefined,+ ),+ )+ rows.push(kv(ctx, 'federation keys', nodes === null ? 'n/a — no .claude-flow/federation' : nodes.length === 0 ? 'none' : `${nodes.length} node ids: ${nodes.slice(0, 4).join(', ')}${nodes.length > 4 ? ' …' : ''} (keys never read)`))+ rows.push(+ kv(+ ctx,+ 'trust',+ peers === null+ ? sourceLine(state.probes.get('peers'), nowMs, 'n/a').text+ : peers.degraded !== undefined+ ? `n/a — agentbbs ${peers.degraded}`+ : `${peers.peers.length} pinned peers accepted for envelopes (agentbbs peers.json)`,+ ),+ )++ rows.push(rule(ctx, 'Peers', 'agentbbs'))++ if (peers !== null && peers.peers.length > 0) {+ for (const peer of peers.peers.slice(0, 6)) rows.push(text(ctx, `◇ ${peer.id} · last sync ${ago(peer.lastSyncMs, nowMs)}`))+ } else {+ rows.push(text(ctx, peers === null ? sourceLine(state.probes.get('peers'), nowMs, 'peers').text : 'no pinned peers', { dimColor: true }))+ }++ rows.push(rule(ctx, 'Channels', 'x.ruv.io'))++ if (channels !== null && channels.channels.length > 0) {+ for (const channel of channels.channels.slice(0, 6)) rows.push(text(ctx, `# ${channel.name ?? channel.id} · ${channel.id.startsWith('prv:') ? 'private' : 'public'} · since ${ago(channel.atMs, nowMs)}`))+ } else {+ rows.push(text(ctx, channels === null ? sourceLine(state.probes.get('channels'), nowMs, 'channels').text : 'no channels joined', { dimColor: true }))+ }++ rows.push(text(ctx, 'last messages: n/a — ruflo keeps no local message log (`npx ruflo federation channel read`)', { dimColor: true }))+ rows.push(rule(ctx, 'Roster', state.options.federationNetwork ? 'wss relay · third-party text' : 'network off'))++ if (!state.options.federationNetwork) {+ rows.push(text(ctx, 'Off: the roster is on the public relay. Turn on federationNetwork in /config (ruflo-console) to ask it.', { dimColor: true }))+ } else if (roster === null) {+ rows.push(text(ctx, sourceLine(state.probes.get('roster'), nowMs, 'roster').text, { dimColor: true }))+ } else if (roster.members.length === 0) {+ rows.push(text(ctx, `roster empty on ${roster.relay ?? 'the relay'} (${ago(roster.atMs, nowMs)})`, { dimColor: true }))+ } else {+ for (const member of roster.members.slice(0, 6)) rows.push(text(ctx, `· ${member.name}${member.detail !== undefined ? ` — ${member.detail}` : ''}`))+ rows.push(text(ctx, `untrusted: published by third-party members, not vetted · ${roster.relay ?? ''} · ${ago(roster.atMs, nowMs)}`, { dimColor: true }))+ }++ return col(ctx, rows, 'federation')+}diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.tsnew file mode 100644index 0000000000..fd47ff858e--- /dev/null+++ b/plugins/ruflo-console/hooks/views/frames.ts@@ -0,0 +1,99 @@+/**+ * 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.+ */+import type { HarnessScore } from '../data/cli'+import type { Snapshot } from '../data/snapshot'+import { activityPicture, claimsPicture, curvePicture, scorePicture, topologyPicture, type ClaimBar, type TopoModel } from '../gfx/pictures'+import type { Grid } from '../gfx/raster'+import type { State } from '../state'+import { live } from './common'++export const MAX_NODES = 12+export const MAX_CLAIM_BARS = 8++/** 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 {+ const swarm = snapshot?.swarm ?? null++ if (snapshot === null || (swarm === null && snapshot.hive === null && snapshot.agents.length === 0)) {+ return null+ }++ const 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 }++ 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 }))],+ }+}++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 }),+ }))+}++/** Running success of routed outcomes, oldest first. */+export const curvePointsOf = (snapshot: Snapshot | null): boolean[] => (snapshot?.outcomes?.points ?? []).map(point => point.ok)++/** 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)++/** When the score on screen was first drawn: the fill animates 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 snapshot = state.snapshot++ switch (state.view) {+ case 'overview':+ pictures.set(+ 'activity',+ activityPicture(+ [+ { label: 'tool calls/5s', values: state.activity },+ { label: 'state writes', values: state.writes },+ ],+ width,+ t,+ ),+ )+ break+ case 'swarm': {+ const model = topoModelOf(snapshot)++ if (model !== null) pictures.set('topology', topologyPicture(model, width, topologyRows(width), t))+ break+ }+ case 'claims': {+ const bars = claimBarsOf(snapshot)++ if (bars.length > 0) pictures.set('claims', claimsPicture(bars, width, bars.length, nowMs))+ break+ }+ case 'learning':+ pictures.set('curve', curvePicture(curvePointsOf(snapshot), width, 6, t))+ break+ case 'metaharness': {+ const score = live<HarnessScore>(state.probes.get('metaharness'))++ if (score !== null) {+ if (!scoreShown.has(score)) scoreShown.set(score, t)+ pictures.set('score', scorePicture(score.dims, width, t, scoreShown.get(score) ?? t))+ }+ break+ }+ default:+ break+ }++ return pictures+}diff --git a/plugins/ruflo-console/hooks/views/learning.ts b/plugins/ruflo-console/hooks/views/learning.tsnew file mode 100644index 0000000000..dac4d52bca--- /dev/null+++ b/plugins/ruflo-console/hooks/views/learning.ts@@ -0,0 +1,71 @@+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'++/**+ * What ruflo has learned, from its own stores: the router's last pick and how routed tasks turned out, the model tier+ * router's tallies, and SONA's trajectory and pattern counts. A rate always carries its N.+ */+export function learningView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const snap = state.snapshot+ const route = state.ruflo.route+ const outcomes = snap?.outcomes ?? null+ const router = snap?.router ?? null+ const neural = snap?.neural ?? null+ const intel = live<Intelligence>(state.probes.get('intelligence'))+ const rows: RenderElement[] = [rule(ctx, 'Router', 'ruflo-mods · routing-outcomes.json')]++ rows.push(+ kv(+ ctx,+ 'last pick',+ route !== null+ ? `${route.agent} ${pct(route.confidence)} · ${route.matched ? 'keyword match' : 'no match, default'} · ${route.reason} (a prior, not a calibrated probability)`+ : state.ruflo.snapshot === null+ ? 'n/a — ruflo-mods not seated, so no in-process route'+ : 'n/a — no prompt routed yet this session',+ ),+ )+ rows.push(+ kv(+ ctx,+ 'routed outcomes',+ outcomes === null || outcomes.total === 0+ ? 'n/a — no routing-outcomes.json'+ : `${outcomes.successes}/${outcomes.total} succeeded (${pct(outcomes.successes / outcomes.total)} success rate, N=${outcomes.total}) · last ${ago(outcomes.points[outcomes.points.length - 1]?.atMs, nowMs)}`,+ outcomes !== null && outcomes.total > 0 ? THEME.info : undefined,+ ),+ )+ 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(+ kv(+ ctx,+ 'model router',+ router === null+ ? 'n/a — no .swarm/model-router-state.json'+ : `${count(router.decisions)} decisions · ${router.distribution.filter(entry => entry.count > 0).map(entry => `${entry.model} ${entry.count}`).join(' · ') || 'none'} · avg confidence ${router.avgConfidence === undefined ? 'n/a' : router.avgConfidence.toFixed(2)} · ${ago(router.updatedMs, nowMs)}`,+ ),+ )++ 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)))+ rows.push(kv(ctx, 'signals', neural === null ? 'n/a' : count(neural.signals)))+ rows.push(kv(ctx, 'last learned', neural?.lastAdaptationMs !== undefined ? ago(neural.lastAdaptationMs, nowMs) : 'n/a', THEME.info))+ rows.push(kv(ctx, 'SONA patterns', snap?.sona === null || snap?.sona === undefined ? 'n/a — no .swarm/sona-patterns.json' : String(snap.sona.patterns)))+ rows.push(+ kv(+ ctx,+ 'live engine',+ intel === null+ ? sourceLine(state.probes.get('intelligence'), nowMs, 'n/a').text+ : `${count(intel.trajectories)} trajectories · ${count(intel.patterns)} patterns · MoE ${count(intel.moeDecisions)} decisions · EWC ${count(intel.ewcConsolidations)} consolidations · neural router ${intel.neuralRouter ?? 'n/a'}`,+ ),+ )+ rows.push(text(ctx, 'live engine: hooks_intelligence_stats in a fresh CLI process, so in-memory counters start at zero there', { dimColor: true }))++ return col(ctx, rows, 'learning')+}diff --git a/plugins/ruflo-console/hooks/views/memory.ts b/plugins/ruflo-console/hooks/views/memory.tsnew file mode 100644index 0000000000..d237f3e148--- /dev/null+++ b/plugins/ruflo-console/hooks/views/memory.ts@@ -0,0 +1,67 @@+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'++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. */+export function memoryView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const 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?.costUsd+ const rows: RenderElement[] = [rule(ctx, 'AgentDB', memory?.backend ?? '')]++ if (memory === null) {+ rows.push(text(ctx, sourceLine(state.probes.get('memory'), nowMs, 'memory stats').text, { dimColor: true }))+ } else {+ rows.push(kv(ctx, 'entries', `${count(memory.total)} · ${count(memory.vectors)} with vectors`))+ rows.push(kv(ctx, 'storage', memory.storage ?? 'n/a'))+ rows.push(kv(ctx, 'span', `oldest ${ago(memory.oldestMs, nowMs)} · newest ${ago(memory.newestMs, nowMs)}`))+ }++ rows.push(rule(ctx, 'Namespaces', spaces === null ? '' : `newest ${spaces.sampled} entries`))++ if (spaces === null) {+ rows.push(text(ctx, sourceLine(state.probes.get('namespaces'), nowMs, 'memory list').text, { dimColor: true }))+ } else if (spaces.byName.length === 0) {+ rows.push(text(ctx, 'no entries', { dimColor: true }))+ } else {+ const top = spaces.byName[0]?.count ?? 1+ const width = Math.max(4, Math.min(30, ctx.columns - 30))++ for (const space of spaces.byName.slice(0, 6)) {+ rows.push(text(ctx, `${space.name.slice(0, 20).padEnd(21)}${'█'.repeat(Math.max(1, Math.round((space.count / top) * width)))} ${space.count}`))+ }++ 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 }))+ }++ return col(ctx, rows, 'memory')+}diff --git a/plugins/ruflo-console/hooks/views/metaharness.ts b/plugins/ruflo-console/hooks/views/metaharness.tsnew file mode 100644index 0000000000..6dcc20596c--- /dev/null+++ b/plugins/ruflo-console/hooks/views/metaharness.ts@@ -0,0 +1,49 @@+import type { RenderElement } from 'claude-code'++import type { Flywheel, HarnessScore } from '../data/cli'+import { ago, col, kv, live, picture, rule, sourceLine, text, THEME, type Ctx } from './common'++/**+ * MetaHarness is optional (ADR-150): every line here degrades to "unavailable" with the CLI's reason, and nothing in+ * the console depends on it. Score and flywheel come from the ruflo CLI; the active policy from disk.+ */+export function metaharnessView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const score = live<HarnessScore>(state.probes.get('metaharness'))+ const flywheel = live<Flywheel>(state.probes.get('flywheel'))+ const policy = state.snapshot?.harnessPolicy ?? null+ const rows: RenderElement[] = [rule(ctx, 'Readiness', score?.archetype ?? 'metaharness score')]++ if (score === null) {+ const line = sourceLine(state.probes.get('metaharness'), nowMs, 'MetaHarness')++ 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(+ kv(+ ctx,+ 'est. cost/run',+ `${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(rule(ctx, 'Flywheel', 'receipts ledger'))++ if (flywheel === null) {+ rows.push(text(ctx, sourceLine(state.probes.get('flywheel'), nowMs, 'flywheel').text, { dimColor: true }))+ } else {+ rows.push(kv(ctx, 'ledger', `${flywheel.isLedgerValid ? 'valid' : 'INVALID'} · ${flywheel.commits} commits · ${flywheel.receipts} receipts`, flywheel.isLedgerValid ? THEME.ok : THEME.bad))+ rows.push(kv(ctx, 'champion', flywheel.champion ?? 'none promoted', flywheel.champion !== undefined ? THEME.info : undefined))+ rows.push(kv(ctx, 'serving epoch', flywheel.epoch === undefined ? 'n/a' : String(flywheel.epoch)))++ for (const error of flywheel.errors) rows.push(text(ctx, `ledger: ${error}`, { color: THEME.bad }))+ }++ 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 }))++ return col(ctx, rows, 'metaharness')+}diff --git a/plugins/ruflo-console/hooks/views/overview.ts b/plugins/ruflo-console/hooks/views/overview.tsnew file mode 100644index 0000000000..efe9d52a8f--- /dev/null+++ b/plugins/ruflo-console/hooks/views/overview.ts@@ -0,0 +1,67 @@+import type { RenderElement } from 'claude-code'++import type { MemoryStats } from '../data/cli'+import { ago, col, count, kv, live, picture, rule, sourceLine, text, THEME, type Ctx } from './common'++/** Each subsystem in one line: what it is, from where, as of when. Nothing on this view is estimated. */+export function overviewView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const snap = state.snapshot+ const version = live<string>(state.probes.get('version'))+ const memory = live<MemoryStats>(state.probes.get('memory'))+ const daemon = snap?.daemon ?? null+ const helpers = snap?.helpers ?? null+ const ruflo = state.ruflo.snapshot+ const loaded = state.mods.filter(mod => mod.isLoaded).length+ const refused = state.mods.length - loaded+ const swarm = snap?.swarm ?? null+ const rows: RenderElement[] = [rule(ctx, 'Subsystems', snap?.isRufloProject === false ? 'not a ruflo project' : '')]++ rows.push(kv(ctx, 'ruflo CLI', version !== null ? `v${version} (${state.options.cli})` : sourceLine(state.probes.get('version'), nowMs, 'n/a').text))+ rows.push(+ kv(+ ctx,+ 'project',+ snap === null ? 'reading…' : snap.isRufloProject ? `ruflo state in ${state.cwd.split('/').slice(-2).join('/')}` : 'n/a — no .claude-flow here; `npx ruflo init` makes one',+ snap?.isRufloProject === true ? THEME.ok : undefined,+ ),+ )+ rows.push(+ kv(+ ctx,+ 'daemon',+ daemon === null+ ? 'n/a — no daemon-state.json'+ : `${daemon.running ? 'running' : 'stopped'} per daemon-state.json (written ${ago(daemon.savedAtMs, nowMs)}) · ${daemon.workers.length} workers · ${count(daemon.workers.reduce((n, w) => n + w.runs, 0))} runs`,+ daemon?.running === true ? THEME.ok : undefined,+ ),+ )+ rows.push(kv(ctx, 'MCP tools', state.rufloTools === null ? 'n/a' : state.rufloTools > 0 ? `${state.rufloTools} ruflo tools callable now (Claude Code's tool list)` : 'none connected in this session', state.rufloTools !== null && state.rufloTools > 0 ? THEME.ok : undefined))+ rows.push(kv(ctx, 'memory DB', memory !== null ? `${count(memory.total)} entries · ${count(memory.vectors)} vectors · ${memory.backend}${memory.storage !== undefined ? ` · ${memory.storage}` : ''}` : sourceLine(state.probes.get('memory'), nowMs, 'n/a').text))+ rows.push(+ kv(+ ctx,+ 'helpers',+ helpers === null+ ? 'n/a — no .claude/helpers/helpers.manifest.json'+ : `manifest v${helpers.version} · ${helpers.files.length} files · ${helpers.isSigned ? `signed (${helpers.algorithm ?? 'unknown'})` : 'UNSIGNED'} · signature not checked here (ruflo verify)`,+ helpers !== null && !helpers.isSigned ? THEME.warn : undefined,+ ),+ )+ rows.push(+ kv(+ ctx,+ 'ruflo-mods',+ ruflo !== null ? `seated · policy ${ruflo.policy} · routed ${ruflo.routed} · tightened ${ruflo.tightened} · owns ${ruflo.owned.join('+') || 'nothing'}` : 'not seated — classic hooks handle every event',+ ruflo !== null ? THEME.ok : undefined,+ ),+ )+ 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`))++ 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 }))++ return col(ctx, rows, 'overview')+}diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.tsnew file mode 100644index 0000000000..013838ac6a--- /dev/null+++ b/plugins/ruflo-console/hooks/views/pane.ts@@ -0,0 +1,119 @@+/**+ * 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.+ */+import type { RenderElement } from 'claude-code'++import { VIEWS } from '../state'+import { claimsView } from './claims'+import { ago, button, clip, col, row, text, THEME, type Ctx } from './common'+import { federationView } from './federation'+import { learningView } from './learning'+import { memoryView } from './memory'+import { metaharnessView } from './metaharness'+import { overviewView } from './overview'+import { pluginsView } from './plugins'+import { swarmView } from './swarm'++export const NARROW = 44++const BODIES = {+ overview: overviewView,+ swarm: swarmView,+ claims: claimsView,+ federation: federationView,+ plugins: pluginsView,+ learning: learningView,+ metaharness: metaharnessView,+ memory: memoryView,+} as const++function tabs(ctx: Ctx): RenderElement {+ const isShort = ctx.columns < 104++ if (ctx.columns < NARROW) {+ const index = VIEWS.findIndex(view => view.id === ctx.state.view)++ return text(ctx, `${index + 1}/${VIEWS.length} ${VIEWS[index]?.label ?? ''} · 1-8 switch · h help`, { bold: true, color: THEME.head })+ }++ return row(+ ctx,+ VIEWS.map(view => {+ const isCurrent = view.id === ctx.state.view+ const label = isShort ? view.label.slice(0, view.id === 'metaharness' ? 4 : 5) : view.label++ return 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) })+ }),+ 'tabs',+ )+}++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')+}++function confirmRow(ctx: Ctx): RenderElement | null {+ const pending = ctx.state.pending++ if (pending === null) {+ return null+ }++ return col(+ ctx,+ [+ text(ctx, `Confirm: ${pending.label}?`, { bold: true, color: THEME.warn }),+ text(ctx, `runs: ruflo ${pending.args.join(' ')}`, { dimColor: true }),+ row(ctx, [button(ctx, 'confirm', 'Yes, run it (y)', ctx.act.confirm, { hotkey: 'y', primary: true }), button(ctx, 'cancel', 'Cancel (n)', ctx.act.cancel, { hotkey: 'n' })]),+ ],+ 'confirm',+ )+}++function footer(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const outcome = state.outcome+ const parts: RenderElement[] = []++ if (outcome !== null && nowMs - outcome.atMs < 60_000) {+ parts.push(+ text(ctx, `${outcome.ok ? '✓' : '✗'} ${outcome.label}: ${outcome.detail}${outcome.verified === 'yes' ? ' · on disk' : outcome.verified === 'no' ? ' · not on disk yet' : ''}`, {+ color: outcome.ok ? THEME.ok : THEME.bad,+ }),+ )+ }++ 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>)'++ parts.push(+ row(ctx, [+ text(ctx, clip(`${read} · ${keys}`, Math.max(10, ctx.columns - 24)), { 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' })] : []),+ ]),+ )++ return col(ctx, parts, 'footer')+}++/** 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 confirm = confirmRow(ctx)++ return ctx.kit.Box({ flexDirection: 'column', children: [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.tsnew file mode 100644index 0000000000..8c78d36891--- /dev/null+++ b/plugins/ruflo-console/hooks/views/plugins.ts@@ -0,0 +1,71 @@+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'++const WEEK = 7 * 86_400_000++/**+ * Installed ruflo plugins and whether the marketplace clone they came from is current. A clone that does not list the+ * plugins this repository publishes (ruflo-mods first) is stale: `/plugin install ruflo-mods@ruflo` then fails with+ * "not found", a real report today. The fix is named, never run.+ */+export function pluginsView(ctx: Ctx): RenderElement {+ const { state, nowMs } = ctx+ const facts = state.snapshot?.plugins ?? null+ const rows: RenderElement[] = [rule(ctx, 'Marketplace', RUFLO_MARKET)]++ if (facts === null) {+ return text(ctx, 'reading plugin records…', { dimColor: true })+ }++ const market = facts.markets?.find(entry => entry.name === RUFLO_MARKET) ?? null++ if (state.home === null) {+ rows.push(text(ctx, 'n/a — HOME is not readable to this mod, so ~/.claude/plugins cannot be found', { dimColor: true }))+ } else if (market === null) {+ rows.push(kv(ctx, 'ruflo clone', facts.markets === null ? 'n/a — no known_marketplaces.json' : 'not added — /plugin marketplace add ruvnet/ruflo'))+ } else {+ const isOld = market.updatedMs !== undefined && nowMs - market.updatedMs > WEEK++ rows.push(kv(ctx, 'ruflo clone', `pulled ${ago(market.updatedMs, nowMs)} · auto-update ${market.isAutoUpdate ? 'on' : 'off'} · lists ${facts.rufloOffered?.length ?? 'n/a'} plugins`, isOld ? THEME.warn : undefined))++ if (facts.missingFromClone.length > 0) {+ rows.push(text(ctx, `STALE: the clone does not list ${facts.missingFromClone.join(', ')} — run /plugin marketplace update ${RUFLO_MARKET}`, { bold: true, color: THEME.bad }))+ } else if (facts.rufloOffered === null) {+ rows.push(text(ctx, "n/a — the clone's marketplace.json is not readable, so freshness is unknown", { dimColor: true }))+ } else {+ rows.push(text(ctx, `current: lists ${EXPECTED_IN_MARKET.join(', ')}`, { color: THEME.ok }))+ }+ }++ const ruflo = (facts.installed ?? []).filter(plugin => plugin.marketplace === RUFLO_MARKET)+ const enabled = ruflo.filter(plugin => facts.enabled.has(plugin.id)).length++ 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)' : ''}`)++ 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)}`))+ }++ 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 }))++ rows.push(rule(ctx, 'Mods', 'function hooks'))+ rows.push(kv(ctx, PLUGIN_NAME, 'loaded (you are reading it)', THEME.ok))+ rows.push(kv(ctx, 'ruflo-mods', state.ruflo.snapshot !== null ? 'seated ($.ruflo answers)' : 'not seated in this session', state.ruflo.snapshot !== null ? THEME.ok : undefined))++ for (const mod of state.mods.slice(-5)) {+ rows.push(kv(ctx, mod.name, `${mod.isLoaded ? 'loaded' : `REFUSED: ${mod.reason ?? 'no reason given'}`} · ${mod.provenance} · ${ago(mod.atMs, nowMs)}`, mod.isLoaded ? undefined : THEME.bad))+ }++ rows.push(text(ctx, 'mods list: those registered after the console loaded (the engine admits earlier ones unseen)', { dimColor: true }))++ return col(ctx, rows, 'plugins')+}diff --git a/plugins/ruflo-console/hooks/views/select.ts b/plugins/ruflo-console/hooks/views/select.tsnew file mode 100644index 0000000000..a045c2e7aa--- /dev/null+++ b/plugins/ruflo-console/hooks/views/select.ts@@ -0,0 +1,20 @@+import type { AgentRecord, ClaimRecord, TaskRecord } from '../data/parse'+import type { State } from '../state'++const at = <T>(list: readonly T[], index: number): T | null => (list.length === 0 ? null : (list[((index % list.length) + list.length) % list.length] ?? null))++/** Tasks no claim names and ruflo does not mark done: what "Claim task" can take. */+export const openTasks = (state: State): TaskRecord[] => {+ const claimed = new Set((state.snapshot?.claims ?? []).map(claim => claim.issueId))++ return (state.snapshot?.tasks ?? []).filter(task => !claimed.has(task.id) && !/complete|done|cancel|fail/i.test(task.status))+}++/** What the claims view's buttons act on: indexes wrap, so a re-read that shortens a list never strands them. */+export function selection(state: State): { claim: ClaimRecord | null; agent: AgentRecord | null; task: TaskRecord | null } {+ return {+ claim: at(state.snapshot?.claims ?? [], state.select.claim),+ agent: at(state.snapshot?.agents ?? [], state.select.agent),+ task: at(openTasks(state), state.select.task),+ }+}diff --git a/plugins/ruflo-console/hooks/views/swarm.ts b/plugins/ruflo-console/hooks/views/swarm.tsnew file mode 100644index 0000000000..628015b39a--- /dev/null+++ b/plugins/ruflo-console/hooks/views/swarm.ts@@ -0,0 +1,75 @@+import type { RenderElement } from 'claude-code'++import { clip, col, kv, picture, rule, text, THEME, type Ctx } from './common'+import { MAX_NODES } from './frames'++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.+ */+export function swarmView(ctx: Ctx): RenderElement {+ const snap = ctx.state.snapshot+ const swarm = snap?.swarm ?? null+ const hive = snap?.hive ?? null+ const agents = swarm !== null && swarm.agentIds.length > 0 ? (snap?.agents ?? []).filter(agent => swarm.agentIds.includes(agent.id)) : (snap?.agents ?? [])+ const rows: RenderElement[] = [rule(ctx, 'Swarm', swarm?.id ?? '')]++ 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 }))++ return ctx.kit.Box({ flexDirection: 'column', key: 'swarm', children: rows })+ }++ 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(rule(ctx, 'Agents', `${agents.length}${agents.length > MAX_NODES - 1 ? `, graph shows ${MAX_NODES - 1}` : ''}`))++ 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,+ ),+ }),+ ],+ }),+ )+ }++ if (agents.length > 8) rows.push(text(ctx, `+${agents.length - 8} more`, { dimColor: true }))++ 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 }))+ }++ if (hive.pending.length === 0 && hive.history.length === 0) rows.push(text(ctx, 'no proposals yet', { 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/tests/fixtures/ruflo-run.ts b/plugins/ruflo-console/tests/fixtures/ruflo-run.tsnew file mode 100644index 0000000000..52e4bf9866--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/ruflo-run.ts@@ -0,0 +1,33 @@+/** Captured from a real `ruflo` 3.50.0 project on 2026-10-01 (swarm init, two agents, hive-mind init + a proposal, a task, two claims, one stealable), with learning stores from a long-lived project. */++export const HIVE_TOKEN = "4d377e5746f657255af8774e4a00fc6f4685d980f0a9ec3561ae03bf0992c861"++export const RUFLO_FILES: Readonly<Record<string, string>> = {+ ".claude-flow/swarm/swarm-state.json": "{\n \"swarms\": {\n \"swarm-1790903031804-y9rnjr\": {\n \"swarmId\": \"swarm-1790903031804-y9rnjr\",\n \"topology\": \"hierarchical\",\n \"maxAgents\": 6,\n \"status\": \"running\",\n \"agents\": [\n \"agent-1790903032181-97m25s\",\n \"agent-1790903032591-x41b0y\"\n ],\n \"tasks\": [],\n \"config\": {\n \"topology\": \"hierarchical\",\n \"maxAgents\": 6,\n \"strategy\": \"specialized\",\n \"communicationProtocol\": \"message-bus\",\n \"autoScaling\": true,\n \"consensusMechanism\": \"majority\"\n },\n \"createdAt\": \"2026-10-02T01:03:51.804Z\",\n \"updatedAt\": \"2026-10-02T01:03:51.804Z\"\n }\n },\n \"version\": \"3.0.0\"\n}",+ ".swarm/state.json": "{\n \"id\": \"swarm-1790903031804-y9rnjr\",\n \"topology\": \"hierarchical\",\n \"maxAgents\": 6,\n \"strategy\": \"specialized\",\n \"v3Mode\": false,\n \"permissions\": null,\n \"initializedAt\": \"2026-10-02T01:03:51.804Z\",\n \"status\": \"ready\"\n}",+ ".claude-flow/agents/store.json": "{\n \"agents\": {\n \"agent-1790903032181-97m25s\": {\n \"agentId\": \"agent-1790903032181-97m25s\",\n \"agentType\": \"coder\",\n \"status\": \"idle\",\n \"health\": 1,\n \"taskCount\": 0,\n \"config\": {\n \"provider\": \"anthropic\",\n \"timeout\": 300,\n \"autoTools\": true\n },\n \"createdAt\": \"2026-10-02T01:03:52.181Z\",\n \"model\": \"sonnet\",\n \"modelRoutedBy\": \"default\"\n },\n \"agent-1790903032591-x41b0y\": {\n \"agentId\": \"agent-1790903032591-x41b0y\",\n \"agentType\": \"tester\",\n \"status\": \"idle\",\n \"health\": 1,\n \"taskCount\": 0,\n \"config\": {\n \"provider\": \"anthropic\",\n \"timeout\": 300,\n \"autoTools\": true\n },\n \"createdAt\": \"2026-10-02T01:03:52.591Z\",\n \"model\": \"sonnet\",\n \"modelRoutedBy\": \"default\"\n }\n },\n \"version\": \"3.0.0\"\n}",+ ".claude-flow/tasks/store.json": "{\n \"tasks\": {\n \"task-1790903322323-nymvi1\": {\n \"taskId\": \"task-1790903322323-nymvi1\",\n \"type\": \"implementation\",\n \"description\": \"Build the console overview\",\n \"priority\": \"normal\",\n \"status\": \"pending\",\n \"progress\": 0,\n \"assignedTo\": [],\n \"tags\": [],\n \"createdAt\": \"2026-10-02T01:08:42.323Z\",\n \"startedAt\": null,\n \"completedAt\": null\n }\n },\n \"version\": \"3.0.0\"\n}",+ ".claude-flow/claims/claims.json": "{\n \"claims\": {\n \"console-demo-1\": {\n \"issueId\": \"console-demo-1\",\n \"claimant\": {\n \"type\": \"agent\",\n \"agentId\": \"agent-1790903032181-97m25s\",\n \"agentType\": \"coder\"\n },\n \"claimedAt\": \"2026-10-02T01:08:42.654Z\",\n \"status\": \"active\",\n \"statusChangedAt\": \"2026-10-02T01:08:42.654Z\",\n \"progress\": 0\n },\n \"console-demo-2\": {\n \"issueId\": \"console-demo-2\",\n \"claimant\": {\n \"type\": \"agent\",\n \"agentId\": \"agent-1790903032591-x41b0y\",\n \"agentType\": \"tester\"\n },\n \"claimedAt\": \"2026-10-02T01:08:42.993Z\",\n \"status\": \"stealable\",\n \"statusChangedAt\": \"2026-10-02T01:08:43.330Z\",\n \"progress\": 0\n }\n },\n \"stealable\": {\n \"console-demo-2\": {\n \"reason\": \"voluntary\",\n \"stealableAt\": \"2026-10-02T01:08:43.330Z\",\n \"progress\": 0\n }\n },\n \"contests\": {}\n}",+ ".claude-flow/hive-mind/state.json": "{\n \"initialized\": true,\n \"topology\": \"hierarchical\",\n \"workers\": [],\n \"consensus\": {\n \"pending\": [\n {\n \"proposalId\": \"proposal-1790903321981-23aov7\",\n \"type\": \"design\",\n \"value\": \"use raft for console\",\n \"proposedBy\": \"system\",\n \"proposedAt\": \"2026-10-02T01:08:41.981Z\",\n \"votes\": {},\n \"status\": \"pending\",\n \"strategy\": \"raft\",\n \"term\": 1,\n \"timeoutAt\": \"2026-10-02T01:09:11.981Z\"\n }\n ],\n \"history\": []\n },\n \"sharedMemory\": {},\n \"createdAt\": \"2026-10-02T01:08:41.632Z\",\n \"updatedAt\": \"2026-10-02T01:08:41.981Z\",\n \"consensusStrategy\": \"byzantine\",\n \"queen\": {\n \"agentId\": \"queen-1790903321632\",\n \"electedAt\": \"2026-10-02T01:08:41.632Z\",\n \"term\": 1\n },\n \"hiveToken\": \"4d377e5746f657255af8774e4a00fc6f4685d980f0a9ec3561ae03bf0992c861\"\n}",+ ".claude-flow/metrics/swarm-activity.json": "{\n \"timestamp\": \"2026-10-02T01:03:52.601Z\",\n \"swarm\": {\n \"active\": true,\n \"agent_count\": 2,\n \"coordination_active\": true\n }\n}",+ ".claude-flow/config.yaml": "# RuFlo V3 Runtime Configuration\n# Generated: 2026-10-02T01:03:40.517Z\n\nversion: \"3.0.0\"\n\nswarm:\n topology: mesh\n maxAgents: 5\n autoScale: true\n coordinationStrategy: consensus\n\nmemory:\n backend: memory\n enableHNSW: false\n persistPath: .claude-flow/data\n cacheSize: 100\n # ADR-049: Self-Learning Memory\n learningBridge:\n enabled: false\n sonaMode: balanced\n confidenceDecayRate: 0.005\n accessBoostAmount: 0.03\n consolidationThreshold: 10\n memoryGraph:\n enabled: false\n pageRankDamping: 0.85\n maxNodes: 5000\n similarityThreshold: 0.8\n agentScopes:\n enabled: false\n defaultScope: project\n\nneural:\n enabled: false\n modelPath: .claude-flow/neural\n\nhooks:\n enabled: true\n autoExecute: true\n\nmcp:\n autoStart: false\n port: 3000\n",+ ".claude-flow/harness-active-policy.json": "{\n \"championId\": \"sha256:6141a8ea990c5063b77e090ae8f37f9c539d8aa8f58dcceb30f3a82f97e57319\",\n \"provenanceTier\": \"oracle:test-exec\",\n \"layer\": \"framework/node-cli\",\n \"appliedAt\": 1790903031380,\n \"previous\": \"\",\n \"params\": {\n \"alpha\": 0.3,\n \"subjectWeight\": 1,\n \"mmrLambda\": 0.5,\n \"bodyWeight\": 1.5,\n \"typePenaltyFactor\": 0.5\n }\n}",+ ".claude-flow/neural/stats.json": "{\n \"trajectoriesRecorded\": 30797,\n \"patternsLearned\": 30781,\n \"signalsProcessed\": 18839,\n \"lastAdaptation\": 1790902994811\n}",+ ".swarm/model-router-state.json": "{\n \"totalDecisions\": 11,\n \"modelDistribution\": {\n \"haiku\": 0,\n \"sonnet\": 6,\n \"opus\": 5,\n \"inherit\": 0\n },\n \"avgComplexity\": 0.2153766233766234,\n \"avgConfidence\": 0.6024569410521556,\n \"circuitBreakerTrips\": 0,\n \"lastUpdated\": \"2026-09-27T17:34:53.630Z\",\n \"learningHistory\": [\n {\n \"task\": \"say hi\",\n \"model\": \"sonnet\",\n \"complexity\": 0.10462857142857143,\n \"outcome\": \"success\",\n \"timestamp\": \"2026-09-27T17:34:09.036Z\"\n },\n {\n \"task\": \"say hi\",\n \"model\": \"sonnet\",\n \"complexity\": 0.10462857142857143,\n \"outcome\": \"success\",\n \"timestamp\": \"2026-09-27T17:34:09.040Z\"\n },\n {\n \"task\": \"Find the file\",\n \"model\": \"sonnet\",\n \"complexity\": 0.12872857142857141,\n \"outcome\": \"success\",\n \"timestamp\": \"2026-09-27T17:34:47.655Z\"\n },\n {\n \"task\": \"Find the file\",\n \"model\": \"sonnet\",\n \"complexity\": 0.12872857142857141,\n \"outcome\": \"success\",\n \"timestamp\": \"2026-09-27T17:34:47.658Z\"\n },\n {\n \"task\": \"Find the file\",\n \"model\": \"sonnet\",\n \"complexity\": 0.12872857142857141,\n \"outcome\": \"success\",\n \"timestamp\": \"2026-09-27T17:34:47.663Z\"\n }\n ],\n \"version\": 2,\n \"priors\": {\n \"low\": {\n \"haiku\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"sonnet\": {\n \"alpha\": 4.5,\n \"beta\": 2.5\n },\n \"opus\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"inherit\": {\n \"alpha\": 1,\n \"beta\": 1\n }\n },\n \"med\": {\n \"haiku\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"sonnet\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"opus\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"inherit\": {\n \"alpha\": 1,\n \"beta\": 1\n }\n },\n \"high\": {\n \"haiku\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"sonnet\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"opus\": {\n \"alpha\": 1,\n \"beta\": 1\n },\n \"inherit\": {\n \"alpha\": 1,\n \"beta\": 1\n }\n }\n },\n \"priorsById\": {\n \"low\": {\n \"inclusionai/ling-2.6-flash\": {\n \"alpha\": 4,\n \"beta\": 1\n },\n \"qwen3.6:27b\": {\n \"alpha\": 2.4,\n \"beta\": 1.6\n }\n },\n \"med\": {},\n \"high\": {}\n }\n}",+ ".claude-flow/routing-outcomes.json": "{\n \"outcomes\": [\n {\n \"task\": \"implement auth token refresh\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.9,\n \"keywords\": [\n \"implement\",\n \"auth\",\n \"token\",\n \"refresh\"\n ],\n \"timestamp\": \"2026-09-27T17:34:39.779Z\"\n },\n {\n \"task\": \"implement auth token refresh\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.9,\n \"keywords\": [\n \"implement\",\n \"auth\",\n \"token\",\n \"refresh\"\n ],\n \"timestamp\": \"2026-09-27T17:34:39.915Z\"\n },\n {\n \"task\": \"implement authentication\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.95,\n \"keywords\": [\n \"implement\",\n \"authentication\"\n ],\n \"timestamp\": \"2026-09-27T19:07:15.374Z\"\n },\n {\n \"task\": \"implement authentication\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.95,\n \"keywords\": [\n \"implement\",\n \"authentication\"\n ],\n \"timestamp\": \"2026-09-27T19:07:31.071Z\"\n },\n {\n \"task\": \"implement authentication\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.95,\n \"keywords\": [\n \"implement\",\n \"authentication\"\n ],\n \"timestamp\": \"2026-09-27T19:07:32.571Z\"\n },\n {\n \"task\": \"implement authentication\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.95,\n \"keywords\": [\n \"implement\",\n \"authentication\"\n ],\n \"timestamp\": \"2026-09-27T19:07:34.084Z\"\n },\n {\n \"task\": \"implement authentication\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.95,\n \"keywords\": [\n \"implement\",\n \"authentication\"\n ],\n \"timestamp\": \"2026-09-27T19:51:49.034Z\"\n },\n {\n \"task\": \"implement authentication\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.95,\n \"keywords\": [\n \"implement\",\n \"authentication\"\n ],\n \"timestamp\": \"2026-09-27T19:51:50.614Z\"\n },\n {\n \"task\": \"implement authentication\",\n \"agent\": \"coder\",\n \"success\": true,\n \"quality\": 0.95,\n \"keywords\": [\n \"implement\",\n \"authentication\"\n ],\n \"timestamp\": \"2026-09-27T19:51:52.200Z\"\n }\n ]\n}",+ ".claude-flow/daemon-state.json": "{\n \"running\": true,\n \"startedAt\": \"2026-07-11T23:23:39.387Z\",\n \"workers\": {\n \"map\": {\n \"runCount\": 137,\n \"successCount\": 137,\n \"failureCount\": 0,\n \"averageDurationMs\": 0.627737226277372,\n \"lastRun\": \"2026-07-11T23:28:05.152Z\",\n \"lastStartedAt\": \"2026-07-11T23:28:05.152Z\",\n \"nextRun\": \"2026-07-11T23:28:05.152Z\",\n \"isRunning\": false\n },\n \"audit\": {\n \"runCount\": 186,\n \"successCount\": 186,\n \"failureCount\": 0,\n \"averageDurationMs\": 62022.98387096774,\n \"lastRun\": \"2026-07-11T23:27:11.397Z\",\n \"lastStartedAt\": \"2026-07-11T23:26:32.760Z\",\n \"nextRun\": \"2026-07-11T23:37:11.398Z\",\n \"isRunning\": false\n },\n \"optimize\": {\n \"runCount\": 94,\n \"successCount\": 94,\n \"failureCount\": 5,\n \"averageDurationMs\": 368130.6382978723,\n \"lastRun\": \"2026-07-11T23:03:53.749Z\",\n \"lastStartedAt\": \"2026-07-11T23:27:39.391Z\",\n \"nextRun\": \"2026-07-11T23:27:39.387Z\",\n \"isRunning\": true\n },\n \"consolidate\": {\n \"runCount\": 68,\n \"successCount\": 68,\n \"failureCount\": 0,\n \"averageDurationMs\": 0.7499999999999999,\n \"lastRun\": \"2026-07-11T23:07:06.141Z\",\n \"lastStartedAt\": \"2026-07-11T23:07:06.141Z\",\n \"nextRun\": \"2026-07-11T23:37:06.141Z\",\n \"isRunning\": false\n },\n \"testgaps\": {\n \"runCount\": 92,\n \"successCount\": 92,\n \"failureCount\": 3,\n \"averageDurationMs\": 108074.63043478261,\n \"lastRun\": \"2026-07-11T23:05:25.360Z\",\n \"lastStartedAt\": \"2026-07-11T23:04:19.732Z\",\n \"nextRun\": \"2026-07-11T23:31:39.387Z\",\n \"isRunning\": false\n },\n \"backup\": {\n \"runCount\": 2,\n \"successCount\": 2,\n \"failureCount\": 0,\n \"averageDurationMs\": 1,\n \"lastRun\": \"2026-07-11T13:30:47.115Z\",\n \"lastStartedAt\": \"2026-07-11T13:30:47.114Z\",\n \"nextRun\": \"2026-07-12T13:30:47.115Z\",\n \"isRunning\": false\n },\n \"harness\": {\n \"runCount\": 6,\n \"successCount\": 6,\n \"failureCount\": 0,\n \"averageDurationMs\": 4.166666666666667,\n \"lastRun\": \"2026-07-11T19:32:29.899Z\",\n \"lastStartedAt\": \"2026-07-11T19:32:29.898Z\",\n \"nextRun\": \"2026-07-12T01:32:29.899Z\",\n \"isRunning\": false\n },\n \"predict\": {\n \"runCount\": 0,\n \"successCount\": 0,\n \"failureCount\": 0,\n \"averageDurationMs\": 0,\n \"isRunning\": false\n },\n \"document\": {\n \"runCount\": 0,\n \"successCount\": 0,\n \"failureCount\": 0,\n \"averageDurationMs\": 0,\n \"isRunning\": false\n }\n },\n \"config\": {\n \"autoStart\": false,\n \"logDir\": \"/home/ruvultra/projects/ruflo/.claude-flow/logs\",\n \"stateFile\": \"/home/ruvultra/projects/ruflo/.claude-flow/daemon-state.json\",\n \"maxConcurrent\": 2,\n \"workerTimeoutMs\": 960000,\n \"resourceThresholds\": {\n \"maxCpuLoad\": 25.6,\n \"minFreeMemoryPercent\": 10\n },\n \"ttlMs\": 43200000,\n \"idleShutdownMs\": 0,\n \"workers\": [\n {\n \"type\": \"map\",\n \"intervalMs\": 900000,\n \"offsetMs\": 0,\n \"priority\": \"normal\",\n \"description\": \"Codebase mapping\",\n \"enabled\": true\n },\n {\n \"type\": \"audit\",\n \"intervalMs\": 600000,\n \"offsetMs\": 120000,\n \"priority\": \"critical\",\n \"description\": \"Security analysis\",\n \"enabled\": true\n },\n {\n \"type\": \"optimize\",\n \"intervalMs\": 900000,\n \"offsetMs\": 240000,\n \"priority\": \"high\",\n \"description\": \"Performance optimization\",\n \"enabled\": true\n },\n {\n \"type\": \"consolidate\",\n \"intervalMs\": 1800000,\n \"offsetMs\": 360000,\n \"priority\": \"low\",\n \"description\": \"Memory distillation (ADR-174)\",\n \"enabled\": true\n },\n {\n \"type\": \"testgaps\",\n \"intervalMs\": 1200000,\n \"offsetMs\": 480000,\n \"priority\": \"normal\",\n \"description\": \"Test coverage analysis\",\n \"enabled\": true\n },\n {\n \"type\": \"backup\",\n \"intervalMs\": 86400000,\n \"offsetMs\": 600000,\n \"priority\": \"low\",\n \"description\": \"Nightly memory DB backup (WAL-safe, rotated)\",\n \"enabled\": true\n },\n {\n \"type\": \"harness\",\n \"intervalMs\": 21600000,\n \"offsetMs\": 720000,\n \"priority\": \"low\",\n \"description\": \"Self-optimizing harness loop (opt-in RUFLO_HARNESS_LOOP, $0-default)\",\n \"enabled\": true\n },\n {\n \"type\": \"predict\",\n \"intervalMs\": 600000,\n \"offsetMs\": 0,\n \"priority\": \"low\",\n \"description\": \"Predictive preloading\",\n \"enabled\": false\n },\n {\n \"type\": \"document\",\n \"intervalMs\": 3600000,\n \"offsetMs\": 0,\n \"priority\": \"low\",\n \"description\": \"Auto-documentation\",\n \"enabled\": false\n }\n ]\n },\n \"savedAt\": \"2026-07-11T23:28:05.152Z\"\n}",+ ".swarm/sona-patterns.json": "{\"version\": \"1.0.0\", \"patterns\": {\"goal-planner:agent+build+design+dogfood+implement+mesh+radio+research+search+streaming\": {\"agent\": \"goal-planner\"}, \"goal-planner:check+cross+drive+machine+mesh+research+search+sota+system+tailnet\": {\"agent\": \"goal-planner\"}}}",+ ".claude/helpers/helpers.manifest.json": "{\"manifest\": {\"version\": \"3.32.24\", \"files\": {\"auto-memory-hook.mjs\": \"68be7e9a9eba7bf9c4e8a230db7bf61a243b965639f8504842799d6c6ca28762\", \"hook-handler.cjs\": \"50ea92a72651bdc95634f7588d56a5870963168eef5226f66ed14af3b47c8d9a\", \"intelligence.cjs\": \"bd1f8e4b034944aee1df0391dc47ac2e8cc4b3aa542c65407a59d49620bbf76b\", \"statusline.cjs\": \"d2a0eac56d1267d8dbed2d70b09feb592299469196ec4b215909f2b052144882\"}}, \"signature\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\", \"algorithm\": \"ed25519\"}",+}++/** What each CLI probe printed in that project (paths rewritten to /work). */+export const CLI_OUT: Readonly<Record<string, string>> = {+ "version": "ruflo v3.50.0\n",+ "memory-stats": "Transformers.js loaded: Xenova/all-MiniLM-L6-v2\n{\n \"unreadStore\": {\n \"path\": \"/work/.swarm/agentdb-memory.db\",\n \"rows\": 2\n },\n \"backend\": \"sqlite (bridge, brute-force cosine)\",\n \"entries\": {\n \"total\": 1,\n \"vectors\": 0,\n \"text\": 1\n },\n \"storage\": {\n \"total\": \"1921288 B\",\n \"location\": \"/work/.swarm/memory.db\"\n },\n \"version\": \"unknown\",\n \"oldestEntry\": \"2026-10-02T01:03:53.176Z\",\n \"newestEntry\": \"2026-10-02T01:03:53.176Z\"\n}\n",+ "mh-score": "{\n \"schema\": 1,\n \"repo\": \"proj\",\n \"harnessFit\": 42,\n \"compileConfidence\": 12,\n \"taskCoverage\": 35,\n \"toolSafety\": 90,\n \"memoryUsefulness\": 6,\n \"estCostPerRunUsd\": 0.024,\n \"recommendedMode\": \"CLI + MCP\",\n \"archetype\": \"mcp-server-harness\",\n \"template\": \"vertical:coding\",\n \"scaffoldReady\": false,\n \"hardConstraints\": \"5/6\",\n \"generatedAt\": \"2026-10-02T01:09:37.764Z\",\n \"durationMs\": 55\n}\n",+ "mh-flywheel": "[INFO] Executing tool: metaharness_flywheel\n Parameters: {\"op\":\"receipts\"}\n\n[OK] Tool executed in 6.53ms\n\nResult:\n{\n \"success\": true,\n \"data\": {\n \"state\": {\n \"version\": 1,\n \"activeChampionRef\": null,\n \"activePolicy\": null,\n \"activeGateVersion\": null,\n \"activePolicySchemaVersion\": null,\n \"activeSafetyEnvelopeRef\": null,\n \"ledgerHead\": \"sha256:0000000000000000000000000000000000000000000000000000000000000000\",\n \"servingEpoch\": 0,\n \"materializedServingEpoch\": 0,\n \"servedChampionRef\": null,\n \"receiptStates\": {},\n \"commits\": []\n },\n \"ledger\": {\n \"valid\": true,\n \"errors\": [],\n \"commits\": 0,\n \"head\": \"sha256:0000000000000000000000000000000000000000000000000000000000000000\"\n }\n },\n \"degraded\": false,\n \"exitCode\": 0\n}\n",+ "intel": "[INFO] Executing tool: hooks_intelligence_stats\n\n[OK] Tool executed in 40.75ms\n\nResult:\n{\n \"sona\": {\n \"trajectoriesTotal\": 0,\n \"trajectoriesSuccessful\": 0,\n \"avgLearningTimeMs\": 0,\n \"patternsLearned\": 0,\n \"patternCategories\": {\n \"learned\": 0\n },\n \"successRate\": 0,\n \"implementation\": \"real-sona\"\n },\n \"moe\": {\n \"expertsTotal\": 8,\n \"expertsActive\": 0,\n \"routingDecisions\": 0,\n \"avgRoutingTimeMs\": 0.15,\n \"avgConfidence\": 0,\n \"loadBalance\": {\n \"giniCoefficient\": 0,\n \"coefficientOfVariation\": 1,\n \"expertUsage\": {\n \"coder\": 0,\n \"tester\": 0,\n \"reviewer\": 0,\n \"architect\": 0,\n \"security\": 0,\n \"performance\": 0,\n \"researcher\": 0,\n \"coordinator\": 0\n }\n },\n \"implementation\": \"real-moe\"\n },\n \"ewc\": {\n \"consolidations\": 0,\n \"catastrophicForgettingPrevented\": 0,\n \"fisherUpdates\": 0,\n \"avgPenalty\": 0,\n \"totalPatterns\": 0,\n \"implementation\": \"real-ewc++\"\n },\n \"flash\": {\n \"speedup\": 0,\n \"avgComputeTimeMs\": 0,\n \"blockSize\": 64,\n \"implementation\": \"real-flash-attention\"\n },\n \"lora\": {\n \"rank\": 8,\n \"alpha\": 16,\n \"adaptations\": 0,\n \"avgLoss\": 0,\n \"implementation\": \"real-lora\"\n },\n \"ruvllm\": {\n \"coordinator\": \"active\",\n \"trajectories\": 0,\n \"contrastiveTrainer\": {\n \"triplets\": 0,\n \"agents\": 0\n },\n \"trainingBackend\": \"ruvllm\",\n \"graphDatabase\": {\n \"backend\": \"graph-node\",\n \"totalNodes\": 0,\n \"totalEdges\": 0,\n \"avgDegree\": 0\n }\n },\n \"hnsw\": {\n \"indexSize\": 0,\n \"avgSearchTimeMs\": 0.12,\n \"cacheHitRate\": 0.78,\n \"memoryUsageMb\": 0\n },\n \"modelRouter\": {\n \"totalDecisions\": 0,\n \"modelDistribution\": {\n \"haiku\": 0,\n \"sonnet\": 0,\n \"opus\": 0,\n \"inherit\": 0\n },\n \"routedByCounts\": {\n \"heuristic\": 0,\n \"bandit-fallback\": 0,\n \"hybrid\": 0\n },\n \"neuralBackendCounts\": {\n \"metaharness-knn\": 0,\n \"metaharness-krr\": 0,\n \"fastgrnn\": 0\n },\n \"ab\": {\n \"comparisons\": 0,\n \"disagreements\": 0,\n \"disagreementRate\": 0\n },\n \"avgComplexity\": 0.5,\n \"avgConfidence\": 0.8\n },\n \"neuralRouter\": {\n \"enabled\": false,\n \"available\": false,\n \"routedBy\": null,\n \"reason\": \"CLAUDE_FLOW_ROUTER_NEURAL!=1\"\n },\n \"costSavings\": null,\n \"costProjection\": null,\n \"recent24h\": null,\n \"warmestBanditCell\": null,\n \"dataSource\": \"real-implementations\",\n \"lastUpdated\": \"2026-10-02T01:09:38.524Z\"\n}\n",+ "bbs-peers": "[INFO] Executing tool: federation_bbs_peers\n\n[OK] Tool executed in 9.10ms\n\nResult:\n{\n \"success\": true,\n \"degraded\": true,\n \"reason\": \"agentbbs-not-found\"\n}\n",+ "channels": "[INFO] Executing tool: x_federation_channel_list\n\n[OK] Tool executed in 7.45ms\n\nResult:\n{\n \"keyStoredAt\": \"/home/ruvultra/.ruflo/channels.json\",\n \"channels\": []\n}\n",+ "memory-list": "Transformers.js loaded: Xenova/all-MiniLM-L6-v2\n[\n {\n \"id\": \"entry_1790903033176_\",\n \"key\": \"console-k1\",\n \"namespace\": \"console\",\n \"size\": 5,\n \"accessCount\": 0,\n \"createdAt\": 1790903033176,\n \"updatedAt\": 1790903033176,\n \"hasEmbedding\": true,\n \"provenanceType\": \"unknown\"\n }\n]\n",+}diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.tsnew file mode 100644index 0000000000..b81808f698--- /dev/null+++ b/plugins/ruflo-console/tests/fixtures/world.ts@@ -0,0 +1,187 @@+import type { On, RenderElement, RenderInput, RenderNode, SessionStartInput } from 'claude-code'+import type { Plugin } from 'claude-code/testing'++import { CLI_OUT } from './ruflo-run'++export const PLUGIN = 'ruflo-console'+export const CWD = '/work'+export const HOME = '/home/dev'+export const SESSION: SessionStartInput = { surface: 'terminal', isInteractive: true, cwd: CWD }++export const paneAt = (bodyColumns = 100, bodyRows = 40, isFocused = true, surface: 'terminal' | 'desktop' = 'terminal'): RenderInput<'Pane'> =>+ ({+ component: 'Pane',+ surface,+ requestId: 'ruflo-console',+ viewport: { columns: 180, rows: 48, isFullscreen: true },+ props: { title: 'ruflo console', isFocused, bodyColumns, placement: 'dock', scroll: { offset: 0, bodyRows }, view: {} },+ }) as RenderInput<'Pane'>++export const BAND: RenderInput<'AbovePrompt'> = {+ component: 'AbovePrompt',+ surface: 'terminal',+ requestId: 'band',+ viewport: { columns: 120, rows: 40, isFullscreen: true },+ 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 type Answer = { exitCode: number; stdout: string; stderr: string } | { deny: string }++export type World = {+ files: Map<string, string>+ runs: string[][]+ blits: string[]+ opened: string[]+ 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. */+ respond: (argv: readonly string[]) => Answer+ put: (path: string, text: string) => void+}++/** The captured CLI output each probe's argv gets. */+export function cliAnswer(argv: readonly string[]): Answer {+ const line = argv.join(' ')+ const out = (name: string): Answer => ({ exitCode: 0, stdout: CLI_OUT[name] ?? '', stderr: '' })++ if (line.endsWith('--version')) return out('version')+ if (line.includes('memory stats')) return out('memory-stats')+ if (line.includes('memory list')) return out('memory-list')+ if (line.includes('metaharness score')) return out('mh-score')+ if (line.includes('metaharness_flywheel')) return out('mh-flywheel')+ if (line.includes('hooks_intelligence_stats')) return out('intel')+ if (line.includes('federation_bbs_peers')) return out('bbs-peers')+ if (line.includes('x_federation_channel_list')) return out('channels')++ return { exitCode: 0, stdout: '{"success": true}', stderr: '' }+}++/**+ * Seats an in-memory world beneath the plugin: files under CWD and HOME, a process table, the store, the panes, and+ * records of what the mod asked for. `refuseAll` refuses every one of those affordances, as an administrator may.+ */+export function worldOf(on: On, files: Readonly<Record<string, string>>, options: { refuseAll?: boolean; home?: Readonly<Record<string, string>> } = {}): World {+ let tick = 1_000+ const all = new Map<string, string>([...Object.entries(files).map(([path, text]) => [`${CWD}/${path}`, text] as const), ...Object.entries(options.home ?? {}).map(([path, text]) => [`${HOME}/${path}`, text] as const)])+ const mtimes = new Map<string, number>([...all.keys()].map(path => [path, tick]))+ const world: World = {+ files: all,+ runs: [],+ blits: [],+ opened: [],+ stored: new Map(),+ panes: [],+ respond: cliAnswer,+ put: (path, text) => {+ tick += 1_000+ all.set(`${CWD}/${path}`, text)+ mtimes.set(`${CWD}/${path}`, tick)+ },+ }+ const refuse = options.refuseAll === true++ on('session.start', ($, e) => ({ cwd: e.cwd }))+ on('fs.read', ($, e) => (refuse || !all.has(e.path) ? { deny: `ENOENT: ${e.path}` } : { value: all.get(e.path) as string }))+ on('fs.stat', ($, e) => {+ const text = all.get(e.path)++ return refuse || text === undefined ? { deny: `ENOENT: ${e.path}` } : { value: { kind: 'file' as const, size: text.length, mtimeMs: mtimes.get(e.path) ?? 0, isLink: false } }+ })+ on('fs.list', ($, e) => {+ const prefix = `${e.path ?? CWD}/`+ const names = [...all.keys()].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/')).map(path => path.slice(prefix.length))++ return refuse || names.length === 0 ? { deny: 'ENOENT' } : { value: names.map(name => ({ name, kind: 'file' as const, size: 1, mtimeMs: 1, isLink: false })) }+ })+ on('process.run', ($, e) => {+ world.runs.push([...e.argv])++ const answer = refuse ? { deny: 'process.run withheld' } : world.respond(e.argv)++ return 'deny' in answer ? { deny: answer.deny } : { value: { ...answer, isStdoutTruncated: false, isStderrTruncated: false } }+ })+ on('env.get', () => (refuse ? { deny: 'env withheld' } : { value: HOME }))+ on('settings.read', () => (refuse ? { deny: 'settings withheld' } : { value: { enabledPlugins: { 'ruflo-core@ruflo': true } } as never }))+ on('session.usage', () => (refuse ? { deny: 'usage withheld' } : { value: { context: { tokens: 50_000, window: 200_000, percent: 25 }, rateLimits: [], cost: { usd: 0.4213 } } as never }))+ on('tool.list', () => (refuse ? { deny: 'tools withheld' } : { value: [{ name: 'mcp__claude-flow__swarm_init' }, { name: 'mcp__claude-flow__claims_board' }, { name: 'Read' }] as never }))+ on('store.get', ($, e) => (refuse ? { deny: 'store withheld' } : { value: world.stored.get(e.key) }))+ on('store.set', ($, e) => {+ if (refuse) return { deny: 'store withheld' }++ world.stored.set(e.key, e.value)++ return { value: undefined }+ })+ on('command.register', ($, e) => (refuse ? { deny: 'commands withheld' } : { value: { command: e.name } }))+ on('ui.open', ($, e) => {+ if (refuse) return { deny: 'panes withheld' } as never++ world.opened.push(e.id)+ world.panes = [{ id: e.id, title: e.title ?? e.id, isShown: true, isFocused: e.focus === true, isPlaced: true }]++ return { value: { isPlaced: true } } as never+ })+ on('ui.close', ($, e) => {+ world.panes = world.panes.filter(pane => pane.id !== e.id)++ return { value: undefined } as never+ })+ on('ui.panes', () => (refuse ? { deny: 'panes withheld' } : { value: world.panes as never }))+ on('ui.blit', ($, e) => {+ world.blits.push(e.key)++ return { value: {} }+ })+ on('ui.toast', () => ({ value: undefined }))++ return world+}++/** A stand-in for ruflo-mods' `$.ruflo` noun, answering a fixed snapshot and recording segments. */+export function fakeRuflo(segments: (string | null)[] = []): Plugin {+ const route = { agent: 'tester', confidence: 0.6, matched: true, reason: 'keyword: test' }++ return {+ name: 'fake-ruflo',+ tier: 'user',+ register: on => {+ on('engine.create', async ($, e, next) => {+ const beneath = await next(e)+ const added = {+ ruflo: {+ segment: async (input: { id: string; text: string | null }) => void segments.push(input.text),+ lastRoute: async () => route,+ snapshot: async () => ({ owned: ['route', 'post-edit'], routed: 4, lastRoute: route, policy: 'observe', tightened: 1, observed: 2, edits: 3, budget: { level: 'WARNING', usd: 3.9, limit: 5 }, segments: [] }),+ },+ }++ return { ...added, ...beneath }+ })+ },+ }+}++export function stringsOf(node: RenderNode | RenderElement | null | undefined): string[] {+ if (node === null || node === undefined || typeof node === 'boolean') return []+ if (typeof node === 'string' || typeof node === 'number') return [String(node)]++ const props = (node as { props?: Record<string, unknown> }).props+ const own = node.type === 'Button' && typeof props?.label === 'string' ? [props.label] : []+ const children = (node as { children?: readonly RenderNode[] }).children ?? []++ return [...own, ...children.flatMap(child => stringsOf(child))]+}++export const textOf = (node: RenderNode | RenderElement | null | undefined): string => stringsOf(node).join('\n')++export function elementsOf(node: RenderNode | RenderElement | null | undefined, type: string): RenderElement[] {+ if (node === null || node === undefined || typeof node !== 'object') return []++ const children = (node as { children?: readonly RenderNode[] }).children ?? []++ return [...(node.type === type ? [node as RenderElement] : []), ...children.flatMap(child => elementsOf(child, type))]+}++export const keyOf = (element: RenderElement): string => String((element as { key?: unknown }).key ?? (element as { props?: { key?: unknown } }).props?.key ?? '')diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.tsnew file mode 100644index 0000000000..1c0036cff3--- /dev/null+++ b/plugins/ruflo-console/tests/views.test.ts@@ -0,0 +1,152 @@+import type { TestBody } from 'claude-code/testing'+import { describe, expect, mock, test } from 'claude-code/testing'++import { HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'+import { command, elementsOf, fakeRuflo, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'++const HOME_FILES = {+ '.claude/plugins/installed_plugins.json': JSON.stringify({+ version: 2,+ plugins: {+ 'ruflo-core@ruflo': [{ scope: 'user', version: '0.2.6', lastUpdated: '2026-07-30T12:06:11.791Z' }],+ 'ruflo-swarm@ruflo': [{ scope: 'user', version: '0.2.1' }],+ },+ }),+ '.claude/plugins/known_marketplaces.json': JSON.stringify({ ruflo: { installLocation: '/home/dev/.claude/plugins/marketplaces/ruflo', lastUpdated: '2026-09-03T18:45:31.282Z', autoUpdate: true } }),+ '.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) {+ 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 }+}++describe('views', () => {+ test('overview: every subsystem from disk, the CLI or the engine, the activity raster, nothing invented', 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')++ expect(text).toContain('v3.50.0 (npx-offline)')+ expect(text).toContain('running per daemon-state.json')+ expect(text).toContain('2 ruflo 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'])+ })++ test('swarms: the topology graph, agents, the hive with its proposal, and no hive token', async ($, on) => {+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ const { text, tree } = await drawn($, 'swarm')++ expect(elementsOf(tree, 'Raster').map(keyOf)).toEqual(['topology'])+ expect(text).toContain('hierarchical · specialized · running · max 6')+ expect(text).toMatch(/coder\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)+ })++ test('claims: the board with a stealable claim, TTL bars, and the act row', async ($, on) => {+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ const { text, tree } = await drawn($, 'claims')++ 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']))+ })++ test('federation: local identity and channels, the relay never asked while the network option is off', async ($, on) => {+ const world = worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ const { text } = await drawn($, 'federation')++ 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) => {+ worldOf(on, RUFLO_FILES, { home: HOME_FILES })+ mock.clock(on)+ await $.session.start(SESSION)++ const { text } = await drawn($, 'plugins')++ 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) => {+ fakeRuflo().register(on, {})+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ const { text, tree } = await drawn($, 'learning')++ 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'])+ })++ test('metaharness: the five scores, 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')++ expect(elementsOf(tree, 'Raster').map(keyOf)).toEqual(['score'])+ 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) => {+ fakeRuflo().register(on, {})+ worldOf(on, RUFLO_FILES)+ mock.clock(on)+ await $.session.start(SESSION)++ const { text } = await drawn($, 'memory')++ 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%)')+ })+})diff --git a/plugins/ruflo-console/tsconfig.json b/plugins/ruflo-console/tsconfig.jsonnew file mode 100644index 0000000000..1e3839a1be--- /dev/null+++ b/plugins/ruflo-console/tsconfig.json@@ -0,0 +1,19 @@+{+ "//": "Self-contained on purpose: bundlers (vite/esbuild in the root CI vitest) load this file for every module they transform, so it must not extend a file that only exists after Claude Code (>= 2.1.287) has loaded the plugin. Claude Code writes its declarations to .claude-plugin/types/ (gitignored) on load or validate; tsc -p . then reads them through typeRoots.",+ "compilerOptions": {+ "target": "es2023",+ "lib": ["es2023"],+ "module": "esnext",+ "moduleResolution": "bundler",+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "noEmit": true,+ "skipLibCheck": true,+ "jsx": "react",+ "jsxFactory": "h",+ "jsxFragmentFactory": "Fragment",+ "typeRoots": ["./.claude-plugin/types"],+ "types": ["claude-code", "claude-code-tools", "claude-code-mcp"]+ },+ "include": ["hooks", "types", "tests"]+}diff --git a/plugins/ruflo-console/types/index.d.ts b/plugins/ruflo-console/types/index.d.tsnew file mode 100644index 0000000000..44fb545ead--- /dev/null+++ b/plugins/ruflo-console/types/index.d.ts@@ -0,0 +1,38 @@+/**+ * Vendored `$.ruflo` contract (ruflo-mods, ADR-404): the subset ruflo-console calls. Source of truth:+ * plugins/ruflo-mods/types/index.d.ts, kept in step by tests/vendored-types.spec.ts. Where the ruflo mod is not seated+ * there is no `$.ruflo` and a call rejects; the console catches and says "ruflo-mods not seated".+ */+export type RufloSegment = { id: string; text: string | null }++export type RufloRoute = {+ agent: string+ confidence: number+ matched: boolean+ reason: string+}++export type RufloSnapshot = {+ owned: readonly ('route' | 'post-edit')[]+ routed: number+ lastRoute: RufloRoute | null+ policy: 'none' | 'legacy' | 'observe' | 'enforce' | 'unreadable'+ tightened: number+ observed: number+ edits: number+ budget?: { level: 'OK' | 'INFO' | 'WARNING' | 'CRITICAL' | 'HARD_STOP'; usd?: number; limit: number }+ segments: readonly { id: string; text: string }[]+}++declare module 'claude-code' {+ interface EngineInterface {+ ruflo: {+ /** Sets (or with `text: null` removes) one status bar segment. */+ segment: (input: RufloSegment) => Promise<void>+ /** The last route, or null before the first owned prompt. */+ lastRoute: () => Promise<RufloRoute | null>+ /** Everything above at once. */+ snapshot: () => Promise<RufloSnapshot>+ }+ }+}