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-console): Hive-Mind view — honeycomb, quorum, proposals, vote/propose/broadcast/spawn

ruvaef399f62366
diff --git a/plugins/ruflo-console/hooks/commands.ts b/plugins/ruflo-console/hooks/commands.ts
index 0485cae74a..f8476af424 100644
--- a/plugins/ruflo-console/hooks/commands.ts
+++ b/plugins/ruflo-console/hooks/commands.ts
@@ -88,7 +88,7 @@ export const HELP = [
'',
'Open and switch',
` /ruflo open the cockpit (also opens by itself where it can dock, panel=auto)`,
- ` /ruflo <view> ${VIEWS.map(view => `${view.id} (${view.key})`).join(', ')}`,
+ ` /ruflo <view> ${VIEWS.map(view => (view.key === '' ? view.id : `${view.id} (${view.key})`)).join(', ')}`,
' /ruflo agent <id|name> drill into one agent: role, task, claims, activity, logs, timeline',
' /ruflo back | close | status',
' /ruflo dump <view> a view as plain text, without the pane (for claude -p and scripts)',
diff --git a/plugins/ruflo-console/hooks/data/events.ts b/plugins/ruflo-console/hooks/data/events.ts
index 145b4841ac..70e1de336f 100644
--- a/plugins/ruflo-console/hooks/data/events.ts
+++ b/plugins/ruflo-console/hooks/data/events.ts
@@ -80,6 +80,23 @@ export function diffEvents(prev: Snapshot | null, next: Snapshot, atMs: number):
if (!decided.has(decision.id)) out.push(ev(atMs, 'swarm', `proposal ${decision.type} decided: ${decision.result} (${decision.votesFor}/${decision.votesAgainst})`, next.hive?.queen))
}
+ // Each ballot new since the last read, tagged with its voter: the hive's honeycomb pulses that worker's cell.
+ const ballotsBefore = new Map(prev.hive?.pending.map(entry => [entry.id, new Set(entry.ballots.map(ballot => ballot.voter))]) ?? [])
+
+ for (const proposal of next.hive?.pending ?? []) {
+ const seen = ballotsBefore.get(proposal.id) ?? new Set<string>()
+
+ for (const ballot of proposal.ballots) {
+ if (!seen.has(ballot.voter)) out.push(ev(atMs, 'swarm', `${ballot.voter} voted ${ballot.isFor ? 'for' : 'against'} ${proposal.type} (${proposal.id})`, ballot.voter))
+ }
+ }
+
+ const workersBefore = new Set(prev.hive?.workers ?? [])
+ const workersAfter = new Set(next.hive?.workers ?? [])
+
+ for (const worker of workersAfter) if (!workersBefore.has(worker)) out.push(ev(atMs, 'swarm', `${worker} joined the hive`, worker))
+ for (const worker of workersBefore) if (!workersAfter.has(worker)) out.push(ev(atMs, 'swarm', `${worker} left the hive`, worker))
+
const patterns = (next.neural?.patterns ?? 0) - (prev.neural?.patterns ?? 0)
if (prev.neural !== null && next.neural !== null && patterns > 0) out.push(ev(atMs, 'learning', `+${patterns} pattern${patterns === 1 ? '' : 's'} learned`))
diff --git a/plugins/ruflo-console/hooks/data/files.ts b/plugins/ruflo-console/hooks/data/files.ts
index 0e9a2cc5b4..39e3b4fc9d 100644
--- a/plugins/ruflo-console/hooks/data/files.ts
+++ b/plugins/ruflo-console/hooks/data/files.ts
@@ -21,6 +21,7 @@ export const PROJECT = {
swarm: '.claude-flow/swarm/swarm-state.json',
pointer: '.swarm/state.json',
agents: '.claude-flow/agents/store.json',
+ hiveAgents: '.claude-flow/agents.json',
tasks: '.claude-flow/tasks/store.json',
claims: '.claude-flow/claims/claims.json',
hive: '.claude-flow/hive-mind/state.json',
diff --git a/plugins/ruflo-console/hooks/data/hive.ts b/plugins/ruflo-console/hooks/data/hive.ts
new file mode 100644
index 0000000000..d97642a02e
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/hive.ts
@@ -0,0 +1,119 @@
+/**
+ * The hive-mind as the console reads it: the queen, its workers with their role and liveness, and what each open
+ * proposal needs to pass. The quorum arithmetic is the CLI's own (`calculateRequiredVotes` and `tryResolveProposal` in
+ * v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts), so the bar the view draws is the bar the CLI decides by. A
+ * figure the source has no formula for (gossip and crdt fault tolerance) is n/a, never estimated.
+ */
+import type { AgentRecord, HiveAgentRecord, HiveInfo, Proposal } from './parse'
+
+/** The roles `hive-mind spawn --role` accepts. */
+export const HIVE_ROLES = ['worker', 'specialist', 'scout'] as const
+
+/** How long a worker's cell pulses after the console sees its vote, join or leave. */
+export const HIVE_PULSE_MS = 2_000
+
+/** Votes a proposal needs, exactly as the CLI counts them: `totalNodes` is the hive's workers, at least one. */
+export function requiredVotes(strategy: string, totalNodes: number, quorumPreset = 'majority'): number {
+ if (totalNodes <= 0) return 1
+
+ const majority = Math.floor(totalNodes / 2) + 1
+ const twoThirds = Math.floor((totalNodes * 2) / 3) + 1
+
+ if (strategy === 'bft') return twoThirds
+ if (strategy === 'quorum') return quorumPreset === 'unanimous' ? totalNodes : quorumPreset === 'supermajority' ? twoThirds : majority
+
+ return majority
+}
+
+/** The CLI counts a hive with no workers as one node. */
+export const nodesOf = (hive: HiveInfo): number => Math.max(1, hive.workers.length)
+
+/**
+ * The proposal strategy (`bft`, `raft`, `quorum`) a hive's consensus strategy maps to; null where the tool has none
+ * (gossip, crdt), so a proposal falls back to the tool's default, raft.
+ */
+export function proposalStrategyOf(consensus: string | undefined): 'bft' | 'raft' | 'quorum' | null {
+ if (consensus === 'byzantine' || consensus === 'bft') return 'bft'
+ if (consensus === 'raft' || consensus === 'quorum') return consensus
+
+ return null
+}
+
+/** Faulty workers the strategy survives: byzantine f < n/3, raft f < n/2. Null where the source states no bound. */
+export function faultTolerance(consensus: string | undefined, workers: number): { faulty: number; of: number; rule: string } | null {
+ if (workers <= 0) return null
+
+ const strategy = proposalStrategyOf(consensus)
+
+ if (strategy === 'bft') return { faulty: Math.floor((workers - 1) / 3), of: workers, rule: 'byzantine f < n/3' }
+ if (strategy === 'raft') return { faulty: Math.floor((workers - 1) / 2), of: workers, rule: 'raft f < n/2' }
+
+ return null
+}
+
+/** One open proposal against its bar: votes cast, votes needed, and whether its raft timeout has passed. */
+export type Tally = { proposal: Proposal; required: number; nodes: number; isTimedOut: boolean; isDeadlocked: boolean }
+
+export function tallyOf(hive: HiveInfo, proposal: Proposal, nowMs: number): Tally {
+ const nodes = nodesOf(hive)
+ const required = requiredVotes(proposal.strategy, nodes, proposal.quorumPreset)
+ const remaining = nodes - proposal.ballots.length
+
+ return {
+ proposal,
+ required,
+ nodes,
+ isTimedOut: proposal.strategy === 'raft' && proposal.timeoutAtMs !== undefined && nowMs > proposal.timeoutAtMs,
+ // Neither side can still reach the bar: the next vote makes the CLI reject it.
+ isDeadlocked: proposal.votesFor + remaining < required && proposal.votesAgainst + remaining < required,
+ }
+}
+
+/** The open proposal j/k picks, by the shared item index; null when none is open. */
+export function pickedProposal(hive: HiveInfo | null, index: number): Proposal | null {
+ const pending = hive?.pending ?? []
+
+ return pending.length === 0 ? null : (pending[((index % pending.length) + pending.length) % pending.length] ?? null)
+}
+
+/** The next registered worker with no ballot on `proposal`: only a worker may vote, and each votes once. */
+export function nextVoter(hive: HiveInfo, proposal: Proposal): string | null {
+ return hive.workers.find(worker => !proposal.ballots.some(ballot => ballot.voter === worker)) ?? null
+}
+
+/** Why a new proposal would be refused before it is asked: raft allows one pending proposal per term. */
+export function proposeBlock(hive: HiveInfo): string | null {
+ const strategy = proposalStrategyOf(hive.strategy) ?? 'raft'
+ const term = hive.queenTerm ?? 1
+ const holder = strategy === 'raft' ? hive.pending.find(entry => entry.strategy === 'raft' && entry.term === term && entry.status === 'pending') : undefined
+
+ return holder === undefined ? null : `raft term ${term} already has ${holder.type} (${holder.id}) open: decide it first`
+}
+
+export type Liveness = 'busy' | 'idle' | 'down' | 'error' | 'unknown'
+
+/** One hive worker as the stores describe it; `isKnown` is false for an id in no agent store. */
+export type Member = { id: string; role: string; status: string; type?: string; liveness: Liveness; isKnown: boolean }
+
+export function livenessOf(status: string): Liveness {
+ if (/error|fail/i.test(status)) return 'error'
+ if (/busy|active|running|working/i.test(status)) return 'busy'
+ if (/stop|terminat|offline|dead/i.test(status)) return 'down'
+ if (/idle|ready|waiting/i.test(status)) return 'idle'
+
+ return 'unknown'
+}
+
+/** Each of `hive.workers`, its role from agents.json and its status from agents.json or the agent store. */
+export function membersOf(hive: HiveInfo, hiveAgents: readonly HiveAgentRecord[], agents: readonly AgentRecord[]): Member[] {
+ const spawned = new Map(hiveAgents.map(agent => [agent.id, agent]))
+ const stored = new Map(agents.map(agent => [agent.id, agent]))
+
+ return hive.workers.map(id => {
+ const record = spawned.get(id) ?? stored.get(id)
+
+ if (record === undefined) return { id, role: 'n/a', status: 'not in a store', liveness: 'unknown', isKnown: false }
+
+ return { id, role: spawned.get(id)?.role ?? 'n/a', status: record.status, type: record.type, liveness: livenessOf(record.status), isKnown: true }
+ })
+}
diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.ts
index 43327e13cc..765018edd5 100644
--- a/plugins/ruflo-console/hooks/data/parse.ts
+++ b/plugins/ruflo-console/hooks/data/parse.ts
@@ -82,9 +82,48 @@ export type ClaimRecord = {
expiresAtMs?: number
context?: string
}
-export type Proposal = { id: string; type: string; status: string; strategy: string; votesFor: number; votesAgainst: number }
-export type Decision = { id: string; type: string; result: string; votesFor: number; votesAgainst: number }
-export type HiveInfo = { topology: string; strategy?: string; queen?: string; workers: string[]; pending: Proposal[]; history: Decision[] }
+/** One worker's vote on a proposal, as `votes` records it: the voter's id and whether it voted for. */
+export type Ballot = { voter: string; isFor: boolean }
+export type Proposal = {
+ id: string
+ type: string
+ status: string
+ strategy: string
+ votesFor: number
+ votesAgainst: number
+ /** Who voted which way, in the order the store lists them. */
+ ballots: Ballot[]
+ /** Voters the CLI excluded as Byzantine (bft proposals only). */
+ byzantine: string[]
+ value?: string
+ proposedBy?: string
+ proposedAtMs?: number
+ /** Raft: the term the proposal belongs to, and when it may be re-proposed in the next one. */
+ term?: number
+ timeoutAtMs?: number
+ /** Quorum: unanimous, majority or supermajority. */
+ quorumPreset?: string
+}
+export type Decision = { id: string; type: string; result: string; votesFor: number; votesAgainst: number; strategy?: string; term?: number; decidedAtMs?: number; byzantine: number }
+/** A message `hive-mind broadcast` left in the hive's shared memory. */
+export type Broadcast = { id: string; message: string; priority: string; from: string; atMs?: number }
+export type HiveInfo = {
+ topology: string
+ strategy?: string
+ queen?: string
+ queenTerm?: number
+ queenElectedAtMs?: number
+ workers: string[]
+ pending: Proposal[]
+ history: Decision[]
+ /** The newest broadcasts, oldest first, and every shared-memory key (values are not kept: they are anyone's JSON). */
+ broadcasts: Broadcast[]
+ memoryKeys: string[]
+ createdAtMs?: number
+ updatedAtMs?: number
+}
+/** A worker `hive-mind spawn` wrote to `.claude-flow/agents.json`, with the role it was given in the hive. */
+export type HiveAgentRecord = AgentRecord & { role?: string }
/** `.claude-flow/swarm/swarm-state.json`: the running swarm, else the one updated last. */
export function parseSwarmStore(text: string | null): SwarmInfo | null {
@@ -252,10 +291,98 @@ export function parseClaims(text: string | null): ClaimRecord[] {
})
}
-const votesOf = (value: unknown): { votesFor: number; votesAgainst: number } => {
- const votes = valuesOf(value)
+const votesOf = (value: unknown): { votesFor: number; votesAgainst: number; ballots: Ballot[] } => {
+ const ballots = Object.entries(recordOf(value) ?? {})
+ .slice(0, MAX_RECORDS)
+ .flatMap(([voter, vote]) => (idOf(voter) !== null && typeof vote === 'boolean' ? [{ voter, isFor: vote }] : []))
+
+ return { votesFor: ballots.filter(ballot => ballot.isFor).length, votesAgainst: ballots.filter(ballot => !ballot.isFor).length, ballots }
+}
+
+const idsOf = (value: unknown, max = 50): string[] => (Array.isArray(value) ? value : []).slice(0, max).flatMap(entry => (idOf(entry) !== null ? [entry as string] : []))
- return { votesFor: votes.filter(vote => vote === true).length, votesAgainst: votes.filter(vote => vote === false).length }
+/** A proposal's value as one bounded line: a string as it is, anything else as its JSON. */
+function valueText(value: unknown): string | undefined {
+ if (typeof value === 'string') return stringOf(value, 120)
+ if (value === undefined || value === null) return undefined
+
+ try {
+ return stringOf(JSON.stringify(value).slice(0, 400), 120)
+ } catch {
+ return undefined
+ }
+}
+
+function proposalOf(entry: unknown): Proposal | null {
+ const proposal = recordOf(entry)
+ const id = idOf(proposal?.proposalId)
+
+ if (proposal === null || id === null) return null
+
+ const out: Proposal = {
+ id,
+ type: stringOf(proposal.type, 40) ?? 'proposal',
+ status: stringOf(proposal.status, 20) ?? 'pending',
+ strategy: stringOf(proposal.strategy, 20) ?? 'unknown',
+ ...votesOf(proposal.votes),
+ byzantine: idsOf(proposal.byzantineVoters),
+ }
+ const value = valueText(proposal.value)
+ const proposedBy = idOf(proposal.proposedBy)
+ const proposedAtMs = msOf(proposal.proposedAt)
+ const term = numberOf(proposal.term)
+ const timeoutAtMs = msOf(proposal.timeoutAt)
+ const quorumPreset = stringOf(proposal.quorumPreset, 20)
+
+ if (value !== undefined) out.value = value
+ if (proposedBy !== null) out.proposedBy = proposedBy
+ if (proposedAtMs !== undefined) out.proposedAtMs = proposedAtMs
+ if (term !== undefined) out.term = term
+ if (timeoutAtMs !== undefined) out.timeoutAtMs = timeoutAtMs
+ if (quorumPreset !== undefined) out.quorumPreset = quorumPreset
+
+ return out
+}
+
+function decisionOf(entry: unknown): Decision | null {
+ const decision = recordOf(entry)
+ const id = idOf(decision?.proposalId)
+ const votes = recordOf(decision?.votes)
+
+ if (decision === null || id === null) return null
+
+ const out: Decision = {
+ id,
+ type: stringOf(decision.type, 40) ?? 'proposal',
+ result: stringOf(decision.result, 20) ?? 'unknown',
+ votesFor: numberOf(votes?.for) ?? 0,
+ votesAgainst: numberOf(votes?.against) ?? 0,
+ byzantine: idsOf(decision.byzantineDetected).length,
+ }
+ const strategy = stringOf(decision.strategy, 20)
+ const term = numberOf(decision.term)
+ const decidedAtMs = msOf(decision.decidedAt)
+
+ if (strategy !== undefined) out.strategy = strategy
+ if (term !== undefined) out.term = term
+ if (decidedAtMs !== undefined) out.decidedAtMs = decidedAtMs
+
+ return out
+}
+
+/** `sharedMemory.broadcasts`, the last 20, each field bounded: the message is free text another process wrote. */
+function broadcastsOf(value: unknown): Broadcast[] {
+ return (Array.isArray(value) ? value : []).slice(-20).flatMap(entry => {
+ const message = recordOf(entry)
+ const id = idOf(message?.messageId)
+ const text = stringOf(message?.message, 160)
+
+ if (message === null || id === null || text === undefined) return []
+
+ const atMs = msOf(message.timestamp)
+
+ return [{ id, message: text, priority: stringOf(message.priority, 12) ?? 'normal', from: idOf(message.fromId) ?? 'system', ...(atMs !== undefined && { atMs }) }]
+ })
}
/** `.claude-flow/hive-mind/state.json`, without its capability token. */
@@ -266,47 +393,53 @@ export function parseHive(text: string | null): HiveInfo | null {
return null
}
- const queen = idOf(recordOf(hive.queen)?.agentId)
+ 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',
- ...votesOf(proposal.votes),
- },
- ]
- })
- const history = (Array.isArray(consensus?.history) ? consensus.history : []).slice(-50).flatMap(entry => {
- const decision = recordOf(entry)
- const id = idOf(decision?.proposalId)
- const votes = recordOf(decision?.votes)
-
- return decision === null || id === null
- ? []
- : [{ id, type: stringOf(decision.type, 40) ?? 'proposal', result: stringOf(decision.result, 20) ?? 'unknown', votesFor: numberOf(votes?.for) ?? 0, votesAgainst: numberOf(votes?.against) ?? 0 }]
- })
+ const shared = recordOf(hive.sharedMemory)
const info: HiveInfo = {
topology: stringOf(hive.topology, 40) ?? 'unknown',
- workers: (Array.isArray(hive.workers) ? hive.workers : []).slice(0, MAX_RECORDS).flatMap(worker => (idOf(worker) !== null ? [worker as string] : [])),
- pending,
- history,
+ workers: idsOf(hive.workers, MAX_RECORDS),
+ pending: (Array.isArray(consensus?.pending) ? consensus.pending : []).slice(-50).flatMap(entry => proposalOf(entry) ?? []),
+ history: (Array.isArray(consensus?.history) ? consensus.history : []).slice(-50).flatMap(entry => decisionOf(entry) ?? []),
+ broadcasts: broadcastsOf(shared?.broadcasts),
+ memoryKeys: Object.keys(shared ?? {}).slice(0, 200).flatMap(key => (idOf(key) !== null ? [key] : [])),
}
const strategy = stringOf(hive.consensusStrategy, 30)
+ const term = numberOf(queen?.term)
+ const electedAtMs = msOf(queen?.electedAt)
+ const createdAtMs = msOf(hive.createdAt)
+ const updatedAtMs = msOf(hive.updatedAt)
if (strategy !== undefined) info.strategy = strategy
- if (queen !== null) info.queen = queen
+ if (queenId !== null) info.queen = queenId
+ if (term !== undefined) info.queenTerm = term
+ if (electedAtMs !== undefined) info.queenElectedAtMs = electedAtMs
+ if (createdAtMs !== undefined) info.createdAtMs = createdAtMs
+ if (updatedAtMs !== undefined) info.updatedAtMs = updatedAtMs
return info
}
+/** `.claude-flow/agents.json`: the workers `hive-mind spawn` writes (the other agent tools use agents/store.json), with their hive role. */
+export function parseHiveAgents(text: string | null): HiveAgentRecord[] {
+ const roles = new Map(
+ valuesOf(jsonObject(text)?.agents).flatMap(entry => {
+ const agent = recordOf(entry)
+ const id = idOf(agent?.agentId)
+ const role = stringOf(recordOf(agent?.config)?.hiveRole, 20)
+
+ return id !== null && role !== undefined ? [[id, role] as const] : []
+ }),
+ )
+
+ return parseAgents(text).map(agent => {
+ const role = roles.get(agent.id)
+
+ return role === undefined ? agent : { ...agent, role }
+ })
+}
+
/** The tail of an id a person can tell apart at a glance: `agent-1790954653916-od014i` → `od014i`. */
export function shortId(id: string): string {
const tail = id.split(/[-_:]/).pop() ?? id
diff --git a/plugins/ruflo-console/hooks/data/snapshot.ts b/plugins/ruflo-console/hooks/data/snapshot.ts
index 42d0c360d9..9349945c83 100644
--- a/plugins/ruflo-console/hooks/data/snapshot.ts
+++ b/plugins/ruflo-console/hooks/data/snapshot.ts
@@ -29,11 +29,13 @@ import {
parseAgents,
parseClaims,
parseHive,
+ parseHiveAgents,
parseSwarmPointer,
parseSwarmStore,
parseTasks,
type AgentRecord,
type ClaimRecord,
+ type HiveAgentRecord,
type HiveInfo,
type SwarmInfo,
type TaskRecord,
@@ -60,6 +62,8 @@ export type Snapshot = {
tasks: TaskRecord[]
claims: ClaimRecord[]
hive: HiveInfo | null
+ /** Workers `hive-mind spawn` wrote to .claude-flow/agents.json, apart from the agent store. */
+ hiveAgents: HiveAgentRecord[]
activity: ReturnType<typeof parseActivity>
daemon: Daemon | null
neural: NeuralStats | null
@@ -102,6 +106,7 @@ export async function readSnapshot(fs: ReaderFs, cache: ReadCache, cwd: string,
tasks: parseTasks(text('tasks')),
claims: parseClaims(text('claims')),
hive: parseHive(text('hive')),
+ hiveAgents: parseHiveAgents(text('hiveAgents')),
activity: parseActivity(text('activity')),
daemon: parseDaemon(text('daemon')),
neural: parseNeural(text('neural')),
diff --git a/plugins/ruflo-console/hooks/gfx/hive.ts b/plugins/ruflo-console/hooks/gfx/hive.ts
new file mode 100644
index 0000000000..7ab56150f0
--- /dev/null
+++ b/plugins/ruflo-console/hooks/gfx/hive.ts
@@ -0,0 +1,170 @@
+/**
+ * The Hive-Mind picture: a honeycomb of flat-topped hex cells, the queen's crown in the centre and her workers in rings
+ * around her, then one meter per open proposal. Each cell's glyph says the worker's role and its colour its liveness;
+ * its walls say how it voted on the picked proposal (green for, pink against, yellow excluded as Byzantine).
+ *
+ * Motion means data: a cell flashes for HIVE_PULSE_MS after the console sees that worker vote, join or leave, and is
+ * still otherwise, so with no fresh event every frame is the same. Colours are on the xterm-256 cube, which is what
+ * Claude Code draws a Raster in where the terminal has no true colour. The size depends only on the model and the
+ * columns, never on the clock, so every animation frame fits the Raster as mounted.
+ */
+import { HIVE_PULSE_MS } from '../data/hive'
+import { Grid } from './raster'
+
+/** xterm-256 cube colours: pink, yellow, cyan, green, magenta, and the greys. */
+export const HIVE_COLOR = { pink: 0xd7005f, yellow: 0xd7af00, cyan: 0x00afd7, green: 0x5fd75f, magenta: 0xd700d7, white: 0xffffff, grey: 0x808080, wall: 0x585858, faint: 0x3a3a3a } as const
+
+export type HiveCell = {
+ id: string
+ /** One glyph: ♛ the queen, ● worker, ◆ specialist, ▲ scout, ○ not in any store. */
+ glyph: string
+ /** Up to three characters under the glyph's right: the short id. */
+ tag: string
+ color: number
+ /** The wall colour for its ballot on the picked proposal; absent when it has not voted. */
+ vote?: 'for' | 'against' | 'byzantine'
+ pulseAtMs?: number
+}
+
+export type HiveMeter = { label: string; votesFor: number; votesAgainst: number; required: number; nodes: number; note: string; isPicked: boolean }
+
+export type HivePictureModel = { queen: HiveCell; members: HiveCell[]; meters: HiveMeter[] }
+
+/** A cell is 6 columns by 3 rows; neighbouring columns of cells step 5 across and 1 down, so walls are shared. */
+const CELL_W = 6
+const STEP_X = 5
+const TOP = ' ▁▁▁▁ '
+const MID = '╱ ╲'
+const BOTTOM = '╲▁▁▁▁╱'
+/** Axial steps for flat-topped hexes that walk a ring clockwise from its top cell. */
+const CLOCKWISE: readonly [number, number][] = [
+ [1, 0],
+ [0, 1],
+ [-1, 1],
+ [-1, 0],
+ [0, -1],
+ [1, -1],
+]
+export const MAX_RINGS = 4
+const MAX_METERS = 5
+
+/** Cells a honeycomb of `rings` rings holds, the centre included: 1, 7, 19, 37, 61. */
+export const cellsIn = (rings: number): number => 1 + 3 * rings * (rings + 1)
+
+/** The rings drawn: enough for every member where the width allows, at most MAX_RINGS. */
+export function ringsFor(members: number, columns: number): number {
+ const fits = Math.max(0, Math.min(MAX_RINGS, Math.floor((columns - CELL_W) / (STEP_X * 2))))
+ let rings = 0
+
+ while (rings < fits && cellsIn(rings) < members + 1) rings += 1
+
+ return rings
+}
+
+/** Axial coordinates of every cell, centre first, then ring by ring, each clockwise from the top. */
+export function spiral(rings: number): [number, number][] {
+ const out: [number, number][] = [[0, 0]]
+
+ for (let k = 1; k <= rings; k++) {
+ let q = 0
+ let r = -k
+
+ for (const [dq, dr] of CLOCKWISE) {
+ for (let step = 0; step < k; step++) {
+ out.push([q, r])
+ q += dq
+ r += dr
+ }
+ }
+ }
+
+ return out
+}
+
+/** The top-left corner of a cell, for a honeycomb of `rings` rings centred in `columns`. */
+export function cellOrigin(q: number, r: number, rings: number, columns: number): { x: number; y: number } {
+ return { x: Math.floor(columns / 2) - Math.floor(CELL_W / 2) + q * STEP_X, y: 2 * rings + 2 * r + q }
+}
+
+export const hiveRows = (model: HivePictureModel, columns: number): number => {
+ const meters = Math.min(MAX_METERS, model.meters.length)
+
+ return 4 * ringsFor(model.members.length, columns) + 3 + (meters > 0 ? meters + 1 : 0)
+}
+
+/** Draws only the non-space characters of `text`, so a cell never blanks the wall its neighbour shares. */
+function ink(grid: Grid, x: number, y: number, text: string, color: number): void {
+ ;[...text].forEach((ch, i) => {
+ if (ch !== ' ') grid.set(x + i, y, ch, color)
+ })
+}
+
+/** Whether a cell is mid-pulse at `t`, and then which half of its blink. */
+function pulseOf(cell: HiveCell, t: number): { isLit: boolean; isPulsing: boolean } {
+ const age = cell.pulseAtMs === undefined ? -1 : t - cell.pulseAtMs
+
+ if (age < 0 || age >= HIVE_PULSE_MS) return { isLit: false, isPulsing: false }
+
+ return { isLit: Math.floor(age / 250) % 2 === 0, isPulsing: true }
+}
+
+const VOTE_WALL = { for: HIVE_COLOR.green, against: HIVE_COLOR.pink, byzantine: HIVE_COLOR.yellow } as const
+
+function drawCell(grid: Grid, cell: HiveCell, x: number, y: number, t: number, isQueen: boolean): void {
+ const pulse = pulseOf(cell, t)
+ const wall = pulse.isLit ? HIVE_COLOR.white : cell.vote !== undefined ? VOTE_WALL[cell.vote] : isQueen ? HIVE_COLOR.magenta : HIVE_COLOR.wall
+
+ ink(grid, x, y, TOP, wall)
+ ink(grid, x, y + 1, MID, wall)
+ ink(grid, x, y + 2, BOTTOM, wall)
+
+ // The interior is cleared first, then the glyph and the tag; a pulse lights the glyph with the walls.
+ grid.text(x + 1, y + 1, ' ')
+ grid.set(x + 1, y + 1, cell.glyph, pulse.isLit ? HIVE_COLOR.white : cell.color)
+ grid.text(x + 2, y + 1, cell.tag.slice(0, 3), pulse.isPulsing ? HIVE_COLOR.white : isQueen ? HIVE_COLOR.magenta : HIVE_COLOR.grey)
+}
+
+/** A proposal's bar: green votes for, pink against, the rest faint, and a yellow tick where the quorum falls. */
+function drawMeter(grid: Grid, meter: HiveMeter, y: number, columns: number): void {
+ const label = `${meter.isPicked ? '▸' : ' '}${meter.label}`.slice(0, 14).padEnd(15)
+ const width = Math.max(8, Math.min(32, columns - label.length - 34))
+ const cells = (votes: number) => Math.round((Math.min(votes, meter.nodes) / Math.max(1, meter.nodes)) * width)
+ const forCells = cells(meter.votesFor)
+ const againstCells = Math.min(width - forCells, cells(meter.votesAgainst))
+ const tick = Math.min(width - 1, Math.max(0, cells(meter.required) - 1))
+
+ grid.text(0, y, label, meter.isPicked ? HIVE_COLOR.white : HIVE_COLOR.grey)
+
+ for (let i = 0; i < width; i++) {
+ const color = i < forCells ? HIVE_COLOR.green : i < forCells + againstCells ? HIVE_COLOR.pink : HIVE_COLOR.faint
+ const isTick = i === tick && i >= forCells + againstCells
+
+ grid.set(label.length + i, y, isTick ? '┃' : i < forCells + againstCells ? '█' : '░', isTick ? HIVE_COLOR.yellow : color)
+ }
+
+ grid.text(label.length + width + 1, y, `${meter.votesFor}/${meter.required} for · ${meter.votesAgainst} against${meter.note === '' ? '' : ` · ${meter.note}`}`.slice(0, Math.max(0, columns - label.length - width - 1)), meter.isPicked ? HIVE_COLOR.cyan : HIVE_COLOR.grey)
+}
+
+export function hivePicture(model: HivePictureModel, columns: number, t: number): Grid {
+ const rings = ringsFor(model.members.length, columns)
+ const grid = new Grid(columns, hiveRows(model, columns))
+ const slots = spiral(rings)
+ const cells = [model.queen, ...model.members]
+
+ // Drawn back to front, the queen last, so her magenta walls stay whole where they meet a worker's.
+ slots.slice(0, cells.length).reverse().forEach(([q, r], back) => {
+ const i = Math.min(slots.length, cells.length) - 1 - back
+ const cell = cells[i]
+ const { x, y } = cellOrigin(q, r, rings, columns)
+
+ if (cell !== undefined) drawCell(grid, cell, x, y, t, i === 0)
+ })
+
+ const hidden = cells.length - slots.length
+
+ if (hidden > 0) grid.text(Math.max(0, columns - 14), 4 * rings + 2, `+${hidden} more`.slice(0, 14), HIVE_COLOR.grey)
+
+ model.meters.slice(0, MAX_METERS).forEach((meter, i) => drawMeter(grid, meter, 4 * rings + 4 + i, columns))
+
+ return grid
+}
diff --git a/plugins/ruflo-console/hooks/hive.ts b/plugins/ruflo-console/hooks/hive.ts
new file mode 100644
index 0000000000..5d5faf0a06
--- /dev/null
+++ b/plugins/ruflo-console/hooks/hive.ts
@@ -0,0 +1,82 @@
+/**
+ * What the Hive-Mind view asks ruflo to do, each a fixed argv. A vote goes through the `hive-mind consensus` subcommand
+ * because only it carries the hive's capability token (it reads the token off disk itself; the console never does), and
+ * the tool counts a vote only from a registered worker, so a vote is cast as one. Propose, broadcast and spawn need no
+ * token and run as `mcp exec` with one JSON argument. Ids pass `idOf`; free text passes `textArg`.
+ */
+import { exec, type ActionSpec } from './actions'
+import { HIVE_ROLES, nextVoter, proposalStrategyOf, proposeBlock } from './data/hive'
+import { idOf, type HiveInfo, type Proposal } from './data/parse'
+import { textArg } from './ops'
+
+/** Who the console names as proposer and sender: the tool records it, and checks it only as an identifier. */
+export const OPERATOR = 'console-operator'
+
+const TYPE = /^([A-Za-z0-9_.-]{1,40}):\s*(.+)$/
+
+/** `design: use raft` proposes a `design`; text with no such prefix is a `general` proposal. */
+export function proposalText(text: string): { type: string; value: string } {
+ const match = TYPE.exec(text.trim())
+
+ return match === null ? { type: 'general', value: text.trim() } : { type: match[1] as string, value: (match[2] as string).trim() }
+}
+
+/** A vote on `proposal` as the next worker that has not voted on it; null when no worker is left to vote as. */
+export function hiveVote(hive: HiveInfo, proposal: Proposal, isFor: boolean): ActionSpec | null {
+ const id = idOf(proposal.id)
+ const voter = nextVoter(hive, proposal)
+
+ if (id === null || voter === null || idOf(voter) === null) return null
+
+ return {
+ label: `vote ${isFor ? 'for' : 'against'} ${proposal.type} (${id}) as worker ${voter}`,
+ args: ['hive-mind', 'consensus', '--action', 'vote', '--proposal-id', id, '--vote', isFor ? 'yes' : 'no', '--voter-id', voter],
+ expect: `${voter}'s ballot on the proposal, or the proposal decided`,
+ verify: snapshot => snapshot.hive?.history.some(entry => entry.id === id) === true || snapshot.hive?.pending.some(entry => entry.id === id && entry.ballots.some(ballot => ballot.voter === voter)) === true,
+ }
+}
+
+/** A new proposal under the hive's own strategy; null when the text cannot be passed or raft would refuse it. */
+export function hivePropose(hive: HiveInfo, text: string): ActionSpec | null {
+ const { type, value } = proposalText(text)
+ const body = textArg(value, 300)
+ const strategy = proposalStrategyOf(hive.strategy)
+ const known = new Set([...hive.pending, ...hive.history].map(entry => entry.id))
+
+ if (body === null || proposeBlock(hive) !== null) return null
+
+ return {
+ label: `propose ${type}: "${body.slice(0, 40)}" (${strategy ?? 'raft, the tool default'})`,
+ args: exec('hive-mind_consensus', { action: 'propose', type, value: body, voterId: OPERATOR, ...(strategy !== null && { strategy }) }),
+ expect: 'a new pending proposal in .claude-flow/hive-mind/state.json',
+ verify: snapshot => snapshot.hive?.pending.some(entry => !known.has(entry.id) && entry.type === type) === true,
+ }
+}
+
+/** A message to every worker, kept in the hive's shared memory (the last 100). */
+export function hiveBroadcast(text: string): ActionSpec | null {
+ const message = textArg(text, 160)
+
+ return message === null
+ ? null
+ : {
+ label: `broadcast "${message.slice(0, 40)}" to the hive`,
+ args: exec('hive-mind_broadcast', { message, priority: 'normal', fromId: OPERATOR }),
+ expect: 'the message in the shared memory broadcasts',
+ verify: snapshot => snapshot.hive?.broadcasts.some(entry => entry.message === message) === true,
+ }
+}
+
+/** One worker spawned and joined to the hive (agents.json and state.json both change). */
+export function hiveSpawn(hive: HiveInfo, role: string): ActionSpec | null {
+ const before = hive.workers.length
+
+ return (HIVE_ROLES as readonly string[]).includes(role)
+ ? {
+ label: `spawn a hive ${role} and join it`,
+ args: exec('hive-mind_spawn', { role, agentType: 'worker', prefix: 'hive-worker' }),
+ expect: 'one more worker in the hive',
+ verify: snapshot => (snapshot.hive?.workers.length ?? 0) > before,
+ }
+ : null
+}
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index 5b38c583a3..58c5b16609 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -3,6 +3,8 @@
* entries from the state; the controller runs the one picked. Text-taking entries (route, store, search) read their
* argument from the query after their keyword: `route fix the login bug`.
*/
+import { HIVE_ROLES, pickedProposal } from './data/hive'
+import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote } from './hive'
import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'
import { AGENT_TYPES, agentLogs, dispatchWorker, harnessAudit, harnessScore, memorySearch, memoryStore, reroute, setClaimStatus, spawnAgent, stopAgent, swarmInit, swarmStop, vote, WORKERS } from './ops'
import { VIEWS, type State, type ViewId } from './state'
@@ -46,7 +48,7 @@ export function fuzzy(query: string, label: string): number | null {
return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0)
}
-const TEXT_KEYWORDS = ['route', 'store', 'search'] as const
+const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast'] as const
/** Every entry for the state as it is, before filtering. */
export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
@@ -86,6 +88,24 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
add(`vote-no-${proposal.id}`, 'hive', `vote no on ${proposal.type} (${proposal.id})`, { kind: 'spec', spec: vote(proposal.id, false), why: 'that proposal id cannot be passed to ruflo' })
}
+ const hive = state.snapshot?.hive ?? null
+ const picked = pickedProposal(hive, state.select.item)
+
+ // The Hive-Mind view's actions; a text entry's id is its keyword, as `runById` reads the text after it.
+ if (hive !== null) {
+ if (picked !== null) {
+ const why = hive.workers.length === 0 ? 'no registered worker to vote as: spawn one' : 'every worker has voted on it'
+
+ add('hive-vote-yes', 'hive', `vote for ${picked.type} as the next worker (${picked.id})`, { kind: 'spec', spec: hiveVote(hive, picked, true), why })
+ add('hive-vote-no', 'hive', `vote against ${picked.type} as the next worker (${picked.id})`, { kind: 'spec', spec: hiveVote(hive, picked, false), why })
+ }
+
+ add('propose', 'hive', 'propose <type: text>: put a decision to the hive', { kind: 'text', keyword: 'propose', make: text => hivePropose(hive, text) })
+ add('broadcast', 'hive', 'broadcast <text>: message every hive worker', { kind: 'text', keyword: 'broadcast', make: hiveBroadcast })
+
+ for (const role of HIVE_ROLES) add(`hive-spawn-${role}`, 'hive', `spawn a hive ${role} and join it`, { kind: 'spec', spec: hiveSpawn(hive, role), why: 'unknown role' })
+ }
+
add('mh-score', 'metaharness', 'score the harness now (metaharness score)', { kind: 'spec', spec: harnessScore(), why: '' })
add('mh-audit', 'metaharness', 'run a MetaHarness audit (oia-audit)', { kind: 'spec', spec: harnessAudit(), why: '' })
@@ -95,7 +115,7 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
add('store', 'memory', 'store <text>: save a note in memory namespace console', { kind: 'text', keyword: 'store', make: text => memoryStore(text, nowMs) })
add('search', 'memory', 'search <query>: semantic memory search', { kind: 'text', keyword: 'search', make: memorySearch })
- for (const view of VIEWS) add(`view-${view.id}`, 'views', `go to ${view.label} (${view.key})`, { kind: 'view', view: view.id })
+ for (const view of VIEWS) add(`view-${view.id}`, 'views', `go to ${view.label}${view.key === '' ? '' : ` (${view.key})`}`, { kind: 'view', view: view.id })
add('refresh', 'console', 'refresh now', { kind: 'command', name: 'refresh' })
add('help', 'console', 'help: keys and commands', { kind: 'command', name: 'help' })
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index b938cc908c..ccb6cfd053 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -9,7 +9,7 @@ import type { RufloRoute, RufloSnapshot } from '../types'
export const PLUGIN_NAME = 'ruflo-console'
export const PANE_ID = 'ruflo-console'
-export type ViewId = 'menu' | 'overview' | 'swarm' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'missions' | 'xruv' | 'terminal' | 'agent'
+export type ViewId = 'menu' | 'overview' | 'swarm' | 'hive' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'missions' | 'xruv' | 'terminal' | 'agent'
/**
* The views in tab order, each with its hotkey and the inline height it asks for. Digits are the first nine; the three
@@ -24,6 +24,8 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st
{ id: 'menu', key: '0', label: 'Main Menu', short: 'Mnu', icon: '📟', blurb: 'the board: every area by its key, the line status, and a prompt that takes a key or a name', rows: 32 },
{ id: 'overview', key: '1', label: 'Overview', short: 'Ovr', icon: '🏠', blurb: 'what ruflo is doing here: subsystems, mods, health alerts and live activity', rows: 26 },
{ id: 'swarm', key: '2', label: 'Swarm', short: 'Swm', icon: '🐝', blurb: 'the swarm as ruflo wrote it: topology, agents at work, and the hive-mind votes', rows: 30 },
+ // No hotkey: every digit and letter is taken. It is reached from the tab, the menu, the palette or /ruflo hive.
+ { id: 'hive', key: '', label: 'Hive-Mind', short: 'Hiv', icon: '👑', blurb: 'the queen, her workers and their votes: quorum, fault tolerance, proposals and broadcasts', rows: 40 },
{ id: 'claims', key: '3', label: 'Claims', short: 'Clm', icon: '📌', blurb: 'who holds which task: claim, release, hand off or steal, each after a y/n confirm', rows: 30 },
{ id: 'federation', key: '4', label: 'Federation', short: 'Fed', icon: '🌐', blurb: 'this node, its peers, keys and channels, placed by how far each is trusted', rows: 26 },
{ id: 'plugins', key: '5', label: 'Plugins', short: 'Plg', icon: '🧩', blurb: 'ruflo plugins: installed, enabled, in the marketplace clone, and loaded as mods', rows: 30 },
@@ -47,7 +49,7 @@ export const rowsOf = (view: ViewId): number => (view === 'agent' ? AGENT_VIEW.r
export const viewOf = (word: string): ViewId | null => {
const lower = word.trim().toLowerCase()
- return VIEWS.find(view => view.id === lower || view.key === lower || view.label.toLowerCase() === lower || (lower.length >= 3 && view.id.startsWith(lower)))?.id ?? null
+ return VIEWS.find(view => view.id === lower || (view.key !== '' && view.key === lower) || view.label.toLowerCase() === lower || (lower.length >= 3 && view.id.startsWith(lower)))?.id ?? null
}
/**
diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.ts
index 93d26951f9..b3efe40cc9 100644
--- a/plugins/ruflo-console/hooks/views/frames.ts
+++ b/plugins/ruflo-console/hooks/views/frames.ts
@@ -5,6 +5,8 @@
*/
import type { AuditTrend, HarnessScore, Intelligence } from '../data/cli'
import { recentByAgent } from '../data/events'
+import { HIVE_PULSE_MS } from '../data/hive'
+import { hivePicture } from '../gfx/hive'
import { agentLabels } from '../data/parse'
import type { Snapshot } from '../data/snapshot'
import type { Channels, Peers, Roster } from '../data/cli'
@@ -17,6 +19,7 @@ import { PROBES, severityOf } from '../data/cli'
import { EXPECTED_IN_MARKET, RUFLO_MARKET } from '../data/snapshot'
import { isBooting, isCompactPane, VIEWS, type State } from '../state'
import { live } from './common'
+import { hivePictureModelOf } from './hive'
import { openTasks } from './select'
export const MAX_NODES = 100
@@ -148,6 +151,12 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numb
if (model !== null) pictures.set('topology', topologyPicture(model, width, topologyRows(width, model.nodes.length), t))
break
}
+ case 'hive': {
+ const model = hivePictureModelOf(state, nowMs, recentByAgent(state.events, nowMs, HIVE_PULSE_MS + 600))
+
+ if (model !== null) pictures.set('hive', hivePicture(model, width, t))
+ break
+ }
case 'claims': {
const cards = flowModelOf(snapshot?.claims ?? [], openTasks(state), snapshot?.agents ?? [], snapshot?.tasks ?? [])
diff --git a/plugins/ruflo-console/hooks/views/hive.ts b/plugins/ruflo-console/hooks/views/hive.ts
new file mode 100644
index 0000000000..219ce53ac4
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/hive.ts
@@ -0,0 +1,244 @@
+/**
+ * The Hive-Mind view: what `.claude-flow/hive-mind/state.json` records. The queen and her term, the consensus strategy
+ * with the fault tolerance and quorum it implies, every worker with its role and liveness, the open proposals against
+ * their bar (pick one with j/k), the decided ones, and the broadcasts. Every action asks y/n first and runs one fixed
+ * argv: vote (as the next worker that has not voted), propose, broadcast, spawn.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { faultTolerance, membersOf, nextVoter, nodesOf, pickedProposal, proposalStrategyOf, proposeBlock, requiredVotes, tallyOf, type Liveness, type Member, type Tally } from '../data/hive'
+import { shortId, type HiveInfo } from '../data/parse'
+import { HIVE_COLOR, type HiveCell, type HivePictureModel } from '../gfx/hive'
+import type { State } from '../state'
+import { ago, button, clip, col, kv, picture, row, rule, text, THEME, type Ctx } from './common'
+
+const ROLE_GLYPH: Record<string, string> = { worker: '●', specialist: '◆', scout: '▲' }
+const LIVE_COLOR: Record<Liveness, number> = { busy: HIVE_COLOR.yellow, idle: HIVE_COLOR.cyan, error: HIVE_COLOR.pink, down: HIVE_COLOR.grey, unknown: HIVE_COLOR.wall }
+const LIVE_THEME = (liveness: Liveness): { color?: string; dimColor?: boolean } =>
+ liveness === 'busy' ? { color: THEME.warn } : liveness === 'idle' ? { color: THEME.info } : liveness === 'error' ? { color: THEME.bad } : { dimColor: true }
+
+const glyphOf = (member: Member): string => (member.isKnown ? (ROLE_GLYPH[member.role] ?? '●') : '○')
+
+/** The bar a proposal must clear, as the CLI's rule reads in words. */
+function ruleOf(strategy: string, preset?: string): string {
+ if (strategy === 'bft') return '2/3 + 1'
+ if (strategy === 'quorum') return preset ?? 'majority'
+
+ return 'majority'
+}
+
+/** The honeycomb's model for this frame: the queen, each worker's cell with its ballot on the picked proposal, the meters. */
+export function hivePictureModelOf(state: State, nowMs: number, pulses: Map<string, number>): HivePictureModel | null {
+ const snap = state.snapshot
+ const hive = snap?.hive ?? null
+
+ if (snap === null || hive === null) return null
+
+ const picked = pickedProposal(hive, state.select.item)
+ const queenPulse = hive.queen === undefined ? undefined : pulses.get(hive.queen)
+ const members = membersOf(hive, snap.hiveAgents, snap.agents).map((member): HiveCell => {
+ const ballot = picked?.ballots.find(entry => entry.voter === member.id)
+ const vote = picked?.byzantine.includes(member.id) === true ? 'byzantine' : ballot === undefined ? undefined : ballot.isFor ? 'for' : 'against'
+ const pulseAtMs = pulses.get(member.id)
+
+ return { id: member.id, glyph: glyphOf(member), tag: shortId(member.id).slice(-3), color: LIVE_COLOR[member.liveness], ...(vote !== undefined && { vote }), ...(pulseAtMs !== undefined && { pulseAtMs }) }
+ })
+
+ return {
+ queen: { id: hive.queen ?? 'queen', glyph: hive.queen === undefined ? '?' : '♛', tag: hive.queenTerm === undefined ? '' : `T${hive.queenTerm}`, color: hive.queen === undefined ? HIVE_COLOR.grey : HIVE_COLOR.magenta, ...(queenPulse !== undefined && { pulseAtMs: queenPulse }) },
+ members,
+ meters: hive.pending.map(proposal => {
+ const tally = tallyOf(hive, proposal, nowMs)
+
+ return { label: proposal.type, votesFor: proposal.votesFor, votesAgainst: proposal.votesAgainst, required: tally.required, nodes: tally.nodes, note: noteOf(tally), isPicked: proposal.id === picked?.id }
+ }),
+ }
+}
+
+/** A proposal's strategy, term and state of play in a few words. */
+function noteOf(tally: Tally): string {
+ const { proposal } = tally
+
+ return [`${proposal.strategy}${proposal.term !== undefined ? ` T${proposal.term}` : ''}${proposal.quorumPreset !== undefined ? ` ${proposal.quorumPreset}` : ''}`, tally.isTimedOut ? 'timed out' : '', tally.isDeadlocked ? 'deadlocked' : '']
+ .filter(Boolean)
+ .join(' · ')
+}
+
+/** A ten-cell text bar of a proposal's votes over the hive's nodes, for the text form of the view. */
+function bar(tally: Tally): string {
+ const of = (votes: number) => Math.round((Math.min(votes, tally.nodes) / tally.nodes) * 10)
+ const yes = of(tally.proposal.votesFor)
+ const no = Math.min(10 - yes, of(tally.proposal.votesAgainst))
+
+ return `${'█'.repeat(yes)}${'▓'.repeat(no)}${'░'.repeat(10 - yes - no)}`
+}
+
+function summary(ctx: Ctx, hive: HiveInfo, members: Member[]): RenderElement[] {
+ const workers = hive.workers.length
+ const strategy = proposalStrategyOf(hive.strategy)
+ const tolerance = faultTolerance(hive.strategy, workers)
+ const required = requiredVotes(strategy ?? 'raft', nodesOf(hive))
+ const isRaft = strategy === 'raft'
+ const counts = (liveness: Liveness) => members.filter(member => member.liveness === liveness).length
+
+ return [
+ kv(
+ ctx,
+ isRaft ? 'queen (leader)' : 'queen',
+ hive.queen === undefined ? 'n/a — no queen recorded' : `${hive.queen}${hive.queenTerm !== undefined ? ` · term ${hive.queenTerm}` : ''} · elected ${ago(hive.queenElectedAtMs, ctx.nowMs)}`,
+ THEME.head,
+ ),
+ kv(ctx, 'consensus', `${hive.strategy ?? 'n/a'} · proposals vote ${strategy ?? `raft (the tool's default: ${hive.strategy ?? 'this strategy'} has no vote rule of its own)`}`),
+ kv(ctx, 'fault tolerance', tolerance === null ? `n/a — ${workers === 0 ? 'no workers' : `no bound stated for ${hive.strategy ?? 'this strategy'}`}` : `tolerates ${tolerance.faulty} faulty of ${tolerance.of} (${tolerance.rule})`),
+ kv(ctx, 'quorum', `${required} of ${nodesOf(hive)} votes to pass (${ruleOf(strategy ?? 'raft')})${workers === 0 ? ' · the CLI counts an empty hive as one node' : ''}`),
+ kv(ctx, 'workers', workers === 0 ? 'none yet — spawn one below' : `${workers} · ${counts('busy')} busy · ${counts('idle')} idle · ${counts('down') + counts('error')} down · ${members.filter(member => !member.isKnown).length} in no agent store`),
+ kv(ctx, 'shared memory', `${hive.memoryKeys.length} key${hive.memoryKeys.length === 1 ? '' : 's'} · ${hive.broadcasts.length} broadcast${hive.broadcasts.length === 1 ? '' : 's'} · updated ${ago(hive.updatedAtMs, ctx.nowMs)}`),
+ ]
+}
+
+function workersSection(ctx: Ctx, hive: HiveInfo, members: Member[]): RenderElement[] {
+ const picked = pickedProposal(hive, ctx.state.select.item)
+ const rows: RenderElement[] = [rule(ctx, 'Workers', `${members.length} · role · liveness · ballot on the picked proposal`)]
+
+ if (members.length === 0) rows.push(text(ctx, 'No workers have joined. A vote needs a registered worker: spawn one below.', { dimColor: true }))
+
+ for (const member of members.slice(0, 12)) {
+ const ballot = picked?.ballots.find(entry => entry.voter === member.id)
+ const vote = picked === null ? '' : picked.byzantine.includes(member.id) ? 'byzantine' : ballot === undefined ? 'not voted' : ballot.isFor ? 'for' : 'against'
+
+ rows.push(
+ row(ctx, [
+ ctx.kit.Text({ ...LIVE_THEME(member.liveness), children: ` ${glyphOf(member)} ` }),
+ ctx.kit.Text({ wrap: 'truncate-end', children: clip(`${shortId(member.id).padEnd(7)} ${member.role.padEnd(11)} ${member.status.padEnd(15)} ${vote.padEnd(10)} ${member.id}`, ctx.columns - 4) }),
+ ]),
+ )
+ }
+
+ if (members.length > 12) rows.push(text(ctx, `+${members.length - 12} more workers`, { dimColor: true }))
+
+ return rows
+}
+
+function proposalsSection(ctx: Ctx, hive: HiveInfo): RenderElement[] {
+ const picked = pickedProposal(hive, ctx.state.select.item)
+ const rows: RenderElement[] = [rule(ctx, 'Proposals', hive.pending.length === 0 ? 'none open' : `${hive.pending.length} open · j/k pick`)]
+
+ if (hive.pending.length === 0) rows.push(text(ctx, 'No open proposals. Propose one below.', { dimColor: true }))
+
+ for (const proposal of hive.pending.slice(0, 8)) {
+ const tally = tallyOf(hive, proposal, ctx.nowMs)
+ const isPicked = proposal.id === picked?.id
+ const deadline = proposal.timeoutAtMs === undefined ? '' : tally.isTimedOut ? ' · timed out: re-propose in the next term' : ` · times out in ${Math.ceil((proposal.timeoutAtMs - ctx.nowMs) / 1000)}s`
+
+ rows.push(
+ text(ctx, `${isPicked ? '▸' : ' '}◇ ${proposal.type} (${noteOf(tally)}) ${proposal.status} · for ${proposal.votesFor} · against ${proposal.votesAgainst} · [${bar(tally)}] need ${tally.required} of ${tally.nodes}`, isPicked ? { bold: true, color: THEME.warn } : { color: THEME.warn }),
+ )
+
+ if (!isPicked) continue
+
+ const voters = (isFor: boolean) => proposal.ballots.filter(ballot => ballot.isFor === isFor).map(ballot => shortId(ballot.voter)).join(', ') || '—'
+
+ rows.push(text(ctx, ` "${proposal.value ?? 'n/a'}" · by ${proposal.proposedBy ?? 'n/a'} · ${ago(proposal.proposedAtMs, ctx.nowMs)}${deadline}`, { dimColor: true }))
+ rows.push(text(ctx, ` for: ${voters(true)} · against: ${voters(false)}${proposal.byzantine.length > 0 ? ` · byzantine (excluded): ${proposal.byzantine.map(shortId).join(', ')}` : ''} · ${proposal.id}`, { dimColor: true }))
+ }
+
+ if (picked !== null && ctx.columns >= 44) {
+ const voter = nextVoter(hive, picked)
+
+ rows.push(
+ row(ctx, [
+ ...(hive.pending.length > 1 ? [button(ctx, 'item-prev', 'prev', () => ctx.act.select(-1), { hotkey: 'k' }), button(ctx, 'item-next', 'next', () => ctx.act.select(1), { hotkey: 'j' })] : []),
+ ...(voter === null ? [] : [button(ctx, 'hive-vote-yes', 'Vote for', () => void ctx.act.run('hive-vote-yes'), { hotkey: 'f' }), button(ctx, 'hive-vote-no', 'Vote against', () => void ctx.act.run('hive-vote-no'), { hotkey: 'a' })]),
+ ]),
+ )
+ rows.push(text(ctx, voter === null ? `vote: n/a — ${hive.workers.length === 0 ? 'no registered worker to vote as (the CLI counts only workers): spawn one' : 'every worker has voted on it'}` : `a vote is cast as the next worker that has not voted: ${voter}`, { dimColor: true }))
+ }
+
+ return rows
+}
+
+function historySection(ctx: Ctx, hive: HiveInfo): RenderElement[] {
+ const rows: RenderElement[] = [rule(ctx, 'Decided', `${hive.history.length} on record`)]
+
+ if (hive.history.length === 0) rows.push(text(ctx, 'Nothing decided yet.', { dimColor: true }))
+
+ for (const decision of hive.history.slice(-6).reverse()) {
+ const isApproved = decision.result === 'approved'
+
+ rows.push(
+ text(
+ ctx,
+ `${isApproved ? '◆' : '◇'} ${decision.type} → ${decision.result} · for ${decision.votesFor} · against ${decision.votesAgainst}${decision.strategy !== undefined ? ` · ${decision.strategy}${decision.term !== undefined ? ` T${decision.term}` : ''}` : ''}${decision.byzantine > 0 ? ` · ${decision.byzantine} byzantine` : ''} · ${ago(decision.decidedAtMs, ctx.nowMs)}`,
+ { color: isApproved ? THEME.ok : THEME.bad },
+ ),
+ )
+ }
+
+ return rows
+}
+
+function broadcastSection(ctx: Ctx, hive: HiveInfo): RenderElement[] {
+ const rows: RenderElement[] = [rule(ctx, 'Broadcasts', `${hive.broadcasts.length} kept · shared memory`)]
+
+ if (hive.broadcasts.length === 0) rows.push(text(ctx, 'No broadcasts yet.', { dimColor: true }))
+
+ for (const message of hive.broadcasts.slice(-5).reverse()) {
+ rows.push(text(ctx, `${ago(message.atMs, ctx.nowMs).padStart(8)} [${message.priority}] ${message.from}: ${message.message}`, message.priority === 'high' || message.priority === 'critical' ? { color: THEME.warn } : {}))
+ }
+
+ const keys = hive.memoryKeys.filter(key => key !== 'broadcasts')
+
+ if (keys.length > 0) rows.push(text(ctx, `memory keys: ${keys.slice(0, 12).join(', ')}${keys.length > 12 ? ` +${keys.length - 12}` : ''}`, { dimColor: true }))
+
+ return rows
+}
+
+function actSection(ctx: Ctx, hive: HiveInfo): RenderElement[] {
+ const block = proposeBlock(hive)
+ const rows: RenderElement[] = [rule(ctx, 'Act', 'each asks y/n, then runs one ruflo command')]
+ const Input = ctx.kit.Input
+
+ if (Input === undefined) {
+ rows.push(text(ctx, 'propose and broadcast from the palette: p → "propose design: use raft", "broadcast hello"', { dimColor: true }))
+ } else {
+ rows.push(Input({ key: 'hive-propose', label: 'propose', placeholder: block ?? 'type: the decision (design: use raft for the console)', submitLabel: 'ask', onSubmit: value => void ctx.act.run('propose', value) }))
+ rows.push(Input({ key: 'hive-broadcast', label: 'broadcast', placeholder: 'a message for every worker', submitLabel: 'ask', onSubmit: value => void ctx.act.run('broadcast', value) }))
+ }
+
+ if (block !== null) rows.push(text(ctx, `propose: n/a — ${block}`, { color: THEME.warn }))
+
+ if (ctx.columns >= 44) {
+ rows.push(row(ctx, [button(ctx, 'hive-spawn-worker', 'Spawn worker', () => void ctx.act.run('hive-spawn-worker'), { hotkey: 's' }), button(ctx, 'hive-spawn-specialist', 'specialist', () => void ctx.act.run('hive-spawn-specialist')), button(ctx, 'hive-spawn-scout', 'scout', () => void ctx.act.run('hive-spawn-scout'))]))
+ }
+
+ return rows
+}
+
+export function hiveView(ctx: Ctx): RenderElement {
+ const snap = ctx.state.snapshot
+ const hive = snap?.hive ?? null
+
+ if (snap === null) return text(ctx, 'reading ruflo state…', { dimColor: true })
+
+ if (hive === null) {
+ return col(ctx, [rule(ctx, 'Hive-Mind', 'not initialised'), text(ctx, 'No hive-mind here. `npx ruflo hive-mind init --consensus raft` starts one with a queen; spawn workers to vote.', { dimColor: true })], 'hive')
+ }
+
+ const members = membersOf(hive, snap.hiveAgents, snap.agents)
+
+ return col(
+ ctx,
+ [
+ rule(ctx, 'Hive-Mind', `${hive.topology} · ${hive.strategy ?? 'consensus n/a'}`),
+ ...summary(ctx, hive, members),
+ picture(ctx, 'hive', `honeycomb needs a terminal: the queen and ${members.length} workers`),
+ text(ctx, '♛ queen · ● worker ◆ specialist ▲ scout ○ in no store · yellow busy, cyan idle, grey down · walls: green for, pink against, yellow byzantine · a cell flashes 2 s when its vote lands', { dimColor: true }),
+ ...proposalsSection(ctx, hive),
+ ...workersSection(ctx, hive, members),
+ ...historySection(ctx, hive),
+ ...broadcastSection(ctx, hive),
+ ...actSection(ctx, hive),
+ ],
+ 'hive',
+ )
+}
diff --git a/plugins/ruflo-console/hooks/views/menu.ts b/plugins/ruflo-console/hooks/views/menu.ts
index a277468150..a2a963021f 100644
--- a/plugins/ruflo-console/hooks/views/menu.ts
+++ b/plugins/ruflo-console/hooks/views/menu.ts
@@ -13,6 +13,8 @@ const MENUS: readonly { title: string; items: readonly Item[] }[] = [
items: [
{ key: '1', label: 'Overview', go: 'overview' },
{ key: '2', label: 'Swarm Topology', go: 'swarm' },
+ // No hotkey is free; the prompt takes its name (hive) and the entry is clickable.
+ { key: '👑', label: 'Hive-Mind', go: 'hive' },
{ key: '3', label: 'Claims Board', go: 'claims' },
{ key: 'q', label: 'Approvals', go: 'approvals' },
{ key: 'm', label: 'Missions', go: 'missions' },
diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts
index c6f33fdf4e..289d6e88fb 100644
--- a/plugins/ruflo-console/hooks/views/pane.ts
+++ b/plugins/ruflo-console/hooks/views/pane.ts
@@ -12,6 +12,7 @@ import { claimsView } from './claims'
import { ago, button, clip, col, isBbs, row, setLook, text, THEME, type Ctx } from './common'
import { costView } from './cost'
import { federationView } from './federation'
+import { hiveView } from './hive'
import { learningView } from './learning'
import { approvalsView, eventsView, timelineView } from './manage'
import { memoryView } from './memory'
@@ -33,6 +34,7 @@ const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {
menu: menuView,
overview: overviewView,
swarm: swarmView,
+ hive: hiveView,
claims: claimsView,
federation: federationView,
plugins: pluginsView,
@@ -69,18 +71,22 @@ function tabs(ctx: Ctx): RenderElement {
// A Button cannot be styled, so the current tab is Text: its key is not needed, the view is already open
// (from a drill-down, b goes back).
// BBS: the current tab is framed like a menu pick, [2: 🐝 SWARM]; the name always shows there, in capitals.
- const current = isBbs() ? `[${view.key}: ${view.icon}${withNames || view.label.length <= 6 ? ` ${view.label.toUpperCase()}` : ''}]` : `${view.key}: ${words}`
+ // A view with no hotkey (key '') shows no key prefix.
+ const prefix = view.key === '' ? '' : `${view.key}: `
+ const current = isBbs() ? `[${prefix}${view.icon}${withNames || view.label.length <= 6 ? ` ${view.label.toUpperCase()}` : ''}]` : `${prefix}${words}`
if (isCurrent) return ctx.kit.Box({ key: `tab-${view.id}`, children: [ctx.kit.Text({ bold: true, color: THEME.head, wrap: 'truncate-end', children: current })] })
- return ctx.kit.Button({ key: `tab-${view.id}`, label: words, hotkey: view.key, plain: true, dimColor: true, onPress: () => ctx.act.view(view.id) })
+ return ctx.kit.Button({ key: `tab-${view.id}`, label: words, ...(view.key !== '' && { hotkey: view.key }), plain: true, dimColor: true, onPress: () => ctx.act.view(view.id) })
}
const line = (views: readonly (typeof VIEWS)[number][], key: string) => ctx.kit.Box({ flexDirection: 'row', gap: 1, key, children: views.map(tab) })
+ // The first row runs to the last digit-keyed view, so a keyless view sits where VIEWS puts it (Hive-Mind after Swarm).
+ const split = VIEWS.reduce((last, view, i) => (/^[0-9]$/.test(view.key) ? i + 1 : last), 0)
return ctx.kit.Box({
flexDirection: 'column',
key: 'tabs',
- children: [line(VIEWS.filter(view => /^[0-9]$/.test(view.key)), 'tabs-views'), line(VIEWS.filter(view => !/^[0-9]$/.test(view.key)), 'tabs-manage')],
+ children: [line(VIEWS.slice(0, split), 'tabs-views'), line(VIEWS.slice(split), 'tabs-manage')],
})
}
diff --git a/plugins/ruflo-console/hooks/views/swarm.ts b/plugins/ruflo-console/hooks/views/swarm.ts
index ddd0f67924..ad320974a0 100644
--- a/plugins/ruflo-console/hooks/views/swarm.ts
+++ b/plugins/ruflo-console/hooks/views/swarm.ts
@@ -60,14 +60,17 @@ export function swarmView(ctx: Ctx): RenderElement {
rows.push(rule(ctx, 'Hive-mind', hive === null ? 'not initialised' : `${hive.strategy ?? 'consensus'}${hive.queen !== undefined ? ` · queen ${hive.queen}` : ''}`))
+ // A short summary: the Hive-Mind view (👑) holds the queen, quorum, proposals, voting and broadcasts.
if (hive === null) {
rows.push(text(ctx, 'n/a — `npx ruflo hive-mind init` for queen-led consensus', { dimColor: true }))
} else {
- for (const proposal of hive.pending.slice(-3)) rows.push(text(ctx, `◇ ${proposal.type} (${proposal.strategy}) ${proposal.status} · for ${proposal.votesFor} · against ${proposal.votesAgainst} · ${proposal.id}`, { color: THEME.warn }))
- for (const decision of hive.history.slice(-2)) rows.push(text(ctx, `◆ ${decision.type} → ${decision.result} · for ${decision.votesFor} · against ${decision.votesAgainst}`, { dimColor: true }))
- if (hive.pending.length === 0 && hive.history.length === 0) rows.push(text(ctx, 'no proposals yet', { dimColor: true }))
- if (hive.pending.length > 0) rows.push(text(ctx, 'vote from Approvals (q) or the palette (p → vote)', { dimColor: true }))
+ const newest = hive.pending.at(-1)
+
+ rows.push(text(ctx, `${hive.workers.length} workers · ${hive.pending.length} open · ${hive.history.length} decided · ${hive.broadcasts.length} broadcasts`, { dimColor: true }))
+ if (newest !== undefined) rows.push(text(ctx, `◇ ${newest.type} (${newest.strategy}) ${newest.status} · for ${newest.votesFor} · against ${newest.votesAgainst} · ${newest.id}`, { color: THEME.warn }))
}
+ if (ctx.columns >= 44) rows.push(row(ctx, [button(ctx, 'open-hive', '▸ open hive', () => ctx.act.view('hive'))]))
+
return col(ctx, rows, 'swarm')
}
diff --git a/plugins/ruflo-console/tests/behaviour.test.ts b/plugins/ruflo-console/tests/behaviour.test.ts
index 1dc294cd03..8939dd7de6 100644
--- a/plugins/ruflo-console/tests/behaviour.test.ts
+++ b/plugins/ruflo-console/tests/behaviour.test.ts
@@ -149,7 +149,7 @@ describe('behaviour', () => {
expect(elementsOf(tree, 'Raster').length === 0).toBe(isNarrow)
expect(elementsOf(tree, 'Button').map(keyOf).includes('claim')).toBe(!isNarrow)
- if (isNarrow) expect(textOf(tree)).toContain('4/16 Claims')
+ if (isNarrow) expect(textOf(tree)).toContain('5/17 Claims')
await pane.unmount()
}
})
diff --git a/plugins/ruflo-console/tests/fixtures/hive.ts b/plugins/ruflo-console/tests/fixtures/hive.ts
new file mode 100644
index 0000000000..3ce46d0efc
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/hive.ts
@@ -0,0 +1,49 @@
+/**
+ * A hive in the shapes hive-mind-tools.ts writes: three workers (two spawned into agents.json, one in no store), a raft
+ * proposal with one ballot, a bft proposal with a Byzantine voter, two decisions and two broadcasts. The capability
+ * token is the captured run's, so a test can assert it never reaches the screen.
+ */
+import { HIVE_TOKEN, RUFLO_FILES } from './ruflo-run'
+
+export const WORKERS = ['hive-worker-1790903400000-a1b2', 'hive-worker-1790903400001-c3d4', 'hive-worker-1790903400002-e5f6'] as const
+export const RAFT_ID = 'proposal-1790903500000-raft01'
+export const BFT_ID = 'proposal-1790903500001-bft002'
+
+export const HIVE_STATE = {
+ initialized: true,
+ topology: 'hierarchical',
+ consensusStrategy: 'raft',
+ queen: { agentId: 'queen-1790903321632', electedAt: '2026-10-02T01:08:41.632Z', term: 2 },
+ hiveToken: HIVE_TOKEN,
+ workers: [...WORKERS],
+ consensus: {
+ pending: [
+ { proposalId: RAFT_ID, type: 'design', value: 'use raft for the console', proposedBy: 'console-operator', proposedAt: '2026-10-02T01:10:00.000Z', votes: { [WORKERS[0]]: true }, status: 'pending', strategy: 'raft', term: 2, timeoutAt: '2026-10-02T01:10:30.000Z' },
+ { proposalId: BFT_ID, type: 'deploy', value: { target: 'staging' }, proposedBy: 'system', proposedAt: '2026-10-02T01:11:00.000Z', votes: { [WORKERS[1]]: false }, status: 'pending', strategy: 'bft', byzantineVoters: [WORKERS[2]] },
+ ],
+ history: [
+ { proposalId: 'proposal-1790903000000-old001', type: 'naming', result: 'approved', votes: { for: 2, against: 0 }, decidedAt: '2026-10-02T01:05:00.000Z', strategy: 'raft', term: 1 },
+ { proposalId: 'proposal-1790903000001-old002', type: 'budget', result: 'rejected', votes: { for: 1, against: 2 }, decidedAt: '2026-10-02T01:06:00.000Z', strategy: 'bft', byzantineDetected: [WORKERS[2]] },
+ ],
+ },
+ sharedMemory: {
+ broadcasts: [
+ { messageId: 'msg-1790903600000-aaaa01', message: 'standup in 5', priority: 'normal', fromId: 'console-operator', timestamp: '2026-10-02T01:12:00.000Z' },
+ { messageId: 'msg-1790903600001-bbbb02', message: 'freeze the main branch', priority: 'high', fromId: 'system', timestamp: '2026-10-02T01:13:00.000Z' },
+ ],
+ 'design-notes': { a: 1 },
+ },
+ createdAt: '2026-10-02T01:08:41.632Z',
+ updatedAt: '2026-10-02T01:13:00.000Z',
+}
+
+const spawned = (agentId: string, role: string, status: string) => ({ agentId, agentType: 'worker', status, health: 1, taskCount: 0, config: { role, hiveRole: role }, createdAt: '2026-10-02T01:09:00.000Z', domain: 'hive-mind' })
+
+export const HIVE_AGENTS = { agents: { [WORKERS[0]]: spawned(WORKERS[0], 'worker', 'busy'), [WORKERS[1]]: spawned(WORKERS[1], 'specialist', 'idle') } }
+
+/** The captured project with this hive in place of its own, and agents.json beside it. */
+export const HIVE_FILES: Readonly<Record<string, string>> = {
+ ...RUFLO_FILES,
+ '.claude-flow/hive-mind/state.json': JSON.stringify(HIVE_STATE, null, 2),
+ '.claude-flow/agents.json': JSON.stringify(HIVE_AGENTS, null, 2),
+}
diff --git a/plugins/ruflo-console/tests/hive.spec.ts b/plugins/ruflo-console/tests/hive.spec.ts
new file mode 100644
index 0000000000..ad048b84b7
--- /dev/null
+++ b/plugins/ruflo-console/tests/hive.spec.ts
@@ -0,0 +1,161 @@
+/**
+ * The Hive-Mind's pure parts: the hive file read with every field the CLI writes (and never its token), the CLI's quorum
+ * arithmetic, the actions' argv, the vote events, and the honeycomb's layout, size and stillness. Pure: run with
+ * `npx vitest run plugins/ruflo-console/tests/hive.spec.ts`.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { diffEvents } from '../hooks/data/events'
+import { faultTolerance, membersOf, nextVoter, pickedProposal, proposalStrategyOf, proposeBlock, requiredVotes, tallyOf } from '../hooks/data/hive'
+import { parseAgents, parseHive, parseHiveAgents, type HiveInfo } from '../hooks/data/parse'
+import type { Snapshot } from '../hooks/data/snapshot'
+import { cellOrigin, cellsIn, hivePicture, hiveRows, ringsFor, spiral, type HivePictureModel } from '../hooks/gfx/hive'
+import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote, proposalText } from '../hooks/hive'
+import { BFT_ID, HIVE_AGENTS, HIVE_STATE, RAFT_ID, WORKERS } from './fixtures/hive'
+import { HIVE_TOKEN } from './fixtures/ruflo-run'
+
+const hive = parseHive(JSON.stringify(HIVE_STATE)) as HiveInfo
+const NOW = Date.parse('2026-10-02T01:10:10.000Z')
+const withHive = (next: HiveInfo | null) => ({ hive: next, agents: [], claims: [], tasks: [], swarm: null, neural: null, outcomes: null, federationNodes: null, missions: null, hasNostrKey: null }) as unknown as Snapshot
+const cellModel = (members: number, pulseAtMs?: number): HivePictureModel => ({
+ queen: { id: 'q', glyph: '♛', tag: 'T1', color: 0xd700d7 },
+ members: Array.from({ length: members }, (_, i) => ({ id: `w${i}`, glyph: '●', tag: `w${i}`, color: 0x00afd7, ...(i === 0 && pulseAtMs !== undefined && { pulseAtMs }) })),
+ meters: [{ label: 'design', votesFor: 1, votesAgainst: 0, required: 2, nodes: 3, note: 'raft T2', isPicked: true }],
+})
+
+describe('the hive file', () => {
+ it('reads the queen, term, strategy, ballots, raft and bft fields, history, broadcasts and memory keys', () => {
+ expect(hive).toMatchObject({ topology: 'hierarchical', strategy: 'raft', queen: 'queen-1790903321632', queenTerm: 2, workers: [...WORKERS] })
+ expect(hive.pending[0]).toMatchObject({ id: RAFT_ID, type: 'design', strategy: 'raft', term: 2, value: 'use raft for the console', proposedBy: 'console-operator', votesFor: 1, votesAgainst: 0, ballots: [{ voter: WORKERS[0], isFor: true }] })
+ expect(hive.pending[0]?.timeoutAtMs).toBe(Date.parse('2026-10-02T01:10:30.000Z'))
+ expect(hive.pending[1]).toMatchObject({ id: BFT_ID, strategy: 'bft', value: '{"target":"staging"}', byzantine: [WORKERS[2]], votesAgainst: 1 })
+ expect(hive.history.map(entry => [entry.type, entry.result, entry.strategy, entry.byzantine])).toEqual([['naming', 'approved', 'raft', 0], ['budget', 'rejected', 'bft', 1]])
+ expect(hive.broadcasts.map(entry => [entry.priority, entry.from, entry.message])).toEqual([['normal', 'console-operator', 'standup in 5'], ['high', 'system', 'freeze the main branch']])
+ expect(hive.memoryKeys).toEqual(['broadcasts', 'design-notes'])
+ expect(JSON.stringify(hive)).not.toContain(HIVE_TOKEN)
+ })
+
+ it('keeps each spawned worker\'s hive role, and says which hive workers no store knows', () => {
+ const spawned = parseHiveAgents(JSON.stringify(HIVE_AGENTS))
+ const members = membersOf(hive, spawned, parseAgents(null))
+
+ expect(spawned.map(agent => agent.role)).toEqual(['worker', 'specialist'])
+ expect(members.map(member => [member.role, member.liveness, member.isKnown])).toEqual([['worker', 'busy', true], ['specialist', 'idle', true], ['n/a', 'unknown', false]])
+ })
+})
+
+describe('quorum, as the CLI counts it', () => {
+ it('requires the votes calculateRequiredVotes does', () => {
+ expect(requiredVotes('bft', 4)).toBe(3)
+ expect(requiredVotes('raft', 4)).toBe(3)
+ expect(requiredVotes('raft', 3)).toBe(2)
+ expect(requiredVotes('quorum', 4, 'unanimous')).toBe(4)
+ expect(requiredVotes('quorum', 6, 'supermajority')).toBe(5)
+ expect(requiredVotes('raft', 0)).toBe(1)
+ })
+
+ it('states fault tolerance only where the strategy has a bound', () => {
+ expect(faultTolerance('byzantine', 4)).toEqual({ faulty: 1, of: 4, rule: 'byzantine f < n/3' })
+ expect(faultTolerance('raft', 5)).toEqual({ faulty: 2, of: 5, rule: 'raft f < n/2' })
+ expect(faultTolerance('gossip', 5)).toBeNull()
+ expect(faultTolerance('raft', 0)).toBeNull()
+ expect([proposalStrategyOf('byzantine'), proposalStrategyOf('quorum'), proposalStrategyOf('crdt')]).toEqual(['bft', 'quorum', null])
+ })
+
+ it('tallies a proposal against its bar, and sees a raft timeout', () => {
+ const tally = tallyOf(hive, hive.pending[0] as HiveInfo['pending'][number], NOW)
+
+ expect([tally.required, tally.nodes, tally.isTimedOut, tally.isDeadlocked]).toEqual([2, 3, false, false])
+ expect(tallyOf(hive, hive.pending[0] as HiveInfo['pending'][number], NOW + 60_000).isTimedOut).toBe(true)
+ expect(pickedProposal(hive, -1)?.id).toBe(BFT_ID)
+ })
+})
+
+describe('hive actions', () => {
+ it('votes as the next worker without a ballot, through the subcommand that carries the token', () => {
+ const proposal = hive.pending[0] as HiveInfo['pending'][number]
+
+ expect(nextVoter(hive, proposal)).toBe(WORKERS[1])
+ expect(hiveVote(hive, proposal, false)?.args).toEqual(['hive-mind', 'consensus', '--action', 'vote', '--proposal-id', RAFT_ID, '--vote', 'no', '--voter-id', WORKERS[1]])
+ expect(hiveVote({ ...hive, workers: [] }, proposal, true)).toBeNull()
+ })
+
+ it('refuses a second raft proposal in the same term before asking', () => {
+ expect(proposeBlock(hive)).toMatch(/^raft term 2 already has design/)
+ expect(hivePropose(hive, 'design: anything')).toBeNull()
+
+ const open = { ...hive, pending: hive.pending.filter(entry => entry.strategy !== 'raft') }
+
+ expect(hivePropose(open, 'review: ship it')?.args).toEqual(['mcp', 'exec', '-t', 'hive-mind_consensus', '-p', JSON.stringify({ action: 'propose', type: 'review', value: 'ship it', voterId: 'console-operator', strategy: 'raft' })])
+ expect(proposalText('no prefix here')).toEqual({ type: 'general', value: 'no prefix here' })
+ expect(hivePropose(open, '--flag')).toBeNull()
+ })
+
+ it('broadcasts and spawns with fixed argv, and only roles the CLI accepts', () => {
+ expect(hiveBroadcast('hello hive')?.args).toEqual(['mcp', 'exec', '-t', 'hive-mind_broadcast', '-p', JSON.stringify({ message: 'hello hive', priority: 'normal', fromId: 'console-operator' })])
+ expect(hiveSpawn(hive, 'scout')?.args).toEqual(['mcp', 'exec', '-t', 'hive-mind_spawn', '-p', JSON.stringify({ role: 'scout', agentType: 'worker', prefix: 'hive-worker' })])
+ expect(hiveSpawn(hive, 'queen')).toBeNull()
+ })
+})
+
+describe('hive events', () => {
+ it('emits one event per new ballot and per join, tagged with that worker', () => {
+ const before = { ...hive, workers: WORKERS.slice(0, 2), pending: hive.pending.map(entry => ({ ...entry, ballots: [], votesFor: 0, votesAgainst: 0 })) }
+ const events = diffEvents(withHive(before), withHive(hive), 5)
+
+ expect(events.map(event => [event.agentId, event.text])).toEqual(
+ expect.arrayContaining([
+ [WORKERS[0], `${WORKERS[0]} voted for design (${RAFT_ID})`],
+ [WORKERS[1], `${WORKERS[1]} voted against deploy (${BFT_ID})`],
+ [WORKERS[2], `${WORKERS[2]} joined the hive`],
+ ]),
+ )
+ })
+})
+
+describe('the honeycomb', () => {
+ it('walks the rings centre first, and no two cells share an interior', () => {
+ const rings = 3
+ const slots = spiral(rings)
+ const interiors = new Set<string>()
+
+ expect(slots).toHaveLength(cellsIn(rings))
+ expect(slots[0]).toEqual([0, 0])
+
+ for (const [q, r] of slots) {
+ const { x, y } = cellOrigin(q, r, rings, 100)
+
+ for (let dx = 1; dx <= 4; dx++) {
+ const key = `${x + dx},${y + 1}`
+
+ expect(interiors.has(key)).toBe(false)
+ interiors.add(key)
+ }
+
+ expect(x).toBeGreaterThanOrEqual(0)
+ expect(y).toBeGreaterThanOrEqual(0)
+ }
+ })
+
+ it('puts the queen in the centre and grows rings only as wide as the columns allow', () => {
+ const grid = hivePicture(cellModel(6), 80, 0)
+ const { x, y } = cellOrigin(0, 0, ringsFor(6, 80), 80)
+
+ expect(String.fromCodePoint(grid.glyph(x + 1, y + 1))).toBe('♛')
+ expect([ringsFor(0, 80), ringsFor(6, 80), ringsFor(7, 80), ringsFor(60, 80), ringsFor(60, 30)]).toEqual([0, 1, 2, 4, 2])
+ expect(grid.rows).toBe(hiveRows(cellModel(6), 80))
+ })
+
+ it('is still with no fresh event, and blinks for two seconds after one, at one size', () => {
+ const still = cellModel(8)
+
+ expect(hivePicture(still, 90, 1_000).encode()).toBe(hivePicture(still, 90, 987_654).encode())
+
+ const pulsed = cellModel(8, 10_000)
+ const sizes = new Set([0, 10_100, 10_300, 11_900, 12_100].map(t => `${hivePicture(pulsed, 90, t).columns}x${hivePicture(pulsed, 90, t).rows}`))
+
+ expect(sizes.size).toBe(1)
+ expect(hivePicture(pulsed, 90, 10_100).encode()).not.toBe(hivePicture(still, 90, 10_100).encode())
+ expect(hivePicture(pulsed, 90, 12_100).encode()).toBe(hivePicture(still, 90, 12_100).encode())
+ })
+})
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index baa060ff2b..7016ef6a10 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -1,6 +1,7 @@
import type { TestBody } from 'claude-code/testing'
import { describe, expect, mock, test } from 'claude-code/testing'
+import { HIVE_FILES, RAFT_ID, WORKERS } from './fixtures/hive'
import { MISSION_OBSERVATION } from './fixtures/missions'
import { HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'
import { command, elementsOf, fakeRuflo, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'
@@ -66,7 +67,56 @@ describe('views', () => {
expect(text).toMatch(/· #[a-z0-9]{4,6}/)
expect(text).toContain('design (raft) pending · for 0 · against 0')
expect(text).not.toContain(HIVE_TOKEN)
- expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['agent-next', 'agent-prev', 'drill', 'palette', 'actions']))
+ expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['agent-next', 'agent-prev', 'drill', 'palette', 'actions', 'open-hive']))
+ // The Hive-Mind tab has no hotkey: every digit and letter is taken.
+ const tabProps = (key: string) => (elementsOf(tree, 'Button').find(button => keyOf(button) === key) as { props?: Record<string, unknown> } | undefined)?.props
+
+ expect(tabProps('tab-claims')?.hotkey).toBe('3')
+ expect(tabProps('tab-hive')).toBeDefined()
+ expect(tabProps('tab-hive')?.hotkey).toBeUndefined()
+ })
+
+ test('hive: the honeycomb, quorum and fault tolerance, proposals, workers, decisions, broadcasts, no token', { options: { boot: false } }, async ($, on) => {
+ worldOf(on, HIVE_FILES)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const { text, rasters, tree } = await drawn($, 'hive')
+
+ expect(rasters).toEqual(['header', 'title', 'hive'])
+ expect(text).toContain('queen-1790903321632 · term 2')
+ expect(text).toContain('raft · proposals vote raft')
+ expect(text).toContain('tolerates 1 faulty of 3 (raft f < n/2)')
+ expect(text).toContain('2 of 3 votes to pass (majority)')
+ expect(text).toContain('3 · 1 busy · 1 idle · 0 down · 1 in no agent store')
+ expect(text).toContain('▸◇ design (raft T2 · timed out) pending · for 1 · against 0')
+ expect(text).toContain('need 2 of 3')
+ expect(text).toContain(`a vote is cast as the next worker that has not voted: ${WORKERS[1]}`)
+ expect(text).toContain('budget → rejected · for 1 · against 2 · bft · 1 byzantine')
+ expect(text).toContain('[high] system: freeze the main branch')
+ expect(text).toContain('propose: n/a — raft term 2 already has design')
+ expect(text).not.toContain(HIVE_TOKEN)
+ expect(elementsOf(tree, 'Input').map(keyOf)).toEqual(['hive-propose', 'hive-broadcast'])
+ expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['hive-vote-yes', 'hive-vote-no', 'hive-spawn-worker']))
+ })
+
+ test('hive: a vote asks before it runs, then runs one fixed argv as the next worker on yes', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, HIVE_FILES)
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await $.command.run(command('hive'))
+
+ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })
+ const votes = () => world.runs.filter(argv => argv.includes('consensus'))
+
+ await pane.press({ key: 'hive-vote-yes' })
+ expect(textOf(await pane.drawn())).toContain(`Confirm: vote for design (${RAFT_ID}) as worker ${WORKERS[1]}?`)
+ expect(votes()).toHaveLength(0)
+
+ await pane.press({ key: 'confirm' })
+ expect(votes()).toHaveLength(1)
+ expect(votes()[0]?.slice(4)).toEqual(['hive-mind', 'consensus', '--action', 'vote', '--proposal-id', RAFT_ID, '--vote', 'yes', '--voter-id', WORKERS[1]])
+ await pane.unmount()
})
test('claims: the flow diagram with lanes and rings, the board, and the act row', { options: { boot: false } }, async ($, on) => {