Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(ruflo-swarm): swarm mod skeleton: readers, members, pane view, actions, commands

ruv5c133697ee82
diff --git a/plugins/ruflo-swarm/.claude-plugin/plugin.json b/plugins/ruflo-swarm/.claude-plugin/plugin.json
index de7e8b0c7b..cf339853be 100644
--- a/plugins/ruflo-swarm/.claude-plugin/plugin.json
+++ b/plugins/ruflo-swarm/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-swarm",
- "description": "Agent teams, swarm coordination, Monitor streams, and worktree isolation — wraps 4 swarm_* + 8 agent_* MCP tools (12 total) plus 6 topologies (hierarchical / mesh / hierarchical-mesh / ring / star / adaptive)",
- "version": "0.2.1",
+ "description": "Agent teams, swarm coordination, Monitor streams, and worktree isolation — wraps 4 swarm_* + 8 agent_* MCP tools (12 total) plus 6 topologies (hierarchical / mesh / hierarchical-mesh / ring / star / adaptive). With Claude Code function hooks on (early access), a live swarm pane: agent tiles lit by reads and writes, topology, task and claims board, cost, router pick and hive-mind votes, with buttons that act through the ruflo CLI",
+ "version": "0.3.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -17,6 +17,52 @@
"mcp",
"topologies",
"worktree-isolation",
- "monitor-stream"
- ]
+ "monitor-stream",
+ "mods",
+ "function-hooks",
+ "pane"
+ ],
+ "userConfig": {
+ "panel": {
+ "type": "string",
+ "title": "Swarm pane",
+ "description": "auto opens the pane when a ruflo swarm is on disk and the layout docks panes; command opens it only with /ruflo-swarm-pane or /ruflo-swarm:watch; off never opens it.",
+ "default": "auto",
+ "options": [
+ "auto",
+ "command",
+ "off"
+ ]
+ },
+ "cli": {
+ "type": "string",
+ "title": "ruflo CLI",
+ "description": "How the pane's buttons reach 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"
+ ]
+ },
+ "routeThreshold": {
+ "type": "number",
+ "title": "Router confidence threshold",
+ "description": "A router pick under this confidence (0 to 1) is shown as below threshold, with its score, rather than as a match.",
+ "default": 0.5
+ },
+ "injectSpawnContext": {
+ "type": "boolean",
+ "title": "Swarm note in subagent prompts",
+ "description": "Append a short note naming the ruflo swarm (id, topology, strategy, read from disk) to the prompt of each subagent Claude Code spawns.",
+ "default": false
+ },
+ "audit": {
+ "type": "boolean",
+ "title": "Audit trail",
+ "description": "Record a bounded trail of engine events (event and tool names, agent ids, times; never prompts, arguments or results) into ruflo memory namespace ruflo-swarm-audit every 30 seconds.",
+ "default": false
+ }
+ }
}
diff --git a/plugins/ruflo-swarm/.gitignore b/plugins/ruflo-swarm/.gitignore
new file mode 100644
index 0000000000..30b4a6a20f
--- /dev/null
+++ b/plugins/ruflo-swarm/.gitignore
@@ -0,0 +1 @@
+.claude/types/
diff --git a/plugins/ruflo-swarm/hooks/actions/argv.ts b/plugins/ruflo-swarm/hooks/actions/argv.ts
new file mode 100644
index 0000000000..a870c7eb97
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/actions/argv.ts
@@ -0,0 +1,154 @@
+import { idOf, plain } from '../reader/parse'
+import type { Snapshot } from '../reader/snapshot'
+
+/**
+ * One thing a button asks ruflo to do: the argv after the CLI prefix, fixed but for ids that passed `idOf`
+ * and one JSON argument built by `JSON.stringify` (an argv element, never a shell string), and how the disk
+ * shows that it happened, checked after the CLI exits.
+ */
+export type ActionSpec = {
+ label: string
+ args: readonly string[]
+ /** Asks the person to press again before it runs: stopping, stealing, handing off. */
+ isDestructive: boolean
+ /** What the disk shows once it took effect; absent where the CLI writes nothing the pane reads. */
+ verify?: (snapshot: Snapshot) => boolean
+ /** The words for `verify`, as the outcome line says them. */
+ expect: string
+}
+
+const exec = (tool: string, params: Record<string, unknown>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const
+
+/** `agent:<id>:<type>`, the claimant form the claims tools parse; a type is letters, digits and dashes. */
+function claimant(id: string, type: string): string | null {
+ const safeType = /^[A-Za-z0-9_-]{1,40}$/.test(type) ? type : null
+
+ return idOf(id) !== null && safeType !== null && !id.includes(':') ? `agent:${id}:${safeType}` : null
+}
+
+export function stopAgent(agentId: string): ActionSpec | null {
+ const id = idOf(agentId)
+
+ return id === null
+ ? null
+ : {
+ label: `stop agent ${id}`,
+ args: ['agent', 'stop', id],
+ isDestructive: true,
+ verify: snapshot => snapshot.agents.find(agent => agent.id === id)?.status !== 'busy' && snapshot.agents.find(agent => agent.id === id)?.status !== 'idle',
+ expect: 'the agent no longer idle or busy in .claude-flow/agents/store.json',
+ }
+}
+
+export function claimTask(taskId: string, agentId: string, agentType: string): ActionSpec | null {
+ const issueId = idOf(taskId)
+ const who = claimant(agentId, agentType)
+
+ return issueId === null || who === null
+ ? null
+ : {
+ label: `claim ${issueId} for ${agentType}`,
+ args: exec('claims_claim', { issueId, claimant: who }),
+ isDestructive: false,
+ verify: snapshot => snapshot.claims.some(claim => claim.issueId === issueId && claim.claimant.id === agentId),
+ expect: 'the claim in .claude-flow/claims/claims.json',
+ }
+}
+
+export function markStealable(taskId: string): ActionSpec | null {
+ const issueId = idOf(taskId)
+
+ return issueId === null
+ ? null
+ : {
+ label: `offer ${issueId} for stealing`,
+ args: exec('claims_mark-stealable', { issueId, reason: 'voluntary' }),
+ isDestructive: false,
+ verify: snapshot => snapshot.claims.some(claim => claim.issueId === issueId && claim.isStealable),
+ expect: 'the claim marked stealable',
+ }
+}
+
+export function stealTask(taskId: string, agentId: string, agentType: string): ActionSpec | null {
+ const issueId = idOf(taskId)
+ const stealer = claimant(agentId, agentType)
+
+ return issueId === null || stealer === null
+ ? null
+ : {
+ label: `steal ${issueId} for ${agentType}`,
+ args: exec('claims_steal', { issueId, stealer }),
+ isDestructive: true,
+ verify: snapshot => snapshot.claims.some(claim => claim.issueId === issueId && claim.claimant.id === agentId),
+ expect: 'the claim held by the selected agent',
+ }
+}
+
+export function handoffTask(taskId: string, from: { id: string; type: string }, to: { id: string; type: string }): ActionSpec | null {
+ const issueId = idOf(taskId)
+ const fromWho = claimant(from.id, from.type)
+ const toWho = claimant(to.id, to.type)
+
+ return issueId === null || fromWho === null || toWho === null || from.id === to.id
+ ? null
+ : {
+ label: `hand ${issueId} to ${to.type}`,
+ args: exec('claims_handoff', { issueId, from: fromWho, to: toWho }),
+ isDestructive: true,
+ verify: snapshot => snapshot.claims.some(claim => claim.issueId === issueId && (claim.handoffTo === to.id || claim.claimant.id === to.id)),
+ expect: 'a handoff to the selected agent on the claim',
+ }
+}
+
+/** Pauses or resumes the work an agent claimed: ruflo pauses claims, not agents. */
+export function setClaimStatus(taskId: string, status: 'paused' | 'active'): ActionSpec | null {
+ const issueId = idOf(taskId)
+
+ return issueId === null
+ ? null
+ : {
+ label: `${status === 'paused' ? 'pause' : 'resume'} the claim on ${issueId}`,
+ args: exec('claims_status', { issueId, status }),
+ isDestructive: false,
+ verify: snapshot => snapshot.claims.some(claim => claim.issueId === issueId && claim.status === status),
+ expect: `the claim ${status}`,
+ }
+}
+
+export function vote(proposalId: string, voterId: string, isFor: boolean): ActionSpec | null {
+ const id = idOf(proposalId)
+ const voter = idOf(voterId)
+
+ return id === null || voter === null
+ ? null
+ : {
+ label: `vote ${isFor ? 'yes' : 'no'} on ${id} as ${voter}`,
+ args: ['hive-mind', 'consensus', '-a', 'vote', '-p', id, '-v', isFor ? 'yes' : 'no', '--voter-id', voter],
+ isDestructive: false,
+ verify: snapshot => {
+ const proposal = snapshot.hive?.pending.find(entry => entry.id === id)
+ const decided = snapshot.hive?.history.some(entry => entry.id === id) === true
+
+ return decided || (proposal !== undefined && proposal.votesFor + proposal.votesAgainst > 0)
+ },
+ expect: 'a vote counted on the proposal in .claude-flow/hive-mind/state.json',
+ }
+}
+
+/** Asks the router again for a task's description. The text is the task's own, cleaned, one argv element. */
+export function reroute(description: string): ActionSpec | null {
+ const task = plain(description, 400)
+
+ return task === ''
+ ? null
+ : { label: 'ask the router', args: ['hooks', 'route', '--task', task, '--format', 'json'], isDestructive: false, expect: 'a pick printed by the router' }
+}
+
+export function agentLogs(agentId: string): ActionSpec | null {
+ const id = idOf(agentId)
+
+ return id === null ? null : { label: `logs of ${id}`, args: ['agent', 'logs', id], isDestructive: false, expect: 'the log lines' }
+}
+
+/** The full argv: the configured CLI's fixed prefix, then the action's own. */
+export const argvOf = (prefix: readonly string[], spec: ActionSpec): string[] => [...prefix, ...spec.args]
diff --git a/plugins/ruflo-swarm/hooks/actions/controller.ts b/plugins/ruflo-swarm/hooks/actions/controller.ts
new file mode 100644
index 0000000000..e704f6d5f4
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/actions/controller.ts
@@ -0,0 +1,290 @@
+import type { Host } from '../host'
+import { LEAD, membersOf, type Member } from '../model/members'
+import { parseRoute, plain } from '../reader/parse'
+import { CLI_PREFIXES, type State } from '../state'
+import type { PaneActions } from '../views/pane'
+import { paneModelOf } from '../views/model'
+import {
+ agentLogs,
+ argvOf,
+ claimTask,
+ handoffTask,
+ markStealable,
+ reroute,
+ setClaimStatus,
+ stealTask,
+ stopAgent,
+ vote,
+ type ActionSpec,
+} from './argv'
+
+/** A CLI call from a button gets this long; the engine's own cap is ten minutes, and the pane does not hold a person that long. */
+const RUN_MS = 60_000
+/** A confirm prompt left unanswered this long is dropped, so a stale press never runs an old action. */
+export const CONFIRM_MS = 30_000
+
+export type Controller = {
+ /** Re-reads the disk now and resolves once the snapshot is fresh. */
+ refresh: () => Promise<void>
+ persist: () => void
+}
+
+const lastLines = (text: string, count: number): string[] =>
+ text
+ .split('\n')
+ .map(line => plain(line, 400))
+ .filter(line => line !== '')
+ .slice(-count)
+
+/** Runs one action through the configured CLI and says what happened, checked against the disk where the disk can show it. */
+export async function runAction(state: State, host: Host, control: Controller, spec: ActionSpec): Promise<void> {
+ const nowMs = () => Date.now()
+
+ state.isActing = true
+ state.confirm = null
+ host.invalidate()
+
+ try {
+ const result = await host.run(argvOf(CLI_PREFIXES[state.options.cli], spec), RUN_MS)
+ const ok = result.exitCode === 0
+ let verified: 'yes' | 'no' | 'n/a' = 'n/a'
+
+ if (spec.args[0] === 'hooks' && spec.args[1] === 'route') {
+ const pick = parseRoute(result.stdout, nowMs())
+
+ if (pick !== null) {
+ state.route = pick
+ control.persist()
+ }
+
+ verified = pick !== null ? 'yes' : 'no'
+ } else if (spec.args[0] === 'agent' && spec.args[1] === 'logs') {
+ state.detail = { title: spec.label, lines: lastLines(ok ? result.stdout : result.stderr || result.stdout, 40) }
+ }
+
+ if (ok && spec.verify !== undefined) {
+ await control.refresh()
+ verified = state.snapshot !== null && spec.verify(state.snapshot) ? 'yes' : 'no'
+ }
+
+ const said = lastLines(ok ? result.stdout : result.stderr || result.stdout, 1)[0] ?? ''
+
+ state.outcome = { label: spec.label, ok, verified, detail: ok ? (verified === 'no' ? `expected ${spec.expect}` : '') : `exit ${result.exitCode}${said !== '' ? `: ${said}` : ''}`, atMs: nowMs() }
+ } catch (error) {
+ // A refused `$.process.run` (removed by an administrator, or denied above this mod) is a sentence, not a crash.
+ state.outcome = { label: spec.label, ok: false, verified: 'n/a', detail: plain(error instanceof Error ? error.message : String(error), 160), atMs: nowMs() }
+ } finally {
+ state.isActing = false
+ host.invalidate()
+ }
+}
+
+/** Asks first for a destructive action (a second press confirms), runs a safe one at once, and says so when there is nothing to act on. */
+export function request(state: State, host: Host, control: Controller, spec: ActionSpec | null, why: string): void {
+ if (state.isActing) {
+ return
+ }
+
+ if (spec === null) {
+ state.outcome = { label: why, ok: false, verified: 'n/a', detail: 'nothing to act on', atMs: Date.now() }
+ host.invalidate()
+
+ return
+ }
+
+ if (spec.isDestructive) {
+ state.confirm = { label: spec.label, spec, askedAtMs: Date.now() }
+ state.timers.get('confirm')?.cancel()
+ state.timers.set(
+ 'confirm',
+ host.after(CONFIRM_MS, () => {
+ state.timers.delete('confirm')
+ state.confirm = null
+ host.invalidate()
+ }),
+ )
+ host.invalidate()
+
+ return
+ }
+
+ void runAction(state, host, control, spec)
+}
+
+/** The activity a Claude Code loop showed this session, as lines: there is no transcript API, so this is what the hooks saw. */
+function activityLines(state: State, member: Member): string[] {
+ const recent = state.activity.recent.get(member.id) ?? []
+ const loop = state.activity.loops.get(member.id)
+
+ return [
+ ...(loop?.description !== undefined ? [`task: ${plain(loop.description, 200)}`] : []),
+ ...(recent.length === 0 ? ['no tool calls seen yet'] : recent.map(call => `${call.isError ? '✗' : '·'} ${call.tool} ${call.subject}`)),
+ ]
+}
+
+export function paneActionsOf(state: State, host: Host, control: Controller): PaneActions {
+ const model = () => paneModelOf(state, state.pane.columns, state.pane.rows, Date.now())
+ const members = () => membersOf(state.snapshot, state.activity, Date.now())
+
+ const step = (by: number) => {
+ const all = members()
+
+ if (all.length === 0) {
+ return
+ }
+
+ const at = Math.max(0, all.findIndex(member => member.id === state.selected))
+
+ state.selected = all[(at + by + all.length) % all.length]?.id ?? null
+ state.detail = null
+ control.persist()
+ host.invalidate()
+ }
+
+ const stepTask = (by: number) => {
+ const rows = model().board.rows
+
+ if (rows.length === 0) {
+ return
+ }
+
+ const at = Math.max(0, rows.findIndex(row => row.id === state.selectedTask))
+
+ state.selectedTask = rows[(at + by + rows.length) % rows.length]?.id ?? null
+ control.persist()
+ host.invalidate()
+ }
+
+ const selected = () => model().selected
+ const task = () => model().board.selected
+ const ruflo = (member: Member | null) => (member !== null && member.source === 'ruflo' ? member : null)
+ const claimOf = (member: Member | null) => (member === null ? undefined : state.snapshot?.claims.find(claim => claim.claimant.id === member.id && claim.status !== 'completed'))
+ const go = (spec: ActionSpec | null, why: string) => request(state, host, control, spec, why)
+
+ return {
+ hide: () => {
+ state.pane.isOpen = false
+ state.pane.isClosedByPerson = true
+ control.persist()
+ void host.closePane('ruflo-swarm').catch(() => undefined)
+ },
+ prev: () => step(-1),
+ next: () => step(1),
+ taskPrev: () => stepTask(-1),
+ taskNext: () => stepTask(1),
+ stop: () => {
+ const member = ruflo(selected())
+
+ go(member === null ? null : stopAgent(member.id), 'stop')
+ },
+ logs: () => {
+ const member = selected()
+
+ if (member === null) {
+ return
+ }
+
+ if (member.source === 'ruflo') {
+ go(agentLogs(member.id), 'logs')
+
+ return
+ }
+
+ state.detail = { title: `activity of ${member.label}${member.id === LEAD ? '' : ` (${member.id})`}`, lines: activityLines(state, member) }
+ host.invalidate()
+ },
+ pause: () => {
+ const claim = claimOf(ruflo(selected()))
+
+ go(claim === undefined ? null : setClaimStatus(claim.issueId, 'paused'), 'pause claim')
+ },
+ resume: () => {
+ const claim = claimOf(ruflo(selected()))
+
+ go(claim === undefined ? null : setClaimStatus(claim.issueId, 'active'), 'resume claim')
+ },
+ claim: () => {
+ const member = ruflo(selected())
+ const row = task()
+
+ go(member === null || row === null ? null : claimTask(row.id, member.id, member.role), 'claim task')
+ },
+ offer: () => {
+ const row = task()
+
+ go(row === null ? null : markStealable(row.id), 'offer task')
+ },
+ steal: () => {
+ const member = ruflo(selected())
+ const row = task()
+
+ go(member === null || row === null ? null : stealTask(row.id, member.id, member.role), 'steal task')
+ },
+ handoff: () => {
+ const member = ruflo(selected())
+ const row = task()
+ const claim = row === null ? undefined : state.snapshot?.claims.find(entry => entry.issueId === row.id)
+ const from = claim?.claimant.kind === 'agent' ? { id: claim.claimant.id, type: claim.claimant.agentType ?? 'agent' } : null
+
+ go(member === null || row === null || from === null ? null : handoffTask(row.id, from, { id: member.id, type: member.role }), 'hand off')
+ },
+ reroute: () => {
+ const row = task()
+
+ go(row === null ? null : reroute(row.description || row.type), 're-route')
+ },
+ voteYes: () => {
+ const proposal = model().proposals[0]
+ const member = selected()
+
+ go(proposal === undefined || member === null ? null : vote(proposal.id, member.id, true), 'vote')
+ },
+ voteNo: () => {
+ const proposal = model().proposals[0]
+ const member = selected()
+
+ go(proposal === undefined || member === null ? null : vote(proposal.id, member.id, false), 'vote')
+ },
+ confirm: () => {
+ const asked = state.confirm
+
+ state.timers.get('confirm')?.cancel()
+ state.timers.delete('confirm')
+
+ if (asked === null || Date.now() - asked.askedAtMs > CONFIRM_MS) {
+ state.confirm = null
+ host.invalidate()
+
+ return
+ }
+
+ void runAction(state, host, control, asked.spec)
+ },
+ cancel: () => {
+ state.timers.get('confirm')?.cancel()
+ state.timers.delete('confirm')
+ state.confirm = null
+ host.invalidate()
+ },
+ fill: () => {
+ const next = model().next
+
+ if (next === null) {
+ return
+ }
+
+ void host
+ .fillPrompt({ text: next.text })
+ .then(result => {
+ if (!result.isFilled) {
+ host.toast(`Next: ${next.text}`, 8000)
+ }
+ })
+ .catch(() => host.toast(`Next: ${next.text}`, 8000))
+ },
+ closeDetail: () => {
+ state.detail = null
+ host.invalidate()
+ },
+ }
+}
diff --git a/plugins/ruflo-swarm/hooks/audit.ts b/plugins/ruflo-swarm/hooks/audit.ts
new file mode 100644
index 0000000000..6eda800657
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/audit.ts
@@ -0,0 +1,59 @@
+import { idOf } from './reader/parse'
+import type { State } from './state'
+
+/** At most this many rows wait for a flush; past it the oldest are dropped and counted. */
+export const AUDIT_MAX = 200
+export const AUDIT_FLUSH_MS = 30_000
+export const AUDIT_NAMESPACE = 'ruflo-swarm-audit'
+
+/** Events never recorded: the render and timer traffic would drown the trail, and the trail's own writes would feed it. */
+const SKIP = /^(ui\.|clock\.|store\.|fs\.|process\.run|session\.usage|agent\.list|env\.|config\.describe)/
+
+const NAME = /^[A-Za-z0-9_.:-]{1,64}$/
+
+/**
+ * One row of the trail: the event's name, the tool's name and the agent's id where the event has them, and the time.
+ * Never prompt text, arguments, file paths, results or anything a tool returned: the trail says what happened, not what was said.
+ */
+export function auditRow(event: string, e: unknown, nowMs: number): string | null {
+ if (SKIP.test(event) || !NAME.test(event)) {
+ return null
+ }
+
+ const value = (e ?? {}) as Record<string, unknown>
+ const tool = typeof value.tool === 'string' && NAME.test(value.tool) ? value.tool : undefined
+ const agent = idOf(value.agentId)
+
+ return JSON.stringify({ t: nowMs, event, ...(tool !== undefined && { tool }), ...(agent !== null && { agent }) })
+}
+
+/** Adds a row on the hot path: a push and, when full, a shift. Nothing waits on I/O here. */
+export function noteAudit(state: State, row: string | null): void {
+ if (row === null) {
+ return
+ }
+
+ state.audit.buffer.push(row)
+
+ if (state.audit.buffer.length > AUDIT_MAX) {
+ state.audit.buffer.shift()
+ state.audit.dropped += 1
+ }
+}
+
+/** The rows to write now and the argv after the CLI prefix that stores them, or null when there is nothing to write. */
+export function takeFlush(state: State, nowMs: number): { args: string[]; rows: number } | null {
+ if (state.audit.buffer.length === 0) {
+ return null
+ }
+
+ const rows = state.audit.buffer.splice(0, state.audit.buffer.length)
+ const dropped = state.audit.dropped
+
+ state.audit.dropped = 0
+ state.audit.flushedAtMs = nowMs
+
+ const value = JSON.stringify({ rows: rows.map(row => JSON.parse(row) as unknown), ...(dropped > 0 && { dropped }) })
+
+ return { args: ['memory', 'store', '--namespace', AUDIT_NAMESPACE, '--key', `audit-${nowMs}`, '--value', value], rows: rows.length }
+}
diff --git a/plugins/ruflo-swarm/hooks/commands.ts b/plugins/ruflo-swarm/hooks/commands.ts
new file mode 100644
index 0000000000..fce0761c9d
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/commands.ts
@@ -0,0 +1,141 @@
+import type { CommandSpec } from 'claude-code'
+
+import { membersOf } from './model/members'
+import { topologyLines } from './model/topology'
+import { plain } from './reader/parse'
+import type { Snapshot } from './reader/snapshot'
+import type { State } from './state'
+import { paneModelOf } from './views/model'
+
+/**
+ * The commands this module serves. Each name is prefixed with the plugin's so it never stands in for a built-in
+ * (`/diff`, `/status`) or for the plugin's own markdown commands (`/ruflo-swarm:swarm`, `/ruflo-swarm:watch`).
+ */
+export const COMMANDS: readonly CommandSpec[] = [
+ { name: 'ruflo-swarm-pane', description: 'Show or hide the live swarm pane', argumentHint: '[open|close]', immediate: true },
+ { name: 'ruflo-swarm-status', description: 'The swarm as ruflo has it on disk: agents, tasks, claims, router and usage', argumentHint: '[json]', immediate: true },
+ { name: 'ruflo-swarm-topology', description: 'The swarm topology, its leader and members', immediate: true },
+ { name: 'ruflo-swarm-claims', description: 'Who has claimed which task, and what is stealable', immediate: true },
+ { name: 'ruflo-swarm-consensus', description: 'Hive-mind proposals, votes and recent decisions', immediate: true },
+]
+
+const NO_SWARM = 'No ruflo swarm on disk in this folder. Start one with /ruflo-swarm:swarm init.'
+
+function missingLine(snapshot: Snapshot): string {
+ return snapshot.missing.length === 0 ? '' : `\nNot on disk: ${snapshot.missing.join(', ')}.`
+}
+
+export function statusText(state: State, nowMs: number, asJson: boolean): string {
+ const snapshot = state.snapshot
+
+ if (snapshot === null) {
+ return state.readError !== null ? `The swarm files could not be read: ${plain(state.readError, 200)}` : NO_SWARM
+ }
+
+ const model = paneModelOf(state, 100, 60, nowMs)
+
+ if (asJson) {
+ return `\`\`\`json\n${JSON.stringify(
+ {
+ swarm: snapshot.swarm,
+ members: model.members.map(member => ({ id: member.id, label: member.label, source: member.source, state: member.state, word: member.word, isLeader: member.isLeader })),
+ tasks: model.board,
+ claims: snapshot.claims,
+ hive: snapshot.hive,
+ route: state.route,
+ usage: state.usage,
+ missing: snapshot.missing,
+ },
+ null,
+ 2,
+ )}\n\`\`\``
+ }
+
+ if (!snapshot.hasSwarm) {
+ return `${NO_SWARM}${missingLine(snapshot)}`
+ }
+
+ const b = model.board
+ const lines = [
+ model.title,
+ `agents: ${model.counts.map(entry => `${entry.state} ${entry.count}`).join(', ') || 'none'}`,
+ ...model.members.slice(0, 20).map(member => ` ${member.isLeader ? '★' : '·'} ${member.label} (${member.source}) ${member.word}`),
+ `tasks: ${b.pending} pending, ${b.claimed} claimed, ${b.done} done${b.failed > 0 ? `, ${b.failed} failed` : ''}`,
+ model.route,
+ model.usage,
+ ]
+
+ return `${lines.join('\n')}${missingLine(snapshot)}`
+}
+
+export function topologyText(state: State, nowMs: number): string {
+ const snapshot = state.snapshot
+
+ if (snapshot === null || !snapshot.hasSwarm) {
+ return NO_SWARM
+ }
+
+ const name = snapshot.swarm?.topology ?? snapshot.hive?.topology ?? 'unknown'
+ const members = membersOf(snapshot, state.activity, nowMs)
+ const extra = [
+ snapshot.swarm?.strategy !== undefined ? `strategy ${snapshot.swarm.strategy}` : '',
+ snapshot.swarm?.maxAgents !== undefined ? `max ${snapshot.swarm.maxAgents} agents` : '',
+ snapshot.hive?.strategy !== undefined ? `hive consensus ${snapshot.hive.strategy}` : '',
+ ].filter(part => part !== '')
+
+ return [`${name}${extra.length > 0 ? ` (${extra.join(', ')})` : ''}`, ...topologyLines(name, members, 80)].join('\n')
+}
+
+export function claimsText(state: State): string {
+ const snapshot = state.snapshot
+
+ if (snapshot === null || !snapshot.hasSwarm) {
+ return NO_SWARM
+ }
+
+ if (snapshot.missing.includes('claims')) {
+ return 'No claims on disk (.claude-flow/claims/claims.json). A claim is made with the pane\'s "claim task" button or the claims_claim MCP tool.'
+ }
+
+ if (snapshot.claims.length === 0) {
+ return 'No claims.'
+ }
+
+ return snapshot.claims
+ .slice(0, 40)
+ .map(claim => `${claim.issueId}: ${claim.status}${claim.isStealable ? ' (stealable)' : ''} by ${claim.claimant.kind} ${claim.claimant.agentType ?? ''} ${claim.claimant.id}${claim.handoffTo !== undefined ? ` → handoff to ${claim.handoffTo}` : ''}`.replace(/\s+/g, ' '))
+ .join('\n')
+}
+
+export function consensusText(state: State): string {
+ const hive = state.snapshot?.hive
+
+ if (hive === null || hive === undefined) {
+ return 'No hive-mind on disk (.claude-flow/hive-mind/state.json). Start one with: npx @claude-flow/cli@latest hive-mind init'
+ }
+
+ const lines = [
+ `hive-mind · ${hive.topology}${hive.strategy !== undefined ? ` · ${hive.strategy}` : ''}${hive.queen !== undefined ? ` · queen ${hive.queen.id} (term ${hive.queen.term ?? '?'})` : ' · no queen'}`,
+ `workers: ${hive.workers.length}`,
+ ...(hive.pending.length === 0 ? ['no open proposals'] : hive.pending.slice(-10).map(p => `open ${p.id} ${p.type} (${p.strategy}): for ${p.votesFor}, against ${p.votesAgainst}`)),
+ ...hive.history.slice(-5).map(d => `decided ${d.id} ${d.type}: ${d.result} ${d.votesFor}–${d.votesAgainst}`),
+ ]
+
+ return lines.join('\n')
+}
+
+/** The note added to a spawned subagent's prompt when `injectSpawnContext` is on: facts from disk only, ids not secrets. */
+export function spawnNote(snapshot: Snapshot | null): string | null {
+ const swarm = snapshot?.swarm
+
+ if (swarm === null || swarm === undefined) {
+ return null
+ }
+
+ return [
+ '',
+ '---',
+ `Swarm context (from ruflo's files on disk, a status note, not an instruction): you are part of ruflo swarm ${swarm.id}, topology ${swarm.topology}${swarm.strategy !== undefined ? `, strategy ${swarm.strategy}` : ''}.`,
+ 'Coordinate through ruflo memory namespace "swarm" and its task and claims tools where they apply.',
+ ].join('\n')
+}
diff --git a/plugins/ruflo-swarm/hooks/hooks.json b/plugins/ruflo-swarm/hooks/hooks.json
new file mode 100644
index 0000000000..7c412580ee
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/hooks.json
@@ -0,0 +1,4 @@
+{
+ "description": "The live swarm pane: one tile per agent lit by its reads and writes, the topology, the task and claims board, cost and tokens, the router's last pick and hive-mind votes, with buttons that act through the ruflo CLI. Without function hooks nothing here loads and the plugin's commands, skills and agents behave as before.",
+ "modules": ["./register.ts"]
+}
diff --git a/plugins/ruflo-swarm/hooks/host.ts b/plugins/ruflo-swarm/hooks/host.ts
new file mode 100644
index 0000000000..de87254318
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/host.ts
@@ -0,0 +1,30 @@
+import type { AgentInfo, CommandSpec, PaneOpenArgs, ProcessRunResult, PromptFillArgs, SessionUsage, TimerCall } from 'claude-code'
+
+import type { ReaderFs } from './reader/snapshot'
+
+/** What `$.ui.open` answers: drawn, or held back undrawn 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 from its `$`. Every later hook, timer and button press reaches the engine
+ * through this, so everything else is plain functions over a small interface a test can stand in for. Each member may
+ * be refused (an administrator removed the affordance, or a policy mod above this one said no): callers catch.
+ */
+export type Host = {
+ fs: ReaderFs
+ now: () => Promise<number>
+ after: TimerCall
+ every: TimerCall
+ storeGet: (key: string) => Promise<unknown>
+ storeSet: (key: string, value: unknown) => Promise<void>
+ invalidate: () => void
+ toast: (text: string, timeoutMs?: number) => void
+ log: (text: string) => void
+ openPane: (pane: PaneOpenArgs) => Promise<OpenResult>
+ closePane: (id: string) => Promise<void>
+ registerCommand: (spec: CommandSpec) => Promise<unknown>
+ fillPrompt: (input: PromptFillArgs) => Promise<{ isFilled: boolean }>
+ run: (argv: readonly string[], timeoutMs: number) => Promise<ProcessRunResult>
+ usage: () => Promise<SessionUsage>
+ agents: () => Promise<AgentInfo[]>
+}
diff --git a/plugins/ruflo-swarm/hooks/model/members.ts b/plugins/ruflo-swarm/hooks/model/members.ts
new file mode 100644
index 0000000000..857f8b77dd
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/model/members.ts
@@ -0,0 +1,234 @@
+import type { Snapshot } from '../reader/snapshot'
+
+/** How a tile is coloured: the five states the pane names. */
+export type MemberState = 'idle' | 'working' | 'blocked' | 'done' | 'failed'
+
+export type PulseKind = 'read' | 'write'
+
+/** One Claude Code agent loop as the engine reported it (`agent.spawn`, `$.agent.list()`), and what it has done since. */
+export type LoopRecord = {
+ id: string
+ /** The agent type it runs as, without a plugin's prefix (`ruflo-swarm:coordinator` → `coordinator`). */
+ role: string
+ name?: string
+ description?: string
+ status: string
+ calls: number
+ errors: number
+ lastTool?: string
+ lastSubject?: string
+ lastAtMs: number
+ pulse?: { kind: PulseKind; atMs: number }
+}
+
+/** What the session's loops are doing, kept by the hooks between reads of the disk. */
+export type Activity = {
+ /** Claude Code's own subagents and teammates, by agent id; `lead` is the main loop. */
+ loops: Map<string, LoopRecord>
+ turnId: string | null
+ isWorking: boolean
+ /** The last few calls of each loop, newest last, for the activity view. */
+ recent: Map<string, { tool: string; subject: string; isError: boolean; atMs: number }[]>
+}
+
+export const LEAD = 'lead'
+export const PULSE_MS = 2_000
+const RECENT = 12
+const MAX_LOOPS = 200
+
+export function newActivity(): Activity {
+ return { loops: new Map(), turnId: null, isWorking: false, recent: new Map() }
+}
+
+export type Member = {
+ id: string
+ label: string
+ role: string
+ source: 'ruflo' | 'claude' | 'lead' | 'queen'
+ state: MemberState
+ /** The word under the colour, as the source said it (`busy`, `terminated`, `running`). */
+ word: string
+ pulse?: PulseKind
+ isLeader: boolean
+ claims: number
+ calls: number
+}
+
+const WRITE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit'])
+const READ_TOOLS = new Set(['Read', 'Glob', 'Grep', 'LS', 'NotebookRead'])
+
+/** Whether a tool call reads or writes files, or neither (a pulse is for file work only). */
+export function pulseOf(tool: string, command?: string): PulseKind | null {
+ if (WRITE_TOOLS.has(tool)) {
+ return 'write'
+ }
+
+ if (READ_TOOLS.has(tool)) {
+ return 'read'
+ }
+
+ if ((tool === 'Bash' || tool === 'PowerShell') && command !== undefined) {
+ return /(?:>|\btee\b|\bsed\s+-i|\bmv\b|\bcp\b|\brm\b|\bmkdir\b|\btouch\b|\bpatch\b|\bgit\s+(?:apply|checkout|restore|commit))/.test(command) ? 'write' : 'read'
+ }
+
+ return null
+}
+
+export const roleOf = (type: string): string => (type.includes(':') ? type.slice(type.lastIndexOf(':') + 1) : type) || 'agent'
+
+function loopFor(activity: Activity, id: string, nowMs: number): LoopRecord {
+ const held = activity.loops.get(id)
+
+ if (held !== undefined) {
+ return held
+ }
+
+ if (activity.loops.size >= MAX_LOOPS) {
+ // Bounded: the loop not heard from longest makes room.
+ const oldest = [...activity.loops.values()].filter(loop => loop.id !== LEAD).sort((a, b) => a.lastAtMs - b.lastAtMs)[0]
+
+ if (oldest !== undefined) {
+ activity.loops.delete(oldest.id)
+ activity.recent.delete(oldest.id)
+ }
+ }
+
+ const loop: LoopRecord = { id, role: id === LEAD ? 'lead' : 'agent', status: 'running', calls: 0, errors: 0, lastAtMs: nowMs }
+
+ activity.loops.set(id, loop)
+
+ return loop
+}
+
+/** A subagent the engine started (`agent.spawn`'s answer), with the type and name it was asked for. */
+export function noteSpawn(activity: Activity, id: string, type: string, nowMs: number, name?: string, description?: string): void {
+ const loop = loopFor(activity, id, nowMs)
+
+ loop.role = roleOf(type)
+ loop.status = 'running'
+ loop.lastAtMs = nowMs
+
+ if (name !== undefined) {
+ loop.name = name
+ }
+
+ if (description !== undefined) {
+ loop.description = description
+ }
+}
+
+/** A tool call made by a loop (`agentId` absent: the main loop). Returns the pulse it lit, if any. */
+export function noteCall(activity: Activity, agentId: string | undefined, tool: string, subject: string, nowMs: number, command?: string): PulseKind | null {
+ const id = agentId ?? LEAD
+ const loop = loopFor(activity, id, nowMs)
+ const pulse = pulseOf(tool, command)
+
+ loop.calls += 1
+ loop.lastTool = tool
+ loop.lastSubject = subject
+ loop.lastAtMs = nowMs
+
+ if (pulse !== null) {
+ loop.pulse = { kind: pulse, atMs: nowMs }
+ }
+
+ return pulse
+}
+
+export function noteResult(activity: Activity, agentId: string | undefined, tool: string, subject: string, isError: boolean, nowMs: number): void {
+ const id = agentId ?? LEAD
+ const loop = loopFor(activity, id, nowMs)
+
+ if (isError) {
+ loop.errors += 1
+ }
+
+ activity.recent.set(id, [...(activity.recent.get(id) ?? []), { tool, subject, isError, atMs: nowMs }].slice(-RECENT))
+}
+
+/** A loop's own `turn.complete`: a subagent's answer is in. */
+export function noteDone(activity: Activity, agentId: string, reason: string, nowMs: number): void {
+ const loop = loopFor(activity, agentId, nowMs)
+
+ loop.status = reason === 'answer' ? 'completed' : reason === 'aborted' ? 'killed' : 'failed'
+ loop.lastAtMs = nowMs
+}
+
+/** `$.agent.list()` as the engine answered it: types and statuses for loops the hooks saw start before this module did. */
+export function noteListed(activity: Activity, listed: readonly { id: string; type: string; status: string; description?: string }[], nowMs: number): void {
+ for (const agent of listed.slice(0, MAX_LOOPS)) {
+ const loop = loopFor(activity, agent.id, nowMs)
+
+ loop.role = roleOf(agent.type)
+ loop.status = agent.status
+
+ if (agent.description !== undefined && loop.description === undefined) {
+ loop.description = agent.description
+ }
+ }
+}
+
+const RUFLO_STATES: Record<string, MemberState> = { idle: 'idle', busy: 'working', terminated: 'done' }
+const LOOP_STATES: Record<string, MemberState> = { running: 'working', pending: 'working', completed: 'done', failed: 'failed', killed: 'failed' }
+
+/**
+ * The tiles, in a stable order: the leader first, then ruflo's agents as the store lists them, then Claude Code's loops.
+ * A ruflo agent with a blocked claim is blocked; a loop that has not called a tool for a while is idle, not working.
+ */
+export function membersOf(snapshot: Snapshot | null, activity: Activity, nowMs: number): Member[] {
+ const claims = snapshot?.claims ?? []
+ const claimsOf = (id: string) => claims.filter(claim => claim.claimant.id === id && claim.status !== 'completed')
+ const queen = snapshot?.hive?.queen
+ const members: Member[] = []
+
+ if (queen !== undefined) {
+ members.push({ id: queen.id, label: 'queen', role: 'queen', source: 'queen', state: 'working', word: `term ${queen.term ?? '?'}`, isLeader: true, claims: 0, calls: 0 })
+ }
+
+ const coordinator = (snapshot?.agents ?? []).find(agent => /coordinator|queen/.test(agent.type) && agent.status !== 'terminated')
+
+ for (const agent of snapshot?.agents ?? []) {
+ const held = claimsOf(agent.id)
+ const isBlocked = held.some(claim => claim.status === 'blocked')
+
+ members.push({
+ id: agent.id,
+ label: agent.type,
+ role: agent.type,
+ source: 'ruflo',
+ state: isBlocked ? 'blocked' : (RUFLO_STATES[agent.status] ?? 'idle'),
+ word: isBlocked ? 'blocked' : agent.status,
+ isLeader: queen === undefined && coordinator?.id === agent.id,
+ claims: held.length,
+ calls: 0,
+ })
+ }
+
+ const loops = [...activity.loops.values()].sort((a, b) => (a.id === LEAD ? -1 : b.id === LEAD ? 1 : 0))
+
+ for (const loop of loops) {
+ const pulse = loop.pulse !== undefined && nowMs - loop.pulse.atMs < PULSE_MS ? loop.pulse.kind : undefined
+ const isLead = loop.id === LEAD
+ const isQuiet = nowMs - loop.lastAtMs > 30_000
+ const base = isLead ? (activity.isWorking ? 'working' : 'idle') : (LOOP_STATES[loop.status] ?? 'idle')
+
+ members.push({
+ id: loop.id,
+ label: isLead ? 'claude (main)' : (loop.name ?? loop.role),
+ role: loop.role,
+ source: isLead ? 'lead' : 'claude',
+ state: base === 'working' && isQuiet && !isLead ? 'idle' : base,
+ word: isLead ? (activity.isWorking ? 'turn running' : 'waiting') : loop.status,
+ ...(pulse !== undefined && { pulse }),
+ isLeader: isLead && queen === undefined && coordinator === undefined,
+ claims: 0,
+ calls: loop.calls,
+ })
+ }
+
+ return members
+}
+
+/** True while some tile is still lit: the frame timer keeps drawing until every pulse has faded. */
+export const isAnimating = (activity: Activity, nowMs: number): boolean =>
+ [...activity.loops.values()].some(loop => loop.pulse !== undefined && nowMs - loop.pulse.atMs < PULSE_MS)
diff --git a/plugins/ruflo-swarm/hooks/model/topology.ts b/plugins/ruflo-swarm/hooks/model/topology.ts
new file mode 100644
index 0000000000..9ee16b0fea
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/model/topology.ts
@@ -0,0 +1,52 @@
+import type { Member } from './members'
+
+/** At most this many members are drawn by name in the diagram; the rest are a count. */
+const NAMED = 6
+
+const clip = (text: string, width: number) => (text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…`)
+
+/**
+ * The topology as a few lines of box-drawing text, the leader starred. Drawn from the members the pane knows,
+ * with the topology ruflo wrote: a name ruflo uses that is not drawn here (`adaptive`, `hierarchical-mesh`) is said, not guessed at.
+ */
+export function topologyLines(topology: string, members: readonly Member[], width: number): string[] {
+ const leader = members.find(member => member.isLeader)
+ const others = members.filter(member => member !== leader)
+ const named = others.slice(0, NAMED).map(member => member.label)
+ const more = others.length - named.length
+ const tail = more > 0 ? [`+${more} more`] : []
+ const lead = leader !== undefined ? `★ ${leader.label}` : '★ (no leader on disk)'
+ const w = Math.max(12, width)
+
+ if (members.length === 0) {
+ return [clip(`${topology}: no members yet`, w)]
+ }
+
+ switch (topology) {
+ case 'hierarchical':
+ case 'hierarchical-mesh': {
+ const rows = [...named, ...tail]
+
+ return [
+ clip(lead, w),
+ ...rows.map((name, index) => clip(`${index === rows.length - 1 ? '└─' : '├─'} ${name}`, w)),
+ ...(topology === 'hierarchical-mesh' && rows.length > 1 ? [clip(' (workers also linked peer to peer)', w)] : []),
+ ]
+ }
+ case 'mesh': {
+ const all = members.slice(0, NAMED).map(member => (member.isLeader ? `★${member.label}` : member.label))
+ const links = (members.length * (members.length - 1)) / 2
+
+ return [clip(all.join(' ⇄ '), w), clip(`all-to-all: ${members.length} members, ${links} links${more > 0 ? `, ${more} not named` : ''}`, w)]
+ }
+ case 'ring': {
+ const all = members.slice(0, NAMED).map(member => (member.isLeader ? `★${member.label}` : member.label))
+
+ return [clip(`${all.join(' → ')}${members.length > NAMED ? ' → …' : ''} ↺`, w)]
+ }
+ case 'star':
+ return [clip(`${lead} hub`, w), clip(` spokes: ${[...named, ...tail].join(', ')}`, w)]
+ default:
+ return [clip(`${topology}: not drawn by the pane (${members.length} members)`, w), clip(lead, w)]
+ }
+}
diff --git a/plugins/ruflo-swarm/hooks/reader/parse.ts b/plugins/ruflo-swarm/hooks/reader/parse.ts
new file mode 100644
index 0000000000..e9a7150607
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/reader/parse.ts
@@ -0,0 +1,360 @@
+/**
+ * Parsers for the files ruflo writes under `.claude-flow/` and `.swarm/`, and for the JSON `hooks route` prints.
+ * Every one takes text from disk that another process wrote, so each tolerates any shape: what it cannot read
+ * is left out, never guessed. Nothing here reads, keeps or returns the hive's `hiveToken`.
+ */
+
+/** Text longer than this is not read: 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
+
+export type SwarmInfo = {
+ id: string
+ topology: string
+ status: string
+ maxAgents?: number
+ strategy?: string
+ consensus?: string
+ agentIds: string[]
+ updatedAt?: string
+}
+
+export type AgentRecord = {
+ id: string
+ type: string
+ status: string
+ health?: number
+ taskCount?: number
+ model?: string
+ createdAt?: string
+}
+
+export type TaskRecord = {
+ id: string
+ type: string
+ description: string
+ priority: string
+ status: string
+ progress?: number
+ assignedTo: string[]
+}
+
+export type ClaimRecord = {
+ issueId: string
+ status: string
+ claimant: { kind: 'agent' | 'human'; id: string; agentType?: string }
+ progress?: number
+ handoffTo?: string
+ isStealable: boolean
+}
+
+export type Proposal = { id: string; type: string; status: string; strategy: string; votesFor: number; votesAgainst: number; proposedBy: string }
+export type Decision = { id: string; type: string; result: string; votesFor: number; votesAgainst: number; decidedAt: string }
+
+export type HiveInfo = {
+ topology: string
+ strategy?: string
+ queen?: { id: string; term?: number }
+ workers: string[]
+ pending: Proposal[]
+ history: Decision[]
+}
+
+export type RoutePick = {
+ task: string
+ agent: string
+ confidence: number
+ matched: boolean
+ pattern?: string
+ alternatives: { agent: string; confidence: number }[]
+ method?: string
+ atMs: number
+}
+
+const ID = /^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/
+
+/** Plain printable text of at most `max` characters: no control 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-…`, `task-…`, `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
+}
+
+const numberOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)
+const stringOf = (value: unknown, max = 80): string | undefined => (typeof value === 'string' && value !== '' ? plain(value, max) : undefined)
+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): Record<string, unknown> | null {
+ if (text === null || text.length > MAX_TEXT) {
+ return null
+ }
+
+ try {
+ return recordOf(JSON.parse(text))
+ } catch {
+ return null
+ }
+}
+
+const valuesOf = (value: unknown): unknown[] => {
+ const record = recordOf(value)
+
+ return record === null ? [] : Object.values(record).slice(0, MAX_RECORDS)
+}
+
+/** `.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)
+ .map(recordOf)
+ .flatMap(swarm => {
+ const id = idOf(swarm?.swarmId)
+
+ if (swarm === null || id === null) {
+ return []
+ }
+
+ const config = recordOf(swarm.config)
+
+ return [
+ {
+ id,
+ topology: stringOf(swarm.topology, 40) ?? 'unknown',
+ status: stringOf(swarm.status, 40) ?? 'unknown',
+ ...(numberOf(swarm.maxAgents) !== undefined && { maxAgents: numberOf(swarm.maxAgents) }),
+ ...(stringOf(config?.strategy, 40) !== undefined && { strategy: stringOf(config?.strategy, 40) }),
+ ...(stringOf(config?.consensusMechanism, 40) !== undefined && { consensus: stringOf(config?.consensusMechanism, 40) }),
+ agentIds: (Array.isArray(swarm.agents) ? swarm.agents : []).slice(0, MAX_RECORDS).flatMap(agent => (idOf(agent) !== null ? [agent as string] : [])),
+ ...(stringOf(swarm.updatedAt, 40) !== undefined && { updatedAt: stringOf(swarm.updatedAt, 40) }),
+ } satisfies SwarmInfo,
+ ]
+ })
+
+ 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` leaves, which names the swarm and its strategy. */
+export function parseSwarmPointer(text: string | null): { id: string; topology?: string; strategy?: string; status?: string } | null {
+ const value = jsonObject(text)
+ const id = idOf(value?.id)
+
+ if (value === null || id === null) {
+ return null
+ }
+
+ return {
+ id,
+ ...(stringOf(value.topology, 40) !== undefined && { topology: stringOf(value.topology, 40) }),
+ ...(stringOf(value.strategy, 40) !== undefined && { strategy: stringOf(value.strategy, 40) }),
+ ...(stringOf(value.status, 40) !== undefined && { status: stringOf(value.status, 40) }),
+ }
+}
+
+/** `.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 []
+ }
+
+ return [
+ {
+ id,
+ type: stringOf(agent.agentType, 40) ?? 'agent',
+ status: stringOf(agent.status, 20) ?? 'unknown',
+ ...(numberOf(agent.health) !== undefined && { health: numberOf(agent.health) }),
+ ...(numberOf(agent.taskCount) !== undefined && { taskCount: numberOf(agent.taskCount) }),
+ ...(stringOf(agent.model, 40) !== undefined && { model: stringOf(agent.model, 40) }),
+ ...(stringOf(agent.createdAt, 40) !== undefined && { createdAt: stringOf(agent.createdAt, 40) }),
+ },
+ ]
+ })
+}
+
+/** `.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)
+
+ if (task === null || id === null) {
+ return []
+ }
+
+ return [
+ {
+ id,
+ type: stringOf(task.type, 40) ?? 'task',
+ description: plain(task.description, 300),
+ priority: stringOf(task.priority, 20) ?? 'normal',
+ status: stringOf(task.status, 20) ?? 'unknown',
+ ...(numberOf(task.progress) !== undefined && { progress: numberOf(task.progress) }),
+ assignedTo: (Array.isArray(task.assignedTo) ? task.assignedTo : []).slice(0, 50).flatMap(agent => (idOf(agent) !== null ? [agent as string] : [])),
+ },
+ ]
+ })
+}
+
+/** `.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 = recordOf(claim?.claimant)
+
+ if (claim === null || issueId === null || claimant === null) {
+ return []
+ }
+
+ const isAgent = claimant.type === 'agent'
+ const who = idOf(isAgent ? claimant.agentId : claimant.userId)
+
+ if (who === null) {
+ return []
+ }
+
+ const handoff = recordOf(claim.handoffTo)
+ const handoffTo = idOf(handoff?.agentId ?? handoff?.userId)
+
+ return [
+ {
+ issueId,
+ status: stringOf(claim.status, 30) ?? 'unknown',
+ claimant: { kind: isAgent ? 'agent' : 'human', id: who, ...(stringOf(claimant.agentType, 40) !== undefined && { agentType: stringOf(claimant.agentType, 40) }) },
+ ...(numberOf(claim.progress) !== undefined && { progress: numberOf(claim.progress) }),
+ ...(handoffTo !== null && { handoffTo }),
+ isStealable: claim.status === 'stealable' || Object.hasOwn(stealable, issueId),
+ },
+ ]
+ })
+}
+
+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 = recordOf(hive.queen)
+ const queenId = idOf(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',
+ proposedBy: stringOf(proposal.proposedBy, 60) ?? '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,
+ decidedAt: stringOf(decision.decidedAt, 40) ?? '',
+ },
+ ]
+ })
+
+ return {
+ topology: stringOf(hive.topology, 40) ?? 'unknown',
+ ...(stringOf(hive.consensusStrategy, 30) !== undefined && { strategy: stringOf(hive.consensusStrategy, 30) }),
+ ...(queenId !== null && { queen: { id: queenId, ...(numberOf(queen?.term) !== undefined && { term: numberOf(queen?.term) }) } }),
+ workers: (Array.isArray(hive.workers) ? hive.workers : []).slice(0, MAX_RECORDS).flatMap(worker => (idOf(worker) !== null ? [worker as string] : [])),
+ pending,
+ history,
+ }
+}
+
+/**
+ * What `hooks route --format json` printed (log lines may come first), or the `hooks_route` MCP tool answered, as one pick.
+ * The router's own `matched` flag is kept as it said it; whether the confidence clears a threshold is the view's call.
+ */
+export function parseRoute(text: string, atMs: number): RoutePick | null {
+ const start = text.indexOf('{')
+ const value = start < 0 ? null : jsonObject(text.slice(start, Math.min(text.length, start + 200_000)))
+ const primary = recordOf(value?.primaryAgent)
+ const agent = stringOf(primary?.type, 40)
+ const confidence = numberOf(primary?.confidence)
+
+ if (value === null || agent === undefined || confidence === undefined) {
+ return null
+ }
+
+ const routing = recordOf(value.routing)
+
+ return {
+ task: plain(value.task, 200),
+ agent,
+ confidence: Math.max(0, Math.min(1, confidence)),
+ matched: value.matched === true,
+ ...(stringOf(value.matchedPattern, 40) !== undefined && { pattern: stringOf(value.matchedPattern, 40) }),
+ alternatives: (Array.isArray(value.alternativeAgents) ? value.alternativeAgents : []).slice(0, 3).flatMap(entry => {
+ const alt = recordOf(entry)
+ const type = stringOf(alt?.type, 40)
+ const score = numberOf(alt?.confidence)
+
+ return type !== undefined && score !== undefined ? [{ agent: type, confidence: Math.max(0, Math.min(1, score)) }] : []
+ }),
+ ...(stringOf(routing?.method, 40) !== undefined && { method: stringOf(routing?.method, 40) }),
+ atMs,
+ }
+}
+
+/** A pick held in `$.store` read back: every field checked, as anything else from storage is. */
+export function routeFromStore(value: unknown): RoutePick | null {
+ const pick = recordOf(value)
+
+ if (pick === null || typeof pick.task !== 'string' || typeof pick.agent !== 'string' || numberOf(pick.confidence) === undefined || numberOf(pick.atMs) === undefined) {
+ return null
+ }
+
+ return parseRoute(JSON.stringify({ task: pick.task, matched: pick.matched, matchedPattern: pick.pattern, primaryAgent: { type: pick.agent, confidence: pick.confidence }, alternativeAgents: [], routing: { method: pick.method } }), numberOf(pick.atMs) ?? 0)
+}
diff --git a/plugins/ruflo-swarm/hooks/reader/snapshot.ts b/plugins/ruflo-swarm/hooks/reader/snapshot.ts
new file mode 100644
index 0000000000..c441746880
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/reader/snapshot.ts
@@ -0,0 +1,114 @@
+import {
+ parseAgents,
+ parseClaims,
+ parseHive,
+ parseSwarmPointer,
+ parseSwarmStore,
+ parseTasks,
+ type AgentRecord,
+ type ClaimRecord,
+ type HiveInfo,
+ type SwarmInfo,
+ type TaskRecord,
+} from './parse'
+
+/** The file calls a reader makes, as `$.fs` answers them; every one may be refused. */
+export type ReaderFs = {
+ read: (path: string) => Promise<string>
+ stat: (path: string) => Promise<{ mtimeMs?: number; size?: number } | undefined>
+}
+
+/** Where ruflo keeps each fact, relative to the session's working directory. */
+export const FILES = {
+ 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',
+} as const
+
+export type FileKey = keyof typeof FILES
+
+export type Snapshot = {
+ swarm: SwarmInfo | null
+ agents: AgentRecord[]
+ tasks: TaskRecord[]
+ claims: ClaimRecord[]
+ hive: HiveInfo | null
+ /** The facts that are not on disk (no file, unreadable, or not in a shape ruflo writes), by key. */
+ missing: FileKey[]
+ /** True when any of ruflo's swarm files is there at all: the pane has something of its own to show. */
+ hasSwarm: boolean
+ readAtMs: number
+}
+
+/** The text of each file as last read, by path, with the mtime it was read at: an unchanged file is not read again. */
+export type ReadCache = Map<string, { mtimeMs: number; size: number; text: string }>
+
+async function textOf(fs: ReaderFs, cache: ReadCache, path: string): Promise<string | null> {
+ try {
+ const stat = await fs.stat(path)
+ const mtimeMs = stat?.mtimeMs ?? -1
+ const size = stat?.size ?? -1
+ const held = cache.get(path)
+
+ if (held !== undefined && mtimeMs >= 0 && held.mtimeMs === mtimeMs && held.size === size) {
+ return held.text
+ }
+
+ const text = await fs.read(path)
+
+ cache.set(path, { mtimeMs, size, text })
+
+ return text
+ } catch {
+ cache.delete(path)
+
+ return null
+ }
+}
+
+/** Reads every swarm fact ruflo keeps on disk, in parallel; a refused or absent file is a missing fact, never an error. */
+export async function readSnapshot(fs: ReaderFs, cache: ReadCache, nowMs: number): Promise<Snapshot> {
+ const keys = Object.keys(FILES) as FileKey[]
+ const texts = await Promise.all(keys.map(key => textOf(fs, cache, FILES[key])))
+ const text = (key: FileKey) => texts[keys.indexOf(key)] ?? null
+
+ const pointer = parseSwarmPointer(text('pointer'))
+ const stored = parseSwarmStore(text('swarm'))
+ // The pointer names the swarm `swarm init` made last; the store has its members. Either alone still names a swarm.
+ 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 parsed = {
+ swarm,
+ agents: parseAgents(text('agents')),
+ tasks: parseTasks(text('tasks')),
+ claims: parseClaims(text('claims')),
+ hive: parseHive(text('hive')),
+ }
+
+ const missing = keys.filter(key => {
+ switch (key) {
+ case 'swarm':
+ return stored === null
+ case 'pointer':
+ return pointer === null
+ case 'hive':
+ return parsed.hive === null
+ default:
+ return text(key) === null
+ }
+ })
+
+ return {
+ ...parsed,
+ missing,
+ hasSwarm: swarm !== null || parsed.agents.length > 0 || parsed.hive !== null,
+ readAtMs: nowMs,
+ }
+}
diff --git a/plugins/ruflo-swarm/hooks/register.ts b/plugins/ruflo-swarm/hooks/register.ts
new file mode 100644
index 0000000000..6132252a2a
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/register.ts
@@ -0,0 +1,465 @@
+import type { EngineInterface, On, PluginOptions } from 'claude-code'
+
+import { paneActionsOf, type Controller } from './actions/controller'
+import { AUDIT_FLUSH_MS, auditRow, noteAudit, takeFlush } from './audit'
+import { claimsText, COMMANDS, consensusText, spawnNote, statusText, topologyText } from './commands'
+import type { Host, OpenResult } from './host'
+import { isAnimating, LEAD, newActivity, noteCall, noteDone, noteListed, noteResult, noteSpawn } from './model/members'
+import { parseRoute, plain } from './reader/parse'
+import { readSnapshot, type ReadCache } from './reader/snapshot'
+import { CLI_PREFIXES, newState, PANE_ID, persistedOf, restore, STORE_KEY, type State } from './state'
+import { paneModelOf } from './views/model'
+import { paneView } from './views/pane'
+
+const REFRESH_DEBOUNCE_MS = 400
+const TICK_MS = 2_000
+/** While idle the disk is read this often: ruflo's own CLI may change it from another terminal. */
+const IDLE_READ_MS = 10_000
+const FRAME_MS = 200
+const RUFLO_COMMAND = /(?:^|[\s/'"])(?:ruflo|claude-flow|@claude-flow\/cli)(?:@[\w.-]+)?\s/
+const ROUTE_COMMAND = /\bhooks\s+route\b/
+const ROUTE_TOOL = /(?:^|__)hooks_route$/
+
+/**
+ * Binds a Host from `$`. Declared here, each member spelled `$.noun.event(...)`, so the engine reads what the module
+ * calls off its source. The calls that answer nothing are wrapped: a refused draw or toast is not a crashed hook.
+ */
+function hostOf($: EngineInterface, cwd: string): Host {
+ const rooted = (path: string) => (path.startsWith('/') ? path : `${cwd.replace(/\/+$/, '')}/${path}`)
+ const quietly = (fn: () => void) => {
+ try {
+ fn()
+ } catch {
+ // Refused: there is nothing to do about a draw nobody may make.
+ }
+ }
+
+ return {
+ fs: { read: path => $.fs.read(rooted(path)), stat: path => $.fs.stat(rooted(path)) },
+ now: () => $.clock.now(),
+ after: (ms, fn) => $.clock.after(ms, fn),
+ every: (ms, fn) => $.clock.every(ms, fn),
+ storeGet: key => $.store.get(key),
+ storeSet: (key, value) => $.store.set(key, value),
+ invalidate: () => quietly(() => $.ui.invalidate('ui.render')),
+ toast: (text, timeoutMs) => quietly(() => $.ui.toast(text, timeoutMs !== undefined ? { timeoutMs } : undefined)),
+ log: text => quietly(() => $.ui.log(text)),
+ openPane: pane => $.ui.open(pane) as Promise<OpenResult>,
+ closePane: id => $.ui.close({ id }),
+ registerCommand: spec => $.command.register(spec),
+ fillPrompt: input => $.prompt.fill(input),
+ run: (argv, timeoutMs) => $.process.run(argv, { timeoutMs }),
+ usage: () => $.session.usage(),
+ agents: () => $.agent.list(),
+ }
+}
+
+/**
+ * The swarm mod: a live pane of the ruflo swarm on disk and of Claude Code's own agent loops, swarm commands, and,
+ * where the options ask, swarm context in spawned subagents and a content-free audit trail. `session.start` binds the
+ * engine; every hook after it works over that binding and one state object.
+ */
+export function register(on: On, raw: PluginOptions) {
+ const state: State = newState(raw, newActivity())
+ const cache: ReadCache = new Map()
+ let host: Host | null = null
+
+ const persist = () => {
+ void host?.storeSet(STORE_KEY, persistedOf(state)).catch(() => undefined)
+ }
+
+ async function refresh(): Promise<void> {
+ const bound = host
+
+ if (bound === null) {
+ return
+ }
+
+ if (state.isRefreshing) {
+ state.isRefreshQueued = true
+
+ return
+ }
+
+ state.isRefreshing = true
+
+ try {
+ const nowMs = Date.now()
+ const [snapshot, usage, listed] = await Promise.all([
+ readSnapshot(bound.fs, cache, nowMs),
+ bound.usage().catch(() => null),
+ bound.agents().catch(() => null),
+ ])
+ const isFirstSight = snapshot.hasSwarm && state.snapshot?.hasSwarm !== true
+
+ state.snapshot = snapshot
+ state.readError = null
+
+ if (usage !== null) {
+ state.usage = {
+ ...(usage.cost?.usd !== undefined && { costUsd: usage.cost.usd }),
+ ...(usage.context?.tokens !== undefined && { contextTokens: usage.context.tokens }),
+ ...(usage.context?.percent !== undefined && { contextPercent: usage.context.percent }),
+ ...(usage.context?.window !== undefined && { contextWindow: usage.context.window }),
+ readAtMs: nowMs,
+ }
+ }
+
+ if (listed !== null) {
+ noteListed(state.activity, listed, nowMs)
+ }
+
+ if (isFirstSight) {
+ maybeAutoOpen()
+ }
+ } catch (error) {
+ state.readError = plain(error instanceof Error ? error.message : String(error), 200)
+ } finally {
+ state.isRefreshing = false
+ bound.invalidate()
+
+ if (state.isRefreshQueued) {
+ state.isRefreshQueued = false
+ scheduleRefresh()
+ }
+ }
+ }
+
+ function scheduleRefresh(): void {
+ if (host === null || state.timers.has('refresh')) {
+ return
+ }
+
+ state.timers.set(
+ 'refresh',
+ host.after(REFRESH_DEBOUNCE_MS, () => {
+ state.timers.delete('refresh')
+ void refresh()
+ }),
+ )
+ }
+
+ /** Redraws while a tile is lit, then stops: no timer runs for a pane with nothing moving. */
+ function animate(): void {
+ const bound = host
+
+ if (bound === null || state.timers.has('frames') || !state.pane.isOpen) {
+ return
+ }
+
+ state.timers.set(
+ 'frames',
+ bound.every(FRAME_MS, () => {
+ bound.invalidate()
+
+ if (!state.pane.isOpen || !isAnimating(state.activity, Date.now())) {
+ state.timers.get('frames')?.cancel()
+ state.timers.delete('frames')
+ }
+ }),
+ )
+ }
+
+ async function openPane(): Promise<{ isPlaced: boolean; reason: string }> {
+ if (host === null) {
+ return { isPlaced: false, reason: 'the session has not started' }
+ }
+
+ try {
+ const result = await host.openPane({ id: PANE_ID, title: 'Swarm' })
+ const isPlaced = result === undefined || result.isPlaced !== false
+
+ state.pane.isOpen = isPlaced
+ state.pane.isClosedByPerson = false
+ persist()
+ void refresh()
+
+ return { isPlaced, reason: result?.reason ?? '' }
+ } catch (error) {
+ return { isPlaced: false, reason: plain(error instanceof Error ? error.message : String(error), 160) }
+ }
+ }
+
+ function maybeAutoOpen(viewport?: { isFullscreen?: boolean }): void {
+ state.viewport.isFullscreen = viewport?.isFullscreen ?? state.viewport.isFullscreen
+
+ const bound = host
+ const shouldOpen =
+ bound !== null &&
+ state.options.panel === 'auto' &&
+ !state.pane.isOpen &&
+ !state.pane.isClosedByPerson &&
+ !state.timers.has('auto-open') &&
+ state.snapshot?.hasSwarm === true &&
+ state.viewport.isFullscreen === true
+
+ if (shouldOpen && bound !== null) {
+ // From a timer: a render hook only draws.
+ state.timers.set(
+ 'auto-open',
+ bound.after(50, () => {
+ state.timers.delete('auto-open')
+ void openPane()
+ }),
+ )
+ }
+ }
+
+ const control: Controller = { refresh, persist }
+
+ // ------------------------------------------------------------- lifecycle
+
+ on('session.start', async ($, e, next) => {
+ host = hostOf($, e.cwd)
+ state.cwd = e.cwd
+
+ for (const timer of state.timers.values()) {
+ timer.cancel()
+ }
+
+ state.timers.clear()
+ noteSpawn(state.activity, LEAD, 'lead', Date.now())
+
+ const bound = host
+
+ await Promise.all([
+ ...COMMANDS.map(spec => bound.registerCommand(spec).catch(() => undefined)),
+ bound
+ .storeGet(STORE_KEY)
+ .then(value => restore(state, value))
+ .catch(() => undefined),
+ ])
+
+ await refresh()
+
+ let lastReadMs = Date.now()
+
+ state.timers.set(
+ 'tick',
+ bound.every(TICK_MS, () => {
+ const nowMs = Date.now()
+
+ if (state.pane.isOpen && (state.activity.isWorking || nowMs - lastReadMs >= IDLE_READ_MS)) {
+ lastReadMs = nowMs
+ scheduleRefresh()
+ }
+ }),
+ )
+
+ if (state.options.audit) {
+ state.timers.set(
+ 'audit',
+ bound.every(AUDIT_FLUSH_MS, () => {
+ const flush = takeFlush(state, Date.now())
+
+ if (flush !== null) {
+ void bound.run([...CLI_PREFIXES[state.options.cli], ...flush.args], 30_000).catch(() => undefined)
+ }
+ }),
+ )
+ }
+
+ return next(e)
+ })
+
+ on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
+ if (e.surface === 'terminal') {
+ maybeAutoOpen(e.viewport)
+ }
+
+ return next(e)
+ })
+
+ on('ui.render', { component: 'Pane' }, ($, e, next) => {
+ if (host === null || e.requestId !== PANE_ID) {
+ return next(e)
+ }
+
+ const table = $.ui.resolve(e)
+ const columns = Math.max(20, Math.floor(Number(e.props.bodyColumns) || 0) - 1)
+ const rows = Math.max(0, Math.floor(Number(e.props.scroll?.bodyRows) || 0))
+ const nowMs = Date.now()
+
+ state.pane.isOpen = true
+ state.pane.columns = columns
+ state.pane.rows = rows
+
+ if (isAnimating(state.activity, nowMs)) {
+ animate()
+ }
+
+ return paneView({ Box: table.Box, Text: table.Text, Button: table.Button }, paneModelOf(state, columns, rows, nowMs), paneActionsOf(state, host, control))
+ })
+
+ 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.isClosedByPerson = e.origin.kind === 'person' || state.pane.isClosedByPerson
+ persist()
+ }
+
+ return result
+ })
+
+ // -------------------------------------------------------------- commands
+
+ on('command.run', { command: 'ruflo-swarm-pane' }, async ($, e, next) => {
+ if (host === null) {
+ return next(e)
+ }
+
+ const arg = e.args.trim().toLowerCase()
+
+ if (arg === 'close' || (arg === '' && state.pane.isOpen)) {
+ state.pane.isOpen = false
+ state.pane.isClosedByPerson = true
+ persist()
+ await host.closePane(PANE_ID).catch(() => undefined)
+
+ return { text: 'Swarm pane hidden' }
+ }
+
+ const opened = await openPane()
+
+ return { text: opened.isPlaced ? 'Swarm pane shown' : `The swarm pane could not be shown: ${opened.reason}` }
+ })
+
+ /** The plugin's markdown `/ruflo-swarm:watch` still runs as it always has; with the mod it opens the pane as well. */
+ on('command.run', { command: 'ruflo-swarm:watch' }, async ($, e, next) => {
+ if (host !== null && state.options.panel !== 'off') {
+ await openPane()
+ }
+
+ return next(e)
+ })
+
+ on('command.run', { command: 'ruflo-swarm-status' }, async ($, e, next) => {
+ if (host === null) {
+ return next(e)
+ }
+
+ await refresh()
+
+ return { text: statusText(state, Date.now(), e.args.trim().toLowerCase() === 'json') }
+ })
+
+ on('command.run', { command: 'ruflo-swarm-topology' }, async ($, e, next) => {
+ if (host === null) {
+ return next(e)
+ }
+
+ await refresh()
+
+ return { text: topologyText(state, Date.now()) }
+ })
+
+ on('command.run', { command: 'ruflo-swarm-claims' }, async ($, e, next) => {
+ if (host === null) {
+ return next(e)
+ }
+
+ await refresh()
+
+ return { text: claimsText(state) }
+ })
+
+ on('command.run', { command: 'ruflo-swarm-consensus' }, async ($, e, next) => {
+ if (host === null) {
+ return next(e)
+ }
+
+ await refresh()
+
+ return { text: consensusText(state) }
+ })
+
+ // ----------------------------------------------------------------- turns
+
+ on('turn.start', ($, e, next) => {
+ state.activity.isWorking = true
+ state.activity.turnId = e.turnId
+ host?.invalidate()
+
+ return next(e)
+ })
+
+ on('turn.complete', ($, e, next) => {
+ if (e.agentId !== undefined) {
+ noteDone(state.activity, e.agentId, e.reason, Date.now())
+ } else {
+ state.activity.isWorking = false
+ scheduleRefresh()
+ }
+
+ host?.invalidate()
+
+ return next(e)
+ })
+
+ // ---------------------------------------------------------------- agents
+
+ /** Claude Code's own subagents join the pane as members; with the option on, each is told which swarm it is in. */
+ on('agent.spawn', async ($, e, next) => {
+ const note = state.options.injectSpawnContext ? spawnNote(state.snapshot) : null
+ const result = await next(note !== null ? { ...e, prompt: `${e.prompt}${note}` } : e)
+
+ if (result.deny === undefined && result.agentId !== undefined) {
+ noteSpawn(state.activity, result.agentId, e.subagentType, Date.now(), e.name, plain(e.description, 120))
+ host?.invalidate()
+ }
+
+ return result
+ })
+
+ // ------------------------------------------------------------ tool calls
+
+ /** Observes only: the call goes on unchanged, and what it read or wrote lights its agent's tile. */
+ on('tool.call', async ($, e, next) => {
+ const args = e as unknown as Readonly<Record<string, unknown>>
+ const command = typeof args.command === 'string' ? args.command : undefined
+ const path = typeof args.file_path === 'string' ? args.file_path : typeof args.path === 'string' ? args.path : typeof args.pattern === 'string' ? args.pattern : undefined
+ const subject = plain(command ?? path ?? '', 80)
+ const pulse = noteCall(state.activity, e.agentId, e.tool, subject, Date.now(), command)
+
+ if (pulse !== null && state.pane.isOpen) {
+ animate()
+ host?.invalidate()
+ }
+
+ const result = await next(e)
+ const isError = result.deny !== undefined || result.isError === true
+
+ noteResult(state.activity, e.agentId, e.tool, subject, isError, Date.now())
+
+ if (!isError) {
+ const text = typeof result.text === 'string' ? result.text : ''
+
+ if ((command !== undefined && ROUTE_COMMAND.test(command)) || ROUTE_TOOL.test(e.tool)) {
+ const pick = parseRoute(text, Date.now())
+
+ if (pick !== null) {
+ state.route = pick
+ persist()
+ }
+ }
+
+ if ((command !== undefined && RUFLO_COMMAND.test(command)) || e.tool.includes('claude-flow') || e.tool.includes('ruflo')) {
+ scheduleRefresh()
+ }
+ }
+
+ return result
+ })
+
+ // ----------------------------------------------------------------- audit
+
+ if (state.options.audit) {
+ on('*', ($, e, next) => {
+ noteAudit(state, auditRow(next.event, e, Date.now()))
+
+ return next(e)
+ })
+ }
+}
diff --git a/plugins/ruflo-swarm/hooks/state.ts b/plugins/ruflo-swarm/hooks/state.ts
new file mode 100644
index 0000000000..fa9719148a
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/state.ts
@@ -0,0 +1,128 @@
+import type { PluginOptions, Timer } from 'claude-code'
+
+import type { ActionSpec } from './actions/argv'
+import type { Activity } from './model/members'
+import { routeFromStore, type RoutePick } from './reader/parse'
+import type { Snapshot } from './reader/snapshot'
+
+export const PLUGIN_NAME = 'ruflo-swarm'
+export const PANE_ID = 'ruflo-swarm'
+
+/** The `$.store` key the few facts that must outlive a hot reload sit under. */
+export const STORE_KEY = 'ruflo-swarm/ui'
+
+/** How the pane reaches the ruflo CLI. Each is a fixed argv prefix; only `npx` may touch the network. */
+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 = {
+ /** `auto` opens the pane once a swarm is on disk and the layout docks panes; `command` only on request; `off` never. */
+ panel: 'auto' | 'command' | 'off'
+ cli: CliChoice
+ /** A router pick under this confidence is drawn as "below threshold", with its score. */
+ routeThreshold: number
+ /** Appends a short swarm note to the prompt of each subagent Claude Code spawns. */
+ injectSpawnContext: boolean
+ /** Records a bounded, content-free trail of engine events into ruflo memory. */
+ audit: boolean
+}
+
+const PANELS = new Set(['auto', 'command', 'off'])
+
+/** The options as the settings hold them, each one checked: a value the plugin does not know is its default. */
+export function optionsOf(raw: PluginOptions): Options {
+ const value = (raw ?? {}) as Record<string, unknown>
+ const panel = typeof value.panel === 'string' && PANELS.has(value.panel) ? (value.panel as Options['panel']) : 'auto'
+ const cli = typeof value.cli === 'string' && value.cli in CLI_PREFIXES ? (value.cli as CliChoice) : 'npx-offline'
+ const threshold = typeof value.routeThreshold === 'number' ? value.routeThreshold : Number(value.routeThreshold)
+
+ return {
+ panel,
+ cli,
+ routeThreshold: Number.isFinite(threshold) && threshold >= 0 && threshold <= 1 ? threshold : 0.5,
+ injectSpawnContext: value.injectSpawnContext === true,
+ audit: value.audit === true,
+ }
+}
+
+/** A destructive or mutating action waiting for the person's second press. */
+export type PendingConfirm = { label: string; spec: ActionSpec; askedAtMs: number }
+
+/** What an action did, as the pane says it: what ran, how it exited, and whether the disk shows the change. */
+export type ActionOutcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number }
+
+export type Usage = { costUsd?: number; contextTokens?: number; contextPercent?: number; contextWindow?: number; readAtMs: number }
+
+export type State = {
+ options: Options
+ cwd: string
+ snapshot: Snapshot | null
+ readError: string | null
+ isRefreshing: boolean
+ isRefreshQueued: boolean
+ activity: Activity
+ usage: Usage | null
+ route: RoutePick | null
+ pane: { isOpen: boolean; isClosedByPerson: boolean; columns: number; rows: number }
+ viewport: { isFullscreen?: boolean }
+ /** The tile the buttons act on, by member id: survives a re-read that reorders the tiles. */
+ selected: string | null
+ selectedTask: string | null
+ confirm: PendingConfirm | null
+ outcome: ActionOutcome | null
+ isActing: boolean
+ /** Lines an action asked to show (an agent's logs), with whose they are. */
+ detail: { title: string; lines: string[] } | null
+ timers: Map<string, Timer>
+ audit: { buffer: string[]; dropped: number; flushedAtMs: number }
+}
+
+export function newState(raw: PluginOptions, activity: Activity): State {
+ return {
+ options: optionsOf(raw),
+ cwd: '',
+ snapshot: null,
+ readError: null,
+ isRefreshing: false,
+ isRefreshQueued: false,
+ activity,
+ usage: null,
+ route: null,
+ pane: { isOpen: false, isClosedByPerson: false, columns: 0, rows: 0 },
+ viewport: {},
+ selected: null,
+ selectedTask: null,
+ confirm: null,
+ outcome: null,
+ isActing: false,
+ detail: null,
+ timers: new Map(),
+ audit: { buffer: [], dropped: 0, flushedAtMs: 0 },
+ }
+}
+
+/** The part of the state written to `$.store`, so a hot reload keeps what the person chose. */
+export type Persisted = { selected: string | null; selectedTask: string | null; isClosedByPerson: boolean; route: RoutePick | null }
+
+export function persistedOf(state: State): Persisted {
+ return { selected: state.selected, selectedTask: state.selectedTask, isClosedByPerson: state.pane.isClosedByPerson, route: state.route }
+}
+
+export function restore(state: State, value: unknown): void {
+ if (value === null || typeof value !== 'object') {
+ return
+ }
+
+ const held = value as Partial<Persisted>
+
+ state.selected = typeof held.selected === 'string' ? held.selected : null
+ state.selectedTask = typeof held.selectedTask === 'string' ? held.selectedTask : null
+ state.pane.isClosedByPerson = held.isClosedByPerson === true
+ state.route = routeFromStore(held.route)
+}
diff --git a/plugins/ruflo-swarm/hooks/views/model.ts b/plugins/ruflo-swarm/hooks/views/model.ts
new file mode 100644
index 0000000000..530c379c1f
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/views/model.ts
@@ -0,0 +1,172 @@
+import { membersOf, type Member, type MemberState } from '../model/members'
+import { topologyLines } from '../model/topology'
+import type { Decision, Proposal, TaskRecord } from '../reader/parse'
+import type { FileKey } from '../reader/snapshot'
+import type { ActionOutcome, PendingConfirm, State } from '../state'
+
+/** Below this many columns the pane draws its narrow form: a list, not a grid, and the board as counts. */
+export const NARROW = 44
+export const TILE = 18
+
+export type TaskRow = { id: string; status: string; type: string; description: string; owner: string; isSelected: boolean }
+
+/** Everything the pane draws, worked out from the state with no element in sight, so it is tested as data. */
+export type PaneModel = {
+ columns: number
+ rows: number
+ isNarrow: boolean
+ hasSwarm: boolean
+ title: string
+ members: Member[]
+ selected: Member | null
+ counts: { state: MemberState; count: number }[]
+ topology: string[]
+ board: { pending: number; claimed: number; done: number; failed: number; rows: TaskRow[]; selected: TaskRow | null; total: number }
+ proposals: Proposal[]
+ decisions: Decision[]
+ usage: string
+ route: string
+ missing: string[]
+ confirm: PendingConfirm | null
+ outcome: ActionOutcome | null
+ detail: State['detail']
+ next: { text: string; why: string } | null
+ isActing: boolean
+}
+
+const MISSING_WORDS: Record<FileKey, string> = {
+ swarm: 'swarm store',
+ pointer: 'swarm pointer',
+ agents: 'agent store',
+ tasks: 'task store',
+ claims: 'claims',
+ hive: 'hive-mind',
+}
+
+const CLAIMED = new Set(['in_progress', 'running', 'assigned'])
+const DONE = new Set(['completed', 'done'])
+const FAILED = new Set(['failed', 'cancelled'])
+
+const short = (id: string) => (id.length > 14 ? `…${id.slice(-8)}` : id)
+
+/** A cost or a token count as the engine gave it; a figure it left out is `n/a`, never zero. */
+export function usageLine(usage: State['usage']): string {
+ if (usage === null) {
+ return 'usage: not read yet'
+ }
+
+ const cost = usage.costUsd !== undefined ? `$${usage.costUsd.toFixed(usage.costUsd < 1 ? 3 : 2)}` : 'n/a'
+ const tokens = usage.contextTokens !== undefined ? `${Math.round(usage.contextTokens / 1000)}k` : 'n/a'
+ const window = usage.contextWindow !== undefined ? `/${Math.round(usage.contextWindow / 1000)}k` : ''
+ const percent = usage.contextPercent !== undefined ? ` (${Math.round(usage.contextPercent)}%)` : ''
+
+ return `cost ${cost} · context ${tokens}${window}${percent}`
+}
+
+/** The router's last pick seen this session, with its score; under the threshold it says so instead of naming a winner. */
+export function routeLine(route: State['route'], threshold: number): string {
+ if (route === null) {
+ return 'router: no pick seen this session'
+ }
+
+ const score = `${Math.round(route.confidence * 100)}%`
+ const alt = route.alternatives[0] !== undefined ? ` · alt ${route.alternatives[0].agent} ${Math.round(route.alternatives[0].confidence * 100)}%` : ''
+
+ if (!route.matched) {
+ return `router: no match (best ${route.agent} ${score})`
+ }
+
+ return route.confidence < threshold
+ ? `router: below threshold ${Math.round(threshold * 100)}% (best ${route.agent} ${score})${alt}`
+ : `router: ${route.agent} ${score}${route.pattern !== undefined ? ` (${route.pattern})` : ''}${alt}`
+}
+
+function nextOf(state: State, members: readonly Member[], board: PaneModel['board']): PaneModel['next'] {
+ const snapshot = state.snapshot
+
+ if (snapshot === null || !snapshot.hasSwarm) {
+ return { text: '/ruflo-swarm:swarm init', why: 'no swarm on disk here: start one' }
+ }
+
+ if (!members.some(member => member.source === 'ruflo')) {
+ return { text: 'npx @claude-flow/cli@latest agent spawn -t coder --name coder', why: 'the swarm has no ruflo agents yet' }
+ }
+
+ if (board.total === 0) {
+ return { text: 'npx @claude-flow/cli@latest task create --type implementation --description "…"', why: 'no tasks on the board' }
+ }
+
+ if (board.pending > 0 && board.claimed === 0) {
+ return { text: '/ruflo-swarm:swarm status', why: `${board.pending} task${board.pending === 1 ? '' : 's'} waiting and none claimed` }
+ }
+
+ return null
+}
+
+export function paneModelOf(state: State, columns: number, rows: number, nowMs: number): PaneModel {
+ const snapshot = state.snapshot
+ const members = membersOf(snapshot, state.activity, nowMs)
+ const selected = members.find(member => member.id === state.selected) ?? members[0] ?? null
+ const counts = (['working', 'blocked', 'idle', 'done', 'failed'] as const)
+ .map(memberState => ({ state: memberState, count: members.filter(member => member.state === memberState).length }))
+ .filter(entry => entry.count > 0)
+
+ const claimsByIssue = new Map((snapshot?.claims ?? []).map(claim => [claim.issueId, claim]))
+ const typeOf = new Map(members.map(member => [member.id, member.label]))
+
+ const taskRow = (task: TaskRecord): TaskRow => {
+ const claim = claimsByIssue.get(task.id)
+ const ownerId = claim?.claimant.id ?? task.assignedTo[0]
+
+ return {
+ id: task.id,
+ status: claim !== undefined && claim.status !== 'active' ? `${task.status}/${claim.status}` : task.status,
+ type: task.type,
+ description: task.description,
+ owner: ownerId === undefined ? 'unassigned' : (typeOf.get(ownerId) ?? short(ownerId)),
+ isSelected: task.id === state.selectedTask,
+ }
+ }
+
+ const tasks = snapshot?.tasks ?? []
+ // Open work first, newest store order kept within each group.
+ const rank = (task: TaskRecord) => (CLAIMED.has(task.status) ? 0 : task.status === 'pending' ? 1 : FAILED.has(task.status) ? 2 : 3)
+ const ordered = [...tasks].sort((a, b) => rank(a) - rank(b)).map(taskRow)
+ const selectedTask = ordered.find(row => row.id === state.selectedTask) ?? ordered[0] ?? null
+
+ const board = {
+ pending: tasks.filter(task => task.status === 'pending').length,
+ claimed: tasks.filter(task => CLAIMED.has(task.status) || claimsByIssue.get(task.id)?.status === 'active').length,
+ done: tasks.filter(task => DONE.has(task.status)).length,
+ failed: tasks.filter(task => FAILED.has(task.status)).length,
+ rows: ordered.map(row => ({ ...row, isSelected: row.id === selectedTask?.id })),
+ selected: selectedTask,
+ total: tasks.length,
+ }
+
+ const swarm = snapshot?.swarm
+ const topologyName = swarm?.topology ?? snapshot?.hive?.topology ?? 'unknown'
+
+ return {
+ columns,
+ rows,
+ isNarrow: columns < NARROW,
+ hasSwarm: snapshot?.hasSwarm === true,
+ title: swarm !== undefined && swarm !== null ? `swarm ${short(swarm.id)} · ${topologyName} · ${swarm.status}` : snapshot?.hive !== null && snapshot?.hive !== undefined ? `hive-mind · ${topologyName}` : 'ruflo swarm',
+ members,
+ selected,
+ counts,
+ topology: topologyLines(topologyName, members, columns),
+ board,
+ proposals: snapshot?.hive?.pending.filter(proposal => proposal.status === 'pending') ?? [],
+ decisions: (snapshot?.hive?.history ?? []).slice(-2).reverse(),
+ usage: usageLine(state.usage),
+ route: routeLine(state.route, state.options.routeThreshold),
+ missing: (snapshot?.missing ?? []).map(key => MISSING_WORDS[key]),
+ confirm: state.confirm,
+ outcome: state.outcome,
+ detail: state.detail,
+ next: nextOf(state, members, board),
+ isActing: state.isActing,
+ }
+}
diff --git a/plugins/ruflo-swarm/hooks/views/palette.ts b/plugins/ruflo-swarm/hooks/views/palette.ts
new file mode 100644
index 0000000000..33583b6f6d
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/views/palette.ts
@@ -0,0 +1,25 @@
+import type { MemberState, PulseKind } from '../model/members'
+
+/**
+ * Colours by the names of Claude Code's own theme, so they follow a dark or a light theme. ANSI names (`cyan`, `yellow`)
+ * are whatever the terminal makes of them and fade on a white background.
+ */
+export const HEAD = 'suggestion'
+export const GOOD = 'success'
+export const BAD = 'error'
+export const WARN = 'warning'
+export const ACCENT = 'claude'
+
+/** A tile's colour by state; idle is drawn dim instead. Every state also has its word, so colour is never the only cue. */
+export const STATE_COLORS: Record<MemberState, string | undefined> = {
+ idle: undefined,
+ working: ACCENT,
+ blocked: WARN,
+ done: GOOD,
+ failed: BAD,
+}
+
+export const STATE_GLYPHS: Record<MemberState, string> = { idle: '○', working: '●', blocked: '◆', done: '✓', failed: '✗' }
+
+/** A lit tile: blue while its agent reads files, yellow while it writes, drawn inverse so it stands out of its state colour. */
+export const PULSE_COLORS: Record<PulseKind, string> = { read: HEAD, write: WARN }
diff --git a/plugins/ruflo-swarm/hooks/views/pane.tsx b/plugins/ruflo-swarm/hooks/views/pane.tsx
new file mode 100644
index 0000000000..7aa1fbbd1e
--- /dev/null
+++ b/plugins/ruflo-swarm/hooks/views/pane.tsx
@@ -0,0 +1,400 @@
+/* @jsxRuntime classic */
+/* @jsx h */
+/* @jsxFrag Fragment */
+import type { Elements, RenderChildren, RenderElement } from 'claude-code'
+
+import type { Member } from '../model/members'
+import { ACCENT, BAD, GOOD, HEAD, PULSE_COLORS, STATE_COLORS, STATE_GLYPHS, WARN } from './palette'
+import { TILE, type PaneModel } from './model'
+
+export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
+
+/** What the buttons do. Each is a closure over the host: the view calls nothing on the engine itself. */
+export type PaneActions = {
+ hide: () => void
+ prev: () => void
+ next: () => void
+ taskPrev: () => void
+ taskNext: () => void
+ stop: () => void
+ logs: () => void
+ pause: () => void
+ resume: () => void
+ claim: () => void
+ offer: () => void
+ steal: () => void
+ handoff: () => void
+ reroute: () => void
+ voteYes: () => void
+ voteNo: () => void
+ confirm: () => void
+ cancel: () => void
+ fill: () => void
+ closeDetail: () => void
+}
+
+type Section = { rows: number; node: RenderChildren }
+
+export const clip = (text: string, width: number): string => (text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}…`)
+const pad = (text: string, width: number): string => (text.length >= width ? text.slice(0, Math.max(0, width)) : text + ' '.repeat(width - text.length))
+
+function rule(kit: Kit, title: string, width: number, right = ''): RenderChildren {
+ const { Box, Text } = kit
+ const fill = Math.max(1, width - title.length - right.length - 2)
+
+ return (
+ <Box>
+ <Text bold color={HEAD}>{title}</Text>
+ <Text dimColor>{` ${'─'.repeat(fill)} `}</Text>
+ <Text>{right}</Text>
+ </Box>
+ )
+}
+
+function tile(kit: Kit, member: Member, width: number, isSelected: boolean): RenderChildren {
+ const { Text } = kit
+ const glyph = member.isLeader ? '★' : STATE_GLYPHS[member.state]
+ const text = pad(`${isSelected ? '▸' : ' '}${glyph} ${clip(member.label, width - 4)}`, width)
+
+ if (member.pulse !== undefined) {
+ return <Text inverse bold color={PULSE_COLORS[member.pulse]}>{text}</Text>
+ }
+
+ const color = STATE_COLORS[member.state]
+
+ return color === undefined ? <Text dimColor={!isSelected} bold={isSelected}>{text}</Text> : <Text color={color} bold={isSelected}>{text}</Text>
+}
+
+/** The agents as a grid of tiles, wrapped to the width; past `maxRows` the rest are a count. */
+function tiles(kit: Kit, model: PaneModel, maxRows: number): Section {
+ const { Box, Text } = kit
+ const perRow = Math.max(1, Math.floor(model.columns / (TILE + 1)))
+ const fit = Math.max(1, maxRows) * perRow
+ const shown = model.members.length > fit ? model.members.slice(0, fit - 1) : model.members
+ const hidden = model.members.length - shown.length
+ const rows: Member[][] = []
+
+ for (let i = 0; i < shown.length; i += perRow) {
+ rows.push(shown.slice(i, i + perRow))
+ }
+
+ return {
+ rows: rows.length + (hidden > 0 ? 1 : 0),
+ node: (
+ <Box flexDirection="column">
+ {rows.map(row => (
+ <Box columnGap={1}>{row.map(member => tile(kit, member, TILE, member.id === model.selected?.id))}</Box>
+ ))}
+ {hidden > 0 ? <Text dimColor>{`+${hidden} more agents (select with ◀ ▶)`}</Text> : null}
+ </Box>
+ ),
+ }
+}
+
+function legend(kit: Kit, model: PaneModel): RenderChildren {
+ const { Box, Text } = kit
+
+ return (
+ <Box flexWrap="wrap">
+ {model.counts.map(entry => (
+ <Text>
+ <Text color={STATE_COLORS[entry.state]} dimColor={STATE_COLORS[entry.state] === undefined}>{STATE_GLYPHS[entry.state]}</Text>
+ <Text dimColor>{` ${entry.state} ${entry.count} `}</Text>
+ </Text>
+ ))}
+ <Text color={PULSE_COLORS.read} inverse>{' read '}</Text>
+ <Text> </Text>
+ <Text color={PULSE_COLORS.write} inverse>{' write '}</Text>
+ </Box>
+ )
+}
+
+/** The selected agent, what it is, and the buttons that act on it: only the ones its kind can take. */
+function selection(kit: Kit, model: PaneModel, actions: PaneActions): Section {
+ const { Box, Text, Button } = kit
+ const member = model.selected
+
+ if (member === null) {
+ return { rows: 1, node: <Text dimColor>No agents yet.</Text> }
+ }
+
+ const isRuflo = member.source === 'ruflo'
+ const task = model.board.selected
+ const who = `${member.label} · ${member.word}${member.claims > 0 ? ` · ${member.claims} claim${member.claims === 1 ? '' : 's'}` : ''}${member.calls > 0 ? ` · ${member.calls} calls` : ''}`
+
+ return {
+ rows: 2,
+ node: (
+ <Box flexDirection="column">
+ <Box>
+ <Button key="prev" dimColor onPress={actions.prev}>◀</Button>
+ <Text bold>{` ${clip(who, Math.max(8, model.columns - 8))} `}</Text>
+ <Button key="next" dimColor onPress={actions.next}>▶</Button>
+ </Box>
+ <Box flexWrap="wrap" columnGap={1}>
+ {isRuflo ? <Button key="logs" onPress={actions.logs}>logs</Button> : <Button key="logs" onPress={actions.logs}>activity</Button>}
+ {isRuflo && task !== null ? <Button key="claim" onPress={actions.claim}>claim task</Button> : null}
+ {isRuflo && task !== null ? <Button key="steal" onPress={actions.steal}>steal task</Button> : null}
+ {isRuflo && task !== null ? <Button key="handoff" onPress={actions.handoff}>hand off here</Button> : null}
+ {isRuflo && member.claims > 0 ? <Button key="pause" onPress={actions.pause}>pause claim</Button> : null}
+ {isRuflo && member.claims > 0 ? <Button key="resume" onPress={actions.resume}>resume claim</Button> : null}
+ {isRuflo && member.state !== 'done' ? <Button key="stop" onPress={actions.stop}>stop…</Button> : null}
+ </Box>
+ </Box>
+ ),
+ }
+}
+
+function prompts(kit: Kit, model: PaneModel, actions: PaneActions): Section | null {
+ const { Box, Text, Button } = kit
+
+ if (model.confirm !== null) {
+ return {
+ rows: 1,
+ node: (
+ <Box columnGap={1}>
+ <Text color={WARN} bold>{clip(`${model.confirm.label}?`, Math.max(8, model.columns - 22))}</Text>
+ <Button key="confirm" onPress={actions.confirm}>confirm</Button>
+ <Button key="cancel" dimColor onPress={actions.cancel}>cancel</Button>
+ </Box>
+ ),
+ }
+ }
+
+ if (model.isActing) {
+ return { rows: 1, node: <Text color={ACCENT}>running…</Text> }
+ }
+
+ const outcome = model.outcome
+
+ if (outcome === null) {
+ return null
+ }
+
+ const mark = !outcome.ok ? '✗' : outcome.verified === 'no' ? '?' : '✓'
+ const color = !outcome.ok ? BAD : outcome.verified === 'no' ? WARN : GOOD
+ const said = outcome.verified === 'yes' ? 'seen on disk' : outcome.verified === 'no' ? 'exited 0 but the disk does not show it' : outcome.ok ? 'done' : 'failed'
+
+ return { rows: 1, node: <Text color={color}>{clip(`${mark} ${outcome.label}: ${said}${outcome.detail !== '' ? ` · ${outcome.detail}` : ''}`, model.columns)}</Text> }
+}
+
+function board(kit: Kit, model: PaneModel, maxRows: number, actions: PaneActions): Section {
+ const { Box, Text, Button } = kit
+ const b = model.board
+ const right = `pending ${b.pending} · claimed ${b.claimed} · done ${b.done}${b.failed > 0 ? ` · failed ${b.failed}` : ''}`
+
+ if (b.total === 0) {
+ return { rows: 2, node: <Box flexDirection="column">{rule(kit, 'Tasks', model.columns, right)}<Text dimColor>No tasks on disk.</Text></Box> }
+ }
+
+ const start = Math.max(0, Math.min(b.rows.findIndex(row => row.isSelected) - 1, b.rows.length - maxRows))
+ const shown = b.rows.slice(start, start + Math.max(1, maxRows))
+
+ return {
+ rows: 2 + shown.length,
+ node: (
+ <Box flexDirection="column">
+ {rule(kit, 'Tasks', model.columns, right)}
+ {shown.map(row => (
+ <Text bold={row.isSelected} dimColor={!row.isSelected && row.status === 'completed'}>
+ {clip(`${row.isSelected ? '▸' : ' '} ${pad(row.status, 12)} ${row.description || row.type} → ${row.owner}`, model.columns)}
+ </Text>
+ ))}
+ <Box columnGap={1}>
+ <Button key="task-prev" dimColor onPress={actions.taskPrev}>◀ task</Button>
+ <Button key="task-next" dimColor onPress={actions.taskNext}>task ▶</Button>
+ <Button key="offer" onPress={actions.offer}>offer for stealing</Button>
+ <Button key="reroute" onPress={actions.reroute}>re-route</Button>
+ </Box>
+ </Box>
+ ),
+ }
+}
+
+function consensus(kit: Kit, model: PaneModel, actions: PaneActions): Section | null {
+ const { Box, Text, Button } = kit
+
+ if (model.proposals.length === 0 && model.decisions.length === 0) {
+ return null
+ }
+
+ const first = model.proposals[0]
+
+ return {
+ rows: 1 + Math.min(2, model.proposals.length) + model.decisions.length + (first !== undefined ? 1 : 0),
+ node: (
+ <Box flexDirection="column">
+ {rule(kit, 'Consensus', model.columns, `${model.proposals.length} open`)}
+ {model.proposals.slice(0, 2).map(proposal => (
+ <Text>{clip(` ${proposal.type} (${proposal.strategy}) for ${proposal.votesFor} · against ${proposal.votesAgainst}`, model.columns)}</Text>
+ ))}
+ {model.decisions.map(decision => (
+ <Text dimColor>{clip(` ${decision.result === 'approved' ? '✓' : '✗'} ${decision.type} ${decision.result} ${decision.votesFor}–${decision.votesAgainst}`, model.columns)}</Text>
+ ))}
+ {first !== undefined ? (
+ <Box columnGap={1}>
+ <Button key="vote-yes" onPress={actions.voteYes}>vote yes</Button>
+ <Button key="vote-no" onPress={actions.voteNo}>vote no</Button>
+ <Text dimColor>{clip(`as ${model.selected?.label ?? '—'}`, 24)}</Text>
+ </Box>
+ ) : null}
+ </Box>
+ ),
+ }
+}
+
+function detail(kit: Kit, model: PaneModel, actions: PaneActions, maxRows: number): Section | null {
+ const { Box, Text, Button } = kit
+
+ if (model.detail === null) {
+ return null
+ }
+
+ const lines = model.detail.lines.slice(-Math.max(1, maxRows))
+
+ return {
+ rows: 1 + lines.length,
+ node: (
+ <Box flexDirection="column">
+ <Box justifyContent="space-between">
+ <Text bold color={HEAD}>{clip(model.detail.title, model.columns - 8)}</Text>
+ <Button key="close-detail" dimColor onPress={actions.closeDetail}>close</Button>
+ </Box>
+ {lines.map(line => <Text dimColor wrap="truncate-end">{clip(line, model.columns)}</Text>)}
+ </Box>
+ ),
+ }
+}
+
+function header(kit: Kit, model: PaneModel, actions: PaneActions): RenderChildren {
+ const { Box, Text, Button } = kit
+
+ return (
+ <Box justifyContent="space-between">
+ <Text bold wrap="truncate-end">{clip(model.title, Math.max(8, model.columns - 7))}</Text>
+ <Button key="hide" dimColor onPress={actions.hide}>hide</Button>
+ </Box>
+ )
+}
+
+function nextRow(kit: Kit, model: PaneModel, actions: PaneActions): Section | null {
+ const { Box, Text, Button } = kit
+
+ if (model.next === null) {
+ return null
+ }
+
+ return {
+ rows: 2,
+ node: (
+ <Box flexDirection="column">
+ <Text>
+ <Text color={ACCENT} bold>Next </Text>
+ <Text>{clip(model.next.text, Math.max(8, model.columns - 5))}</Text>
+ </Text>
+ <Box columnGap={1}>
+ <Text dimColor>{clip(model.next.why, Math.max(8, model.columns - 16))}</Text>
+ <Button key="fill" onPress={actions.fill}>put in prompt</Button>
+ </Box>
+ </Box>
+ ),
+ }
+}
+
+/** The empty pane: no swarm on disk. Says so, and names the one command that starts one. */
+function empty(kit: Kit, model: PaneModel, actions: PaneActions): RenderElement {
+ const { Box, Text } = kit
+ const next = nextRow(kit, model, actions)
+
+ return (
+ <Box flexDirection="column" rowGap={1}>
+ {header(kit, model, actions)}
+ <Text>No ruflo swarm on disk in this folder.</Text>
+ {next?.node ?? null}
+ <Text dimColor>{clip(`${model.usage}`, model.columns)}</Text>
+ </Box>
+ )
+}
+
+/** The narrow form: one line per agent and the board as counts, for a pane under 44 columns. */
+function narrow(kit: Kit, model: PaneModel, actions: PaneActions): RenderElement {
+ const { Box, Text, Button } = kit
+ const budget = Math.max(1, model.rows - 7)
+ const shown = model.members.slice(0, budget)
+ const b = model.board
+
+ return (
+ <Box flexDirection="column">
+ {header(kit, model, actions)}
+ {shown.map(member => {
+ const color = member.pulse !== undefined ? PULSE_COLORS[member.pulse] : STATE_COLORS[member.state]
+
+ return (
+ <Text color={color} dimColor={color === undefined} inverse={member.pulse !== undefined} bold={member.id === model.selected?.id}>
+ {clip(`${member.id === model.selected?.id ? '▸' : ' '}${member.isLeader ? '★' : STATE_GLYPHS[member.state]} ${member.label} ${member.state}`, model.columns)}
+ </Text>
+ )
+ })}
+ {model.members.length > shown.length ? <Text dimColor>{`+${model.members.length - shown.length} more`}</Text> : null}
+ <Text>{clip(`tasks ${b.pending} pending · ${b.claimed} claimed · ${b.done} done`, model.columns)}</Text>
+ <Text dimColor>{clip(model.route, model.columns)}</Text>
+ <Text dimColor>{clip(model.usage, model.columns)}</Text>
+ <Box columnGap={1}>
+ <Button key="prev" dimColor onPress={actions.prev}>◀</Button>
+ <Button key="next" dimColor onPress={actions.next}>▶</Button>
+ <Button key="logs" onPress={actions.logs}>{model.selected?.source === 'ruflo' ? 'logs' : 'activity'}</Button>
+ </Box>
+ {prompts(kit, model, actions)?.node ?? null}
+ </Box>
+ )
+}
+
+/**
+ * The swarm pane. Sections are kept in the order that matters most and dropped from the bottom when the body is short:
+ * the tiles, what is selected and any confirm prompt always; then the board, consensus, topology, the router and usage.
+ */
+export function paneView(kit: Kit, model: PaneModel, actions: PaneActions): RenderElement {
+ const { Box, Text } = kit
+
+ if (!model.hasSwarm && model.members.length <= 1) {
+ return empty(kit, model, actions)
+ }
+
+ if (model.isNarrow) {
+ return narrow(kit, model, actions)
+ }
+
+ let budget = Math.max(6, model.rows) - 1
+ const take = (section: Section | null): RenderChildren => {
+ if (section === null || section.rows > budget) {
+ return null
+ }
+
+ budget -= section.rows
+
+ return section.node
+ }
+
+ const top = [take(tiles(kit, model, Math.max(1, Math.min(6, Math.floor(model.rows / 4))))), take({ rows: 1, node: legend(kit, model) }), take(selection(kit, model, actions)), take(prompts(kit, model, actions))]
+ const shownDetail = take(detail(kit, model, actions, Math.min(12, Math.max(2, budget - 8))))
+ const shownBoard = take(board(kit, model, Math.min(8, Math.max(1, budget - 10)), actions))
+ const shownConsensus = take(consensus(kit, model, actions))
+ const shownTopology = take({ rows: 1 + model.topology.length, node: <Box flexDirection="column">{rule(kit, 'Topology', model.columns)}{model.topology.map(line => <Text>{line}</Text>)}</Box> })
+ const shownSignals = take({ rows: 2, node: <Box flexDirection="column"><Text>{clip(model.route, model.columns)}</Text><Text dimColor>{clip(model.usage, model.columns)}</Text></Box> })
+ const shownNext = take(nextRow(kit, model, actions))
+ const shownMissing = model.missing.length > 0 ? take({ rows: 1, node: <Text dimColor>{clip(`not on disk: ${model.missing.join(', ')}`, model.columns)}</Text> }) : null
+
+ return (
+ <Box flexDirection="column">
+ {header(kit, model, actions)}
+ {top}
+ {shownDetail}
+ {shownBoard}
+ {shownConsensus}
+ {shownTopology}
+ {shownSignals}
+ {shownNext}
+ {shownMissing}
+ </Box>
+ )
+}
diff --git a/plugins/ruflo-swarm/scripts/fetch-mod-types.sh b/plugins/ruflo-swarm/scripts/fetch-mod-types.sh
new file mode 100755
index 0000000000..e2ac4ed842
--- /dev/null
+++ b/plugins/ruflo-swarm/scripts/fetch-mod-types.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Writes the engine's function-hooks declarations into .claude/types/, where
+# tsconfig.json reads them. They are what `/plugin-types` writes; this fetches
+# the copy Anthropic publishes beside its own mods (anthropics/claude-code,
+# mods/types/claude-code.d.ts). The folder is gitignored: regenerate, never edit.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+mkdir -p "$ROOT/.claude/types"
+curl -fsSL https://raw.githubusercontent.com/anthropics/claude-code/main/mods/types/claude-code.d.ts \
+ -o "$ROOT/.claude/types/claude-code.d.ts"
+head -1 "$ROOT/.claude/types/claude-code.d.ts"
diff --git a/plugins/ruflo-swarm/scripts/smoke.sh b/plugins/ruflo-swarm/scripts/smoke.sh
index 6868151b33..ede921a270 100755
--- a/plugins/ruflo-swarm/scripts/smoke.sh
+++ b/plugins/ruflo-swarm/scripts/smoke.sh
@@ -7,9 +7,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares 0.2.1 with new keywords"
+step "1. plugin.json declares 0.3.0 with new keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.2.1" ]]; then bad "expected 0.2.1, got '$v'"; else
+if [[ "$v" != "0.3.0" ]]; then bad "expected 0.3.0, got '$v'"; else
miss=""
for k in mcp topologies worktree-isolation monitor-stream; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
diff --git a/plugins/ruflo-swarm/tsconfig.json b/plugins/ruflo-swarm/tsconfig.json
new file mode 100644
index 0000000000..662d1a7bcd
--- /dev/null
+++ b/plugins/ruflo-swarm/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "compilerOptions": {
+ "target": "es2023", "lib": ["es2023"], "types": [],
+ "module": "esnext", "moduleResolution": "bundler",
+ "strict": true, "noUncheckedIndexedAccess": true,
+ "noEmit": true, "skipLibCheck": true,
+ "jsx": "react", "jsxFactory": "h", "jsxFragmentFactory": "Fragment"
+ },
+ "include": [".claude/types", "hooks", "tests"],
+ "exclude": ["tests/**/*.spec.ts"]
+}