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): the Hive-Mind as a living comb

ruv025ddc06ac96
diff --git a/plugins/ruflo-console/hooks/data/hive.ts b/plugins/ruflo-console/hooks/data/hive.ts
index d97642a02e..6b43b91d94 100644
--- a/plugins/ruflo-console/hooks/data/hive.ts
+++ b/plugins/ruflo-console/hooks/data/hive.ts
@@ -4,6 +4,7 @@
* 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 { ConsoleEvent } from './events'
import type { AgentRecord, HiveAgentRecord, HiveInfo, Proposal } from './parse'
/** The roles `hive-mind spawn --role` accepts. */
@@ -90,6 +91,54 @@ export function proposeBlock(hive: HiveInfo): string | null {
return holder === undefined ? null : `raft term ${term} already has ${holder.type} (${holder.id}) open: decide it first`
}
+/** What the console last saw a hive member do, and when, while it is fresh: a vote either way, a join or a leave. */
+export type HiveWave = { kind: 'for' | 'against' | 'join' | 'leave'; atMs: number }
+
+/**
+ * The newest fresh event about `id`, read from the words `diffEvents` writes ("<id> voted for …", "<id> joined the
+ * hive"); null when there is none within HIVE_PULSE_MS of `nowMs`. The honeycomb runs a wave from that cell.
+ */
+export function waveOf(events: readonly ConsoleEvent[], id: string, nowMs: number): HiveWave | null {
+ for (let i = events.length - 1; i >= 0; i--) {
+ const event = events[i] as ConsoleEvent
+
+ if (nowMs - event.atMs >= HIVE_PULSE_MS) break
+ if (event.agentId !== id || event.atMs > nowMs) continue
+
+ const words = event.text.startsWith(`${id} `) ? event.text.slice(id.length + 1) : ''
+ const kind = words.startsWith('voted for ') ? 'for' : words.startsWith('voted against ') ? 'against' : words === 'joined the hive' ? 'join' : words === 'left the hive' ? 'leave' : null
+
+ if (kind !== null) return { kind, atMs: event.atMs }
+ }
+
+ return null
+}
+
+/**
+ * When the console first saw each broadcast, so the ticker slides a new one in once. Everything present at the first
+ * read counts as old (arrived at 0), so opening the view never animates what was already there.
+ */
+export class Arrivals {
+ private readonly seen = new Map<string, number>()
+ private hive: string | null = null
+
+ arrivedAt(hiveId: string, ids: readonly string[], nowMs: number): Map<string, number> {
+ const isFirst = this.hive !== hiveId
+
+ if (isFirst) {
+ this.hive = hiveId
+ this.seen.clear()
+ }
+
+ for (const id of ids) if (!this.seen.has(id)) this.seen.set(id, isFirst ? 0 : nowMs)
+
+ // Forget what the hive no longer keeps (it holds the last 100), so the map stays the hive's size.
+ if (this.seen.size > ids.length * 2 + 16) for (const id of [...this.seen.keys()]) if (!ids.includes(id)) this.seen.delete(id)
+
+ return this.seen
+ }
+}
+
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. */
diff --git a/plugins/ruflo-console/hooks/gfx/hive-chamber.ts b/plugins/ruflo-console/hooks/gfx/hive-chamber.ts
new file mode 100644
index 0000000000..c6825d526b
--- /dev/null
+++ b/plugins/ruflo-console/hooks/gfx/hive-chamber.ts
@@ -0,0 +1,99 @@
+/**
+ * Voting chambers: each open proposal as a hex-ended meter, four rows tall. Votes for fill from the left, votes against
+ * from the right, toward their quorum lines (green ┃ where "for" passes, pink ┃ where "against" rejects; one yellow ┃
+ * where both fall together). Above the fill, one ballot dot per voter: green for, pink against, a red ✖ for a voter
+ * excluded as Byzantine. A ballot the console has just seen arrive blinks white for HIVE_PULSE_MS; nothing else
+ * moves. The bar's arithmetic is the CLI's: `required` and `nodes` come from `tallyOf`.
+ */
+import { Grid } from './raster'
+import { addLight, HIVE_COLOR, waveAge } from './hive'
+
+export type ChamberBallot = { tag: string; isFor: boolean; atMs?: number }
+
+export type Chamber = {
+ label: string
+ note: string
+ votesFor: number
+ votesAgainst: number
+ required: number
+ nodes: number
+ ballots: ChamberBallot[]
+ byzantine: string[]
+ isPicked: boolean
+}
+
+export const CHAMBER_ROWS = 4
+export const MAX_CHAMBERS = 4
+
+export const chamberRows = (chambers: number): number => Math.min(MAX_CHAMBERS, chambers) * CHAMBER_ROWS
+
+/** The bar's width in cells: what the columns leave beside the words, between 8 and 48. */
+export const barWidth = (columns: number): number => Math.max(8, Math.min(48, columns - 44))
+
+/** Where the fills and the quorum lines fall on a bar `width` cells wide: proportional to the hive's nodes. */
+export function chamberLayout(chamber: Pick<Chamber, 'votesFor' | 'votesAgainst' | 'required' | 'nodes'>, width: number): { forCells: number; againstCells: number; passAt: number; rejectAt: number } {
+ const of = (votes: number) => Math.round((Math.min(votes, chamber.nodes) / Math.max(1, chamber.nodes)) * width)
+ const forCells = of(chamber.votesFor)
+
+ return { forCells, againstCells: Math.min(width - forCells, of(chamber.votesAgainst)), passAt: Math.min(width - 1, Math.max(0, of(chamber.required) - 1)), rejectAt: Math.max(0, Math.min(width - 1, width - of(chamber.required))) }
+}
+
+function drawChamber(grid: Grid, chamber: Chamber, y: number, columns: number, t: number): void {
+ const width = barWidth(columns)
+ const { forCells, againstCells, passAt, rejectAt } = chamberLayout(chamber, width)
+ const wall = chamber.isPicked ? HIVE_COLOR.yellow : HIVE_COLOR.wall
+ const x0 = 1
+
+ // The hex: slanted ends, a lid and a floor.
+ grid.text(x0 + 1, y, `╱${'▔'.repeat(width + 2)}╲`, wall)
+ grid.set(x0, y + 1, '╱', wall)
+ grid.set(x0, y + 2, '╲', wall)
+ grid.set(x0 + width + 5, y + 1, '╲', wall)
+ grid.set(x0 + width + 5, y + 2, '╱', wall)
+ grid.text(x0 + 1, y + 3, `╲${'▁'.repeat(width + 2)}╱`, wall)
+
+ const bx = x0 + 3
+
+ for (let i = 0; i < width; i++) {
+ const isFor = i < forCells
+ const isAgainst = i >= width - againstCells
+ const color = isFor ? HIVE_COLOR.green : isAgainst ? HIVE_COLOR.pink : HIVE_COLOR.faint
+
+ grid.set(bx + i, y + 2, isFor || isAgainst ? '█' : '░', color)
+ }
+
+ // The quorum lines sit on the fill and are drawn over it, so a bar that has crossed its line still shows it.
+ const both = passAt === rejectAt
+
+ grid.set(bx + passAt, y + 2, '┃', both ? HIVE_COLOR.yellow : addLight(HIVE_COLOR.green, HIVE_COLOR.white, passAt < forCells ? 0.6 : 0))
+ if (!both) grid.set(bx + rejectAt, y + 2, '┃', addLight(HIVE_COLOR.pink, HIVE_COLOR.white, rejectAt >= width - againstCells ? 0.6 : 0))
+
+ // One dot per ballot: "for" from the left, "against" from the right, Byzantine voters beside the against side.
+ const slot = (n: number) => Math.max(1, Math.floor(width / Math.max(1, chamber.nodes))) * n
+ const dot = (x: number, ballot: { atMs?: number }, color: number, ch = '●') => {
+ const age = waveAge(ballot.atMs === undefined ? undefined : { kind: 'for', atMs: ballot.atMs }, t)
+
+ grid.set(x, y + 1, ch, age !== null && Math.floor(age / 250) % 2 === 0 ? HIVE_COLOR.white : color)
+ }
+ const fors = chamber.ballots.filter(ballot => ballot.isFor)
+ const againsts = chamber.ballots.filter(ballot => !ballot.isFor)
+
+ fors.forEach((ballot, i) => dot(bx + Math.min(width - 1, slot(i)), ballot, HIVE_COLOR.green))
+ againsts.forEach((ballot, i) => dot(bx + Math.max(0, width - 1 - slot(i)), ballot, HIVE_COLOR.pink))
+ chamber.byzantine.forEach((_, i) => dot(bx + Math.max(0, width - 1 - slot(againsts.length + i)), {}, HIVE_COLOR.red, '✖'))
+
+ const words = x0 + width + 7
+ const room = Math.max(0, columns - words)
+
+ grid.text(words, y + 1, `${chamber.isPicked ? '▸ ' : ''}${chamber.label.toUpperCase()}`.slice(0, room), chamber.isPicked ? HIVE_COLOR.yellow : HIVE_COLOR.grey)
+ grid.text(words, y + 2, `${chamber.votesFor} for · ${chamber.votesAgainst} against · need ${chamber.required} of ${chamber.nodes}`.slice(0, room), chamber.isPicked ? HIVE_COLOR.cyan : HIVE_COLOR.grey)
+ if (chamber.note !== '') grid.text(words, y + 3, chamber.note.slice(0, room), HIVE_COLOR.wall)
+}
+
+export function chambersPicture(chambers: readonly Chamber[], columns: number, t: number): Grid {
+ const grid = new Grid(columns, Math.max(1, chamberRows(chambers.length)))
+
+ chambers.slice(0, MAX_CHAMBERS).forEach((chamber, i) => drawChamber(grid, chamber, i * CHAMBER_ROWS, columns, t))
+
+ return grid
+}
diff --git a/plugins/ruflo-console/hooks/gfx/hive-egg.ts b/plugins/ruflo-console/hooks/gfx/hive-egg.ts
new file mode 100644
index 0000000000..80585c46eb
--- /dev/null
+++ b/plugins/ruflo-console/hooks/gfx/hive-egg.ts
@@ -0,0 +1,51 @@
+/**
+ * The Hive-Mind's empty state: a dim, empty comb with one glowing egg in its centre cell, where the queen will sit once
+ * a hive is started. It comes in two pictures so the view can put the start buttons between them, inside the comb:
+ * the top holds the egg, the bottom a band of cells that closes the comb under the buttons. Still: nothing moves
+ * before there is a hive.
+ */
+import { Grid } from './raster'
+import { addLight, cellOrigin, drawWalls, fieldOf, fillInterior, HIVE_COLOR } from './hive'
+
+export const EGG_TOP_ROWS = 13
+export const EGG_BOTTOM_ROWS = 7
+const EGG = 0xffffd7
+const NEST = 0x875f00
+
+/** The egg's three rows, two cells wide, sitting in the middle of a cell's interior. */
+export const EGG_GLYPHS = ['▄▄', '██', '▀▀'] as const
+
+export function eggTopPicture(columns: number): Grid {
+ const grid = new Grid(columns, EGG_TOP_ROWS)
+ const field = fieldOf(columns, EGG_TOP_ROWS)
+
+ for (const [q, r] of field) {
+ const { x, y } = cellOrigin(q, r, columns, EGG_TOP_ROWS)
+ const isNeighbour = Math.max(Math.abs(q), Math.abs(r), Math.abs(q + r)) === 1
+
+ // The egg's light reaches the six cells around it: their walls warm to gold.
+ drawWalls(grid, x, y, isNeighbour ? addLight(HIVE_COLOR.faint, HIVE_COLOR.yellow, 0.45) : HIVE_COLOR.faint)
+ }
+
+ const { x, y } = cellOrigin(0, 0, columns, EGG_TOP_ROWS)
+
+ fillInterior(grid, x, y, NEST)
+ drawWalls(grid, x, y, HIVE_COLOR.gold, NEST)
+ EGG_GLYPHS.forEach((glyphs, i) => grid.text(x + 3, y + 1 + i, glyphs, EGG, NEST))
+
+ return grid
+}
+
+/** A band of empty cells, the comb going on under the start buttons: a taller comb cut off at the band's last row. */
+export function eggBottomPicture(columns: number): Grid {
+ const grid = new Grid(columns, EGG_BOTTOM_ROWS)
+ const comb = EGG_BOTTOM_ROWS + 2
+
+ for (const [q, r] of fieldOf(columns, comb)) {
+ const { x, y } = cellOrigin(q, r, columns, comb)
+
+ drawWalls(grid, x, y, HIVE_COLOR.faint)
+ }
+
+ return grid
+}
diff --git a/plugins/ruflo-console/hooks/gfx/hive-strip.ts b/plugins/ruflo-console/hooks/gfx/hive-strip.ts
new file mode 100644
index 0000000000..f2b53f6de7
--- /dev/null
+++ b/plugins/ruflo-console/hooks/gfx/hive-strip.ts
@@ -0,0 +1,162 @@
+/**
+ * The hive's strip under the chambers: on the left a shield showing how many faulty workers the strategy survives (f of
+ * n, one pip per worker, the survivable ones gold; dim and n/a where the CLI states no bound), on the right the term
+ * timeline (the current queen's election, the decisions and openings on record, each where its timestamp falls) over
+ * the pheromone ticker: the shared-memory broadcasts, newest first. A broadcast the console has just seen slides in
+ * from the left for HIVE_PULSE_MS, pushing the older ones along; otherwise the strip is still. Terms are marked only
+ * where the file records them: an earlier term's start is never inferred.
+ */
+import { HIVE_PULSE_MS } from '../data/hive'
+import { Grid } from './raster'
+import { addLight, HIVE_COLOR } from './hive'
+
+export type Shield = { faulty: number; of: number; rule: string } | null
+
+export type Mark = { atMs: number; kind: 'opened' | 'passed' | 'failed'; label: string; term?: number }
+
+export type Pheromone = { id: string; text: string; isLoud: boolean; arrivedAtMs: number }
+
+export type StripModel = {
+ shield: Shield
+ strategy: string
+ startMs: number
+ nowMs: number
+ term?: number
+ electedAtMs?: number
+ marks: Mark[]
+ pheromones: Pheromone[]
+ keys: string[]
+}
+
+export const STRIP_ROWS = 7
+const SHIELD_W = 12
+const MAX_PIPS = 8
+const SHIELD = ['╭──────────╮', '│ │', '│ │', '│ │', '╰╮ ╭╯', ' ╰─╮ ╭─╯', ' ╰────╯'] as const
+const MARK: Record<Mark['kind'], [string, number]> = { opened: ['◇', HIVE_COLOR.yellow], passed: ['✔', HIVE_COLOR.green], failed: ['✘', HIVE_COLOR.pink] }
+
+function drawShield(grid: Grid, shield: Shield, strategy: string): void {
+ const isNa = shield === null
+ const tone = isNa ? HIVE_COLOR.wall : shield.faulty === 0 ? HIVE_COLOR.pink : HIVE_COLOR.cyan
+ const bg = isNa ? undefined : shield.faulty === 0 ? 0x5f0000 : 0x005f5f
+
+ // The walls in the strategy's tone; the face between them lit (cyan when it survives a fault, red when it survives none).
+ SHIELD.forEach((line, y) => {
+ const first = line.search(/\S/)
+ const last = line.trimEnd().length - 1
+
+ ;[...line].forEach((ch, x) => {
+ if (ch !== ' ') grid.set(x, y, ch, tone)
+ else if (x > first && x < last) grid.set(x, y, ' ', HIVE_COLOR.white, bg)
+ })
+ })
+
+ if (shield === null) {
+ grid.text(3, 1, 'f n/a', HIVE_COLOR.grey)
+ grid.text(2, 2, strategy.slice(0, 8), HIVE_COLOR.grey)
+ grid.text(2, 3, 'no bound', HIVE_COLOR.wall)
+
+ return
+ }
+
+ grid.text(2, 1, `f ${shield.faulty}`.padEnd(4), HIVE_COLOR.gold, bg)
+ grid.text(6, 1, `of ${shield.of}`.slice(0, 5), HIVE_COLOR.white, bg)
+ grid.text(2, 2, (shield.rule.split(' ')[1] ?? '').slice(0, 8), addLight(tone, HIVE_COLOR.white, 0.3), bg)
+
+ // One pip per worker, the ones the strategy survives losing in gold.
+ const pips = Math.min(MAX_PIPS, shield.of)
+
+ for (let i = 0; i < pips; i++) grid.set(2 + i, 3, i < shield.faulty ? '◆' : '◇', i < shield.faulty ? HIVE_COLOR.gold : HIVE_COLOR.white, bg)
+ if (shield.of > MAX_PIPS) grid.set(2 + MAX_PIPS, 3, '+', HIVE_COLOR.white, bg)
+ grid.text(3, 4, strategy.slice(0, 6), tone, bg)
+}
+
+/** The column a time falls in on an axis `width` cells wide from `startMs` to `nowMs`. */
+export function axisAt(atMs: number, startMs: number, nowMs: number, width: number): number {
+ const span = Math.max(1, nowMs - startMs)
+
+ return Math.max(0, Math.min(width - 1, Math.round(((atMs - startMs) / span) * (width - 1))))
+}
+
+function drawTimeline(grid: Grid, model: StripModel, x0: number, width: number): void {
+ const at = (ms: number) => x0 + axisAt(ms, model.startMs, model.nowMs, width)
+ const elected = model.electedAtMs === undefined ? null : at(model.electedAtMs)
+
+ grid.text(x0, 0, 'TERMS', HIVE_COLOR.pink)
+
+ // The axis: the current term from its election on in cyan, before it grey (a term the file does not date is unlabelled).
+ for (let i = 0; i < width; i++) grid.set(x0 + i, 2, '━', elected !== null && x0 + i >= elected ? HIVE_COLOR.cyan : HIVE_COLOR.wall)
+
+ for (const term of [...new Set(model.marks.flatMap(mark => (mark.term !== undefined && mark.term !== model.term ? [mark.term] : [])))]) {
+ const first = model.marks.find(mark => mark.term === term)
+
+ if (first !== undefined) grid.text(at(first.atMs), 1, `T${term}`, HIVE_COLOR.grey)
+ }
+
+ if (elected !== null) grid.text(elected, 1, `♛T${model.term ?? '?'}`, HIVE_COLOR.gold)
+
+ for (const mark of model.marks) {
+ const [ch, color] = MARK[mark.kind]
+ const x = at(mark.atMs)
+
+ grid.set(x, 2, ch, color)
+ if (grid.glyph(x, 3) === 0x20) grid.text(x, 3, mark.label.slice(0, 5), addLight(0x000000, color, 0.7))
+ }
+
+ const right = 'now'
+
+ grid.text(x0 + width - right.length, 1, right, HIVE_COLOR.grey)
+}
+
+/** Each pheromone's ticker text, newest first, joined by a hex separator. */
+export const tickerText = (pheromones: readonly Pheromone[]): string => pheromones.map(entry => entry.text).join(' ⬡ ')
+
+/** How far the ticker has slid at `t`: the newest pheromone's whole width while it has just arrived, easing to 0. */
+export function tickerShift(pheromones: readonly Pheromone[], t: number): number {
+ const newest = pheromones[0]
+
+ if (newest === undefined) return 0
+
+ const age = t - newest.arrivedAtMs
+
+ if (age < 0 || age >= HIVE_PULSE_MS) return 0
+
+ const k = 1 - age / HIVE_PULSE_MS
+
+ return Math.round(k * k * (newest.text.length + 5))
+}
+
+function drawTicker(grid: Grid, model: StripModel, x0: number, width: number, t: number): void {
+ grid.text(x0, 4, `PHEROMONES ${model.pheromones.length}`, HIVE_COLOR.pink)
+
+ if (model.pheromones.length === 0) {
+ grid.text(x0, 5, 'no broadcasts in the shared memory yet', HIVE_COLOR.wall)
+ } else {
+ const shift = tickerShift(model.pheromones, t)
+ let x = x0 - shift
+
+ model.pheromones.forEach((entry, i) => {
+ const color = i === 0 && shift > 0 ? HIVE_COLOR.white : entry.isLoud ? HIVE_COLOR.yellow : HIVE_COLOR.cyan
+
+ for (const ch of `${i > 0 ? ' ⬡ ' : ''}${entry.text}`) {
+ if (x >= x0 && x < x0 + width) grid.set(x, 5, ch, ch === '⬡' ? HIVE_COLOR.wall : color)
+ x += 1
+ }
+ })
+ }
+
+ const keys = model.keys.length === 0 ? 'no shared-memory keys' : model.keys.map(key => `⬢ ${key}`).join(' ')
+
+ grid.text(x0, 6, keys.slice(0, width), HIVE_COLOR.wall)
+}
+
+export function stripPicture(model: StripModel, columns: number, t: number): Grid {
+ const grid = new Grid(columns, STRIP_ROWS)
+ const x0 = SHIELD_W + 2
+ const width = Math.max(10, columns - x0 - 1)
+
+ drawShield(grid, model.shield, model.strategy)
+ drawTimeline(grid, model, x0, width)
+ drawTicker(grid, model, x0, width, t)
+
+ return grid
+}
diff --git a/plugins/ruflo-console/hooks/gfx/hive.ts b/plugins/ruflo-console/hooks/gfx/hive.ts
index 7ab56150f0..bec1b35777 100644
--- a/plugins/ruflo-console/hooks/gfx/hive.ts
+++ b/plugins/ruflo-console/hooks/gfx/hive.ts
@@ -1,170 +1,283 @@
/**
- * 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).
+ * The Hive-Mind's hero picture: a honeycomb that fills the pane's width. The queen sits in the centre cell wearing her
+ * crown, with a soft pink halo on the walls around her; her workers take the cells nearest her, ring by ring, grouped
+ * by role (● worker cyan, ◆ specialist yellow, ▲ scout green), each cell lit by how alive the worker is; the cells
+ * nobody holds stay dim, so the comb fills as workers join. A worker flagged Byzantine has red walls. On the proposal
+ * picked below, each worker's ballot is a dot in its cell (green for, pink against). Decisions on record leave a scar
+ * in the outermost free cells: ✔ passed, ✘ failed.
*
- * 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.
+ * Motion means data: a worker's cell blinks and a wave runs from it to the queen for HIVE_PULSE_MS after the console
+ * sees it vote, join or leave; nothing else moves, but for the queen's slow heartbeat (HEARTBEAT_MS, in eight steps,
+ * so it repeats exactly). Colours are on the xterm-256 cube and its grey ramp, 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.
*/
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
+/** xterm-256 colours: the console's neon pink, yellow, cyan and green, a cube red, and grey-ramp walls. */
+export const HIVE_COLOR = {
+ pink: 0xd7005f,
+ yellow: 0xd7af00,
+ cyan: 0x00afd7,
+ green: 0x5fd75f,
+ red: 0xd70000,
+ magenta: 0xd700d7,
+ gold: 0xffd700,
+ white: 0xffffff,
+ grey: 0x808080,
+ wall: 0x585858,
+ faint: 0x303030,
+} as const
+
+export type Role = 'worker' | 'specialist' | 'scout' | 'unknown'
+export type Glow = 'busy' | 'idle' | 'down' | 'error' | 'unknown'
+export type Wave = { kind: 'for' | 'against' | 'join' | 'leave'; atMs: number }
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. */
+ role: Role
+ glow: Glow
+ /** Up to four characters on the cell's bottom row: 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
+ /** The worker's ballot on the picked proposal; absent when it has not voted or nothing is picked. */
+ vote?: 'for' | 'against' | 'pending'
+ isByzantine?: boolean
+ /** When the console saw this worker vote, join or leave: the cell blinks and a wave runs to the queen. */
+ wave?: Wave
}
-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 type Scar = { label: string; isPassed: boolean }
+
+export type HivePictureModel = { queen: { tag: string; isKnown: boolean; wave?: Wave }; members: HiveCell[]; scars: Scar[] }
+
+/** A cell is 8 columns by 5 rows; neighbouring columns of cells step 6 across and 2 down, so walls are shared. */
+export const CELL_W = 8
+export const CELL_H = 5
+export const STEP_X = 6
+const SHAPE = [' ▁▁▁▁ ', ' ╱ ╲ ', '╱ ╲', '╲ ╱', ' ╲▁▁▁▁╱ '] as const
+/** Each interior row of a cell: [row, first column, last column]. */
+export const INTERIOR: readonly [number, number, number][] = [
+ [1, 2, 5],
+ [2, 1, 6],
+ [3, 1, 6],
]
-export const MAX_RINGS = 4
-const MAX_METERS = 5
+export const HEARTBEAT_MS = 4_000
+const HEART = [0, 0.15, 0.35, 0.55, 0.55, 0.35, 0.15, 0] as const
+const MAX_SCARS = 8
+
+export const ROLE_GLYPH: Record<Role, string> = { worker: '●', specialist: '◆', scout: '▲', unknown: '○' }
+export const ROLE_COLOR: Record<Role, number> = { worker: HIVE_COLOR.cyan, specialist: HIVE_COLOR.yellow, scout: HIVE_COLOR.green, unknown: HIVE_COLOR.grey }
+/** A cell's lit interior by role and liveness, every one an exact cube or grey-ramp colour; null leaves it dark. */
+export const CELL_BG: Record<Role, Record<Glow, number | null>> = {
+ worker: { busy: 0x0087af, idle: 0x005f5f, down: 0x262626, error: 0x5f0000, unknown: null },
+ specialist: { busy: 0xaf8700, idle: 0x5f5f00, down: 0x262626, error: 0x5f0000, unknown: null },
+ scout: { busy: 0x5f8700, idle: 0x005f00, down: 0x262626, error: 0x5f0000, unknown: null },
+ unknown: { busy: null, idle: null, down: null, error: null, unknown: null },
+}
+const QUEEN_BG = 0x5f005f
+const DOT: Record<NonNullable<HiveCell['vote']>, [string, number]> = { for: ['●', HIVE_COLOR.green], against: ['●', HIVE_COLOR.pink], pending: ['·', HIVE_COLOR.grey] }
+/** The wave's leading dot: a glyph no cell uses, so it reads as the wave and nothing else. */
+export const WAVE_HEAD = '◉'
+export const WAVE_COLOR: Record<Wave['kind'], number> = { for: HIVE_COLOR.green, against: HIVE_COLOR.pink, join: HIVE_COLOR.cyan, leave: HIVE_COLOR.grey }
-/** 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)
+/** Light adds: the wall keeps its colour and the light is laid over it, so a halo stays saturated. */
+export function addLight(base: number, light: number, k: number): number {
+ const channel = (shift: number) => Math.min(255, Math.round(((base >> shift) & 255) + ((light >> shift) & 255) * k))
-/** 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
+ return (channel(16) << 16) | (channel(8) << 8) | channel(0)
+}
- while (rings < fits && cellsIn(rings) < members + 1) rings += 1
+/** Rows of the comb: one ring above and below the queen while every member fits the first ring, else two. */
+export const heroRows = (members: number): number => (members <= 6 ? 2 * 4 + CELL_H : 4 * 4 + CELL_H)
- return rings
+/** The top-left corner of axial cell (q, r) in a comb `columns` wide and `rows` tall, the queen's cell centred. */
+export function cellOrigin(q: number, r: number, columns: number, rows: number): { x: number; y: number } {
+ return { x: Math.floor(columns / 2) - CELL_W / 2 + q * STEP_X, y: Math.floor((rows - CELL_H) / 2) + 2 * q + 4 * r }
}
-/** 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]]
+export const hexDistance = (q: number, r: number): number => (Math.abs(q) + Math.abs(r) + Math.abs(q + r)) / 2
+
+/** Every whole cell that fits the comb, the queen's first, then by distance from her, each ring clockwise from the top. */
+export function fieldOf(columns: number, rows: number): [number, number][] {
+ const out: [number, number][] = []
+ const span = Math.ceil(columns / STEP_X) + 1
- for (let k = 1; k <= rings; k++) {
- let q = 0
- let r = -k
+ for (let q = -span; q <= span; q++) {
+ for (let r = -span - rows; r <= span + rows; r++) {
+ const { x, y } = cellOrigin(q, r, columns, rows)
- for (const [dq, dr] of CLOCKWISE) {
- for (let step = 0; step < k; step++) {
- out.push([q, r])
- q += dq
- r += dr
- }
+ if (x >= 0 && y >= 0 && x + CELL_W <= columns && y + CELL_H <= rows) out.push([q, r])
}
}
- return out
+ // Clockwise from the top, on screen: a column step is 6 across and 2 down, a row step 4 down (cells are taller than wide).
+ const angle = ([q, r]: [number, number]) => (Math.atan2((q * STEP_X) / 1.5, -(2 * q + 4 * r)) + 2 * Math.PI) % (2 * Math.PI)
+
+ return out.sort((a, b) => hexDistance(...a) - hexDistance(...b) || angle(a) - angle(b))
}
-/** 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 }
+const ROLE_ORDER: Role[] = ['worker', 'specialist', 'scout', 'unknown']
+
+/** Members in the order they take cells: by role, so each role holds an arc of the rings, then as listed. */
+export const byRole = (members: readonly HiveCell[]): HiveCell[] => ROLE_ORDER.flatMap(role => members.filter(member => member.role === role))
+
+/** A blink and its age while a wave is fresh, else null: the only motion a cell has. */
+export function waveAge(wave: Wave | undefined, t: number): number | null {
+ const age = wave === undefined ? -1 : t - wave.atMs
+
+ return age < 0 || age >= HIVE_PULSE_MS ? null : age
}
-export const hiveRows = (model: HivePictureModel, columns: number): number => {
- const meters = Math.min(MAX_METERS, model.meters.length)
+/** The queen's halo strength at `t`: eight steps a beat, so a frame one beat later is the same frame. */
+export function heartbeat(t: number): number {
+ const phase = (((t % HEARTBEAT_MS) + HEARTBEAT_MS) % HEARTBEAT_MS) / HEARTBEAT_MS
- return 4 * ringsFor(model.members.length, columns) + 3 + (meters > 0 ? meters + 1 : 0)
+ return HEART[Math.floor(phase * HEART.length) % HEART.length] as number
}
-/** 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)
+/** The walls of a cell, the bottom edge carrying the cell's own light under it. */
+export function drawWalls(grid: Grid, x: number, y: number, wall: number, bg?: number): void {
+ SHAPE.forEach((line, dy) => {
+ ;[...line].forEach((ch, dx) => {
+ if (ch !== ' ') grid.set(x + dx, y + dy, ch, wall, dy === CELL_H - 1 && ch === '▁' ? bg : undefined)
+ })
})
}
-/** 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
+/** Lights a cell's interior (and clears it): the background is the light, null keeps the terminal's own. */
+export function fillInterior(grid: Grid, x: number, y: number, bg: number | null): void {
+ for (const [dy, from, to] of INTERIOR) {
+ for (let dx = from; dx <= to; dx++) grid.set(x + dx, y + dy, ' ', HIVE_COLOR.white, bg ?? undefined)
+ }
+}
+
+function drawMember(grid: Grid, cell: HiveCell, x: number, y: number, t: number): void {
+ const age = waveAge(cell.wave, t)
+ const isLit = age !== null && Math.floor(age / 250) % 2 === 0
+ const bg = CELL_BG[cell.role][cell.glow]
+ const wall = isLit ? HIVE_COLOR.white : cell.isByzantine === true ? HIVE_COLOR.red : HIVE_COLOR.wall
+ const glyph = cell.glow === 'busy' ? HIVE_COLOR.white : cell.glow === 'down' || cell.glow === 'unknown' ? HIVE_COLOR.grey : ROLE_COLOR[cell.role]
+
+ fillInterior(grid, x, y, bg)
+ drawWalls(grid, x, y, wall, bg ?? undefined)
+ grid.set(x + 3, y + 2, ROLE_GLYPH[cell.role], isLit ? HIVE_COLOR.white : glyph, bg ?? undefined)
+ grid.text(x + 2, y + 3, cell.tag.slice(0, 4), age !== null ? HIVE_COLOR.white : HIVE_COLOR.grey, bg ?? undefined)
- if (age < 0 || age >= HIVE_PULSE_MS) return { isLit: false, isPulsing: false }
+ if (cell.isByzantine === true) grid.set(x + 4, y + 1, '✖', HIVE_COLOR.red, bg ?? undefined)
+ else if (cell.vote !== undefined) grid.set(x + 4, y + 1, DOT[cell.vote][0], DOT[cell.vote][1], bg ?? undefined)
+}
+
+function drawQueen(grid: Grid, model: HivePictureModel, x: number, y: number, t: number): void {
+ const age = waveAge(model.queen.wave, t)
+ const isLit = age !== null && Math.floor(age / 250) % 2 === 0
+ const bg = model.queen.isKnown ? QUEEN_BG : null
- return { isLit: Math.floor(age / 250) % 2 === 0, isPulsing: true }
+ fillInterior(grid, x, y, bg)
+ drawWalls(grid, x, y, isLit ? HIVE_COLOR.white : model.queen.isKnown ? HIVE_COLOR.pink : HIVE_COLOR.grey, bg ?? undefined)
+ grid.text(x + 2, y + 1, model.queen.isKnown ? '✦ ✦' : '', HIVE_COLOR.yellow, bg ?? undefined)
+ grid.set(x + 3, y + 2, model.queen.isKnown ? '♛' : '?', model.queen.isKnown ? HIVE_COLOR.gold : HIVE_COLOR.grey, bg ?? undefined)
+ grid.text(x + 3, y + 3, model.queen.tag.slice(0, 3), HIVE_COLOR.yellow, bg ?? undefined)
}
-const VOTE_WALL = { for: HIVE_COLOR.green, against: HIVE_COLOR.pink, byzantine: HIVE_COLOR.yellow } as const
+/** The halo: the six cells around the queen get pink light on their walls, swelling and fading with her heartbeat; a
+ * blinking or Byzantine neighbour keeps its own walls. */
+function drawHalo(grid: Grid, columns: number, rows: number, t: number, lit: Set<string>): void {
+ const k = heartbeat(t)
-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
+ for (const [q, r] of [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]] as const) {
+ if (lit.has(`${q},${r}`)) continue
- ink(grid, x, y, TOP, wall)
- ink(grid, x, y + 1, MID, wall)
- ink(grid, x, y + 2, BOTTOM, wall)
+ const { x, y } = cellOrigin(q, r, columns, rows)
- // 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)
+ SHAPE.forEach((line, dy) => {
+ ;[...line].forEach((ch, dx) => {
+ const at = grid.glyph(x + dx, y + dy)
+
+ // Only the walls the queen does not share: hers stay pink whatever the beat.
+ if (ch !== ' ' && at === ch.codePointAt(0)) grid.set(x + dx, y + dy, ch, addLight(HIVE_COLOR.faint, HIVE_COLOR.pink, 0.3 + k))
+ })
+ })
+ }
}
-/** 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))
+/** A dotted wave from a worker's cell to the queen's: its head travels in with the age, its trail fading behind. */
+function drawWave(grid: Grid, from: { x: number; y: number }, to: { x: number; y: number }, wave: Wave, t: number): void {
+ const age = waveAge(wave, t)
- grid.text(0, y, label, meter.isPicked ? HIVE_COLOR.white : HIVE_COLOR.grey)
+ if (age === null) return
- 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
+ const front = age / HIVE_PULSE_MS
+ const steps = Math.max(1, Math.ceil(Math.max(Math.abs(to.x - from.x), Math.abs(to.y - from.y) * 2)))
+ let hasHead = false
- grid.set(label.length + i, y, isTick ? '┃' : i < forCells + againstCells ? '█' : '░', isTick ? HIVE_COLOR.yellow : color)
- }
+ // From the front back along the trail: the first free cell carries the head, the ones behind it the fading trail.
+ for (let i = Math.min(steps, Math.floor(front * steps)); i >= 0; i--) {
+ const s = i / steps
+ const behind = front - s
+ const x = Math.round(from.x + (to.x - from.x) * s)
+ const y = Math.round(from.y + (to.y - from.y) * s)
+
+ if (behind > 0.45) break
+ // Only over empty space, so the wave never hides a glyph, a ballot or a wall.
+ if (grid.glyph(x, y) !== 0x20) continue
- 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)
+ grid.set(x, y, hasHead ? (behind < 0.2 ? '•' : '·') : WAVE_HEAD, hasHead ? addLight(0x000000, WAVE_COLOR[wave.kind], 1 - behind) : HIVE_COLOR.white)
+ hasHead = true
+ }
}
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 rows = heroRows(model.members.length)
+ const grid = new Grid(columns, rows)
+ const field = fieldOf(columns, rows)
+ const members = byRole(model.members).slice(0, Math.max(0, field.length - 1))
+ const free = field.slice(1 + members.length)
+ const scars = model.scars.slice(0, Math.min(MAX_SCARS, free.length))
+ const centre = (q: number, r: number) => {
+ const { x, y } = cellOrigin(q, r, columns, rows)
+
+ return { x: x + 4, y: y + 2 }
+ }
+
+ // The empty comb first, dim, then the scars in its outermost cells, then the workers and the queen over them.
+ for (const [q, r] of field) {
+ const { x, y } = cellOrigin(q, r, columns, rows)
+
+ drawWalls(grid, x, y, HIVE_COLOR.faint)
+ }
+
+ scars.forEach((scar, i) => {
+ const [q, r] = free[free.length - 1 - i] as [number, number]
+ const { x, y } = cellOrigin(q, r, columns, rows)
+ const color = scar.isPassed ? HIVE_COLOR.green : HIVE_COLOR.pink
+
+ drawWalls(grid, x, y, addLight(HIVE_COLOR.faint, color, 0.35))
+ grid.set(x + 3, y + 2, scar.isPassed ? '✔' : '✘', color)
+ grid.text(x + 2, y + 3, scar.label.slice(0, 4), addLight(HIVE_COLOR.faint, color, 0.5))
+ })
+
+ members.forEach((cell, i) => {
+ const [q, r] = field[i + 1] as [number, number]
+ const { x, y } = cellOrigin(q, r, columns, rows)
+
+ drawMember(grid, cell, x, y, t)
})
- const hidden = cells.length - slots.length
+ const queen = cellOrigin(0, 0, columns, rows)
+ const lit = new Set(members.flatMap((cell, i) => (waveAge(cell.wave, t) !== null || cell.isByzantine === true ? [`${(field[i + 1] as [number, number]).join(',')}`] : [])))
+
+ if (model.queen.isKnown) drawHalo(grid, columns, rows, t, lit)
+ drawQueen(grid, model, queen.x, queen.y, t)
+
+ members.forEach((cell, i) => {
+ const [q, r] = field[i + 1] as [number, number]
+
+ if (cell.wave !== undefined) drawWave(grid, centre(q, r), centre(0, 0), cell.wave, t)
+ })
- if (hidden > 0) grid.text(Math.max(0, columns - 14), 4 * rings + 2, `+${hidden} more`.slice(0, 14), HIVE_COLOR.grey)
+ const hidden = model.members.length - members.length
- model.meters.slice(0, MAX_METERS).forEach((meter, i) => drawMeter(grid, meter, 4 * rings + 4 + i, columns))
+ if (hidden > 0) grid.text(Math.max(0, columns - 10), rows - 1, `+${hidden} more`.slice(0, 10), HIVE_COLOR.grey)
return grid
}
diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.ts
index b3efe40cc9..e425b0747d 100644
--- a/plugins/ruflo-console/hooks/views/frames.ts
+++ b/plugins/ruflo-console/hooks/views/frames.ts
@@ -5,8 +5,6 @@
*/
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'
@@ -19,7 +17,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 { hivePictures } from './hive'
import { openTasks } from './select'
export const MAX_NODES = 100
@@ -151,12 +149,9 @@ 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))
+ case 'hive':
+ for (const [key, grid] of hivePictures(state, width, nowMs, t)) pictures.set(key, grid)
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
index 1076db6249..0d45c5cd91 100644
--- a/plugins/ruflo-console/hooks/views/hive.ts
+++ b/plugins/ruflo-console/hooks/views/hive.ts
@@ -1,23 +1,38 @@
/**
- * 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.
+ * The Hive-Mind view: what `.claude-flow/hive-mind/state.json` records, drawn as a living comb. The hero honeycomb (the
+ * queen crowned in the centre, her workers ringed around her by role, lit by liveness, Byzantine voters in red, scars
+ * of past decisions), a voting chamber per open proposal (pick one with j/k), the strip with the fault-tolerance
+ * shield, the term timeline and the pheromone ticker; then the same facts in words. Every action asks y/n first and
+ * runs one fixed argv: vote (as the next worker that has not voted), propose, broadcast, spawn. With no hive yet, an
+ * empty comb with a glowing egg holds the start buttons.
*/
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 { Arrivals, faultTolerance, membersOf, nextVoter, nodesOf, pickedProposal, proposalStrategyOf, proposeBlock, requiredVotes, tallyOf, waveOf, type Liveness, type Member, type Tally } from '../data/hive'
+import { shortId, type HiveInfo, type Proposal } from '../data/parse'
+import { hivePicture, type HiveCell, type HivePictureModel, type Role } from '../gfx/hive'
+import { chambersPicture, MAX_CHAMBERS, type Chamber } from '../gfx/hive-chamber'
+import { eggBottomPicture, eggTopPicture } from '../gfx/hive-egg'
+import { stripPicture, type Mark, type StripModel } from '../gfx/hive-strip'
+import type { Grid } from '../gfx/raster'
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] ?? '●') : '○')
+const roleOf = (member: Member): Role => (member.isKnown && (member.role === 'worker' || member.role === 'specialist' || member.role === 'scout') ? member.role : 'unknown')
+
+/** The starts an empty hive offers: the palette ids `starts.ts` registers, each asking first with its exact argv. */
+export const HIVE_STARTS = [
+ { id: 'hive', label: '▸ start a hive-mind (raft)' },
+ { id: 'hive-workers', label: '▸ spawn 3 hive workers' },
+] as const
+
+/** When the console first saw each broadcast: the ticker slides a new one in, once. */
+const arrivals = new Arrivals()
/** The bar a proposal must clear, as the CLI's rule reads in words. */
function ruleOf(strategy: string, preset?: string): string {
@@ -27,34 +42,119 @@ function ruleOf(strategy: string, preset?: string): string {
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 {
+/** The honeycomb's model for this frame: the queen, each worker's cell with its ballot on the picked proposal, the scars. */
+export function hivePictureModelOf(state: State, nowMs: 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 }) }
+ const wave = waveOf(state.events, member.id, nowMs)
+
+ return {
+ id: member.id,
+ role: roleOf(member),
+ glow: member.liveness,
+ tag: shortId(member.id).slice(-4),
+ ...(picked !== null && { vote: ballot === undefined ? ('pending' as const) : ballot.isFor ? ('for' as const) : ('against' as const) }),
+ ...(picked?.byzantine.includes(member.id) === true && { isByzantine: true }),
+ ...(wave !== null && { wave }),
+ }
})
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 }) },
+ queen: { tag: hive.queenTerm === undefined ? '' : `T${hive.queenTerm}`, isKnown: hive.queen !== undefined },
members,
- meters: hive.pending.map(proposal => {
- const tally = tallyOf(hive, proposal, nowMs)
+ scars: hive.history
+ .slice(-8)
+ .reverse()
+ .map(decision => ({ label: decision.type, isPassed: decision.result === 'approved' })),
+ }
+}
+
+/** The open proposals the chambers show: at most MAX_CHAMBERS, the window sliding so the picked one is always in it. */
+export function shownProposals(hive: HiveInfo, picked: Proposal | null): Proposal[] {
+ const at = picked === null ? 0 : hive.pending.findIndex(entry => entry.id === picked.id)
+ const from = Math.max(0, Math.min(hive.pending.length - MAX_CHAMBERS, at - MAX_CHAMBERS + 1))
+
+ return hive.pending.slice(from, from + MAX_CHAMBERS)
+}
+
+export function chambersOf(state: State, hive: HiveInfo, nowMs: number): Chamber[] {
+ const picked = pickedProposal(hive, state.select.item)
+
+ return shownProposals(hive, picked).map(proposal => {
+ const tally = tallyOf(hive, proposal, nowMs)
+
+ return {
+ label: proposal.type,
+ note: noteOf(tally),
+ votesFor: proposal.votesFor,
+ votesAgainst: proposal.votesAgainst,
+ required: tally.required,
+ nodes: tally.nodes,
+ ballots: proposal.ballots.map(ballot => {
+ const wave = waveOf(state.events, ballot.voter, nowMs)
+
+ return { tag: shortId(ballot.voter), isFor: ballot.isFor, ...(wave !== null && (wave.kind === 'for' || wave.kind === 'against') && { atMs: wave.atMs }) }
+ }),
+ byzantine: proposal.byzantine,
+ isPicked: proposal.id === picked?.id,
+ }
+ })
+}
+
+/** The strip's model: the shield, the dated marks on the term timeline, and the broadcasts newest first. */
+export function stripOf(hive: HiveInfo, nowMs: number): StripModel {
+ const marks: Mark[] = [
+ ...hive.history.flatMap(decision => (decision.decidedAtMs === undefined ? [] : [{ atMs: decision.decidedAtMs, kind: decision.result === 'approved' ? ('passed' as const) : ('failed' as const), label: decision.type, ...(decision.term !== undefined && { term: decision.term }) }])),
+ ...hive.pending.flatMap(proposal => (proposal.proposedAtMs === undefined ? [] : [{ atMs: proposal.proposedAtMs, kind: 'opened' as const, label: proposal.type, ...(proposal.term !== undefined && { term: proposal.term }) }])),
+ ].sort((a, b) => a.atMs - b.atMs)
+ const seen = arrivals.arrivedAt(`${hive.createdAtMs ?? 0}:${hive.queen ?? ''}`, hive.broadcasts.map(entry => entry.id), nowMs)
+ const times = [hive.createdAtMs, hive.queenElectedAtMs, ...marks.map(mark => mark.atMs)].filter((ms): ms is number => ms !== undefined && ms <= 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 }
- }),
+ return {
+ shield: faultTolerance(hive.strategy, hive.workers.length),
+ strategy: hive.strategy ?? 'n/a',
+ startMs: times.length === 0 ? nowMs - 60_000 : Math.min(...times),
+ nowMs,
+ ...(hive.queenTerm !== undefined && { term: hive.queenTerm }),
+ ...(hive.queenElectedAtMs !== undefined && { electedAtMs: hive.queenElectedAtMs }),
+ marks,
+ pheromones: hive.broadcasts
+ .slice()
+ .reverse()
+ .map(entry => ({ id: entry.id, text: `${entry.priority === 'normal' ? '' : `[${entry.priority}] `}${entry.from}: ${entry.message}`, isLoud: entry.priority === 'high' || entry.priority === 'critical', arrivedAtMs: seen.get(entry.id) ?? 0 })),
+ keys: hive.memoryKeys.filter(key => key !== 'broadcasts'),
}
}
+/** Every Hive-Mind picture for one instant, by Raster key: the comb, chambers and strip, or the empty comb's egg. */
+export function hivePictures(state: State, columns: number, nowMs: number, t: number): Map<string, Grid> {
+ const pictures = new Map<string, Grid>()
+ const hive = state.snapshot?.hive ?? null
+
+ if (state.snapshot === null) return pictures
+
+ if (hive === null) {
+ pictures.set('hive-egg', eggTopPicture(Math.min(columns, 96)))
+ pictures.set('hive-egg-base', eggBottomPicture(Math.min(columns, 96)))
+
+ return pictures
+ }
+
+ const model = hivePictureModelOf(state, nowMs)
+
+ if (model !== null) pictures.set('hive', hivePicture(model, columns, t))
+ if (hive.pending.length > 0) pictures.set('hive-chambers', chambersPicture(chambersOf(state, hive, nowMs), columns, t))
+ pictures.set('hive-strip', stripPicture(stripOf(hive, nowMs), columns, t))
+
+ return pictures
+}
+
/** A proposal's strategy, term and state of play in a few words. */
function noteOf(tally: Tally): string {
const { proposal } = tally
@@ -215,26 +315,41 @@ function actSection(ctx: Ctx, hive: HiveInfo): RenderElement[] {
return rows
}
+/**
+ * No hive yet: the empty comb with its egg, the start buttons inside it (between the comb's two halves), and the way
+ * in said plainly. The buttons run the starts' palette ids, so each asks first with its exact argv.
+ */
+function emptyComb(ctx: Ctx): RenderElement[] {
+ return [
+ picture(ctx, 'hive-egg', 'an empty comb: no queen yet'),
+ text(ctx, ' the comb is empty · the egg is where the queen will sit · start a hive, then spawn workers to fill the comb', { color: THEME.warn }),
+ row(ctx, [text(ctx, ' '), ...HIVE_STARTS.map(start => button(ctx, `start-${start.id}`, start.label, () => void ctx.act.run(start.id)))]),
+ picture(ctx, 'hive-egg-base', ''),
+ ]
+}
+
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')
- }
+ if (hive === null) return col(ctx, [rule(ctx, 'Hive-Mind', 'not initialised'), ...emptyComb(ctx)], 'hive')
const members = membersOf(hive, snap.hiveAgents, snap.agents)
+ const byzantine = new Set(hive.pending.flatMap(proposal => proposal.byzantine)).size
return col(
ctx,
[
- rule(ctx, 'Hive-Mind', `${hive.topology} · ${hive.strategy ?? 'consensus n/a'}`),
- ...summary(ctx, hive, members),
+ rule(ctx, 'Hive-Mind', `${hive.topology} · ${hive.strategy ?? 'consensus n/a'} · ${members.length} in the comb${byzantine > 0 ? ` · ${byzantine} byzantine` : ''}`),
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 }),
+ text(ctx, '♛ queen · ● worker ◆ specialist ▲ scout ○ in no store · brighter = busier · ballot dot: green for, pink against, · not yet · red walls ✖ byzantine · ✔ ✘ scars: decided · a wave runs to the queen for 2 s when a vote lands', { dimColor: true }),
+ ...(hive.pending.length > 0 ? [rule(ctx, 'Voting chambers', `${hive.pending.length} open · for fills from the left, against from the right, ┃ the quorum lines`), picture(ctx, 'hive-chambers', `${hive.pending.length} open proposals`)] : []),
...proposalsSection(ctx, hive),
+ rule(ctx, 'Terms · pheromones', 'the shield: faulty workers survived, f of n'),
+ picture(ctx, 'hive-strip', 'the term timeline and the broadcast ticker need a terminal'),
+ ...summary(ctx, hive, members),
...workersSection(ctx, hive, members),
...historySection(ctx, hive),
...broadcastSection(ctx, hive),
diff --git a/plugins/ruflo-console/tests/hive.spec.ts b/plugins/ruflo-console/tests/hive.spec.ts
index 1103a4c213..22bc99d1bc 100644
--- a/plugins/ruflo-console/tests/hive.spec.ts
+++ b/plugins/ruflo-console/tests/hive.spec.ts
@@ -6,10 +6,14 @@
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 { Arrivals, faultTolerance, membersOf, nextVoter, pickedProposal, proposalStrategyOf, proposeBlock, requiredVotes, tallyOf, waveOf } 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 { CELL_BG, CELL_H, CELL_W, cellOrigin, drawWalls, fieldOf, HEARTBEAT_MS, heroRows, hexDistance, HIVE_COLOR, hivePicture, INTERIOR, type HiveCell, type HivePictureModel, type Role } from '../hooks/gfx/hive'
+import { chamberLayout, chamberRows, chambersPicture, type Chamber } from '../hooks/gfx/hive-chamber'
+import { EGG_BOTTOM_ROWS, EGG_TOP_ROWS, eggBottomPicture, eggTopPicture } from '../hooks/gfx/hive-egg'
+import { axisAt, STRIP_ROWS, stripPicture, tickerShift, type StripModel } from '../hooks/gfx/hive-strip'
+import { DEFAULT, Grid } from '../hooks/gfx/raster'
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'
@@ -17,12 +21,42 @@ 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 }],
+const ROLES: Role[] = ['worker', 'specialist', 'scout']
+const cellModel = (members: number, extra: Partial<HiveCell> = {}, scars: HivePictureModel['scars'] = []): HivePictureModel => ({
+ queen: { tag: 'T2', isKnown: true },
+ members: Array.from({ length: members }, (_, i) => ({ id: `w${i}`, role: ROLES[i % 3] as Role, glow: i % 2 === 0 ? 'busy' : 'idle', tag: `w${i}`, ...(i === 0 && extra) })),
+ scars,
})
+/** A picture as text, one line per row, for a still in the test output. */
+const stillOf = (grid: Grid): string =>
+ Array.from({ length: grid.rows }, (_, y) =>
+ Array.from({ length: grid.columns }, (_, x) => String.fromCodePoint(grid.glyph(x, y)))
+ .join('')
+ .trimEnd(),
+ ).join('\n')
+const fg = (grid: Grid, x: number, y: number) => grid.cells[(y * grid.columns + x) * 3 + 1] as number
+const bg = (grid: Grid, x: number, y: number) => grid.cells[(y * grid.columns + x) * 3 + 2] as number
+const at = (grid: Grid, x: number, y: number) => String.fromCodePoint(grid.glyph(x, y))
+
+/** The xterm-256 index Claude Code would draw a colour as where the terminal has no true colour: nearest of 16..255. */
+function xterm256(color: number): number {
+ const levels = [0, 95, 135, 175, 215, 255]
+ const table: number[] = []
+
+ for (const r of levels) for (const g of levels) for (const b of levels) table.push((r << 16) | (g << 8) | b)
+ for (let i = 0; i < 24; i++) table.push((8 + 10 * i) * 0x010101)
+
+ const distance = (a: number, b: number) => [16, 8, 0].reduce((sum, shift) => sum + (((a >> shift) & 255) - ((b >> shift) & 255)) ** 2, 0)
+ let best = 0
+
+ table.forEach((entry, i) => {
+ if (distance(entry, color) < distance(table[best] as number, color)) best = i
+ })
+
+ return best + 16
+}
+
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] })
@@ -114,48 +148,292 @@ describe('hive events', () => {
})
describe('the honeycomb', () => {
- it('walks the rings centre first, and no two cells share an interior', () => {
- const rings = 3
- const slots = spiral(rings)
+ it('fills a comb wider than tall, the queen first, then by distance, no two interiors overlapping, every cell whole', () => {
+ const field = fieldOf(110, 21)
const interiors = new Set<string>()
- expect(slots).toHaveLength(cellsIn(rings))
- expect(slots[0]).toEqual([0, 0])
+ expect(field[0]).toEqual([0, 0])
+ expect(field.length).toBeGreaterThan(40)
+ field.slice(1).forEach(([q, r], i) => expect(hexDistance(q, r)).toBeGreaterThanOrEqual(hexDistance(...(field[i] as [number, number]))))
+ expect(field.slice(1, 7).map(([q, r]) => hexDistance(q, r))).toEqual([1, 1, 1, 1, 1, 1])
+
+ for (const [q, r] of field) {
+ const { x, y } = cellOrigin(q, r, 110, 21)
- for (const [q, r] of slots) {
- const { x, y } = cellOrigin(q, r, rings, 100)
+ expect(x >= 0 && y >= 0 && x + CELL_W <= 110 && y + CELL_H <= 21).toBe(true)
- for (let dx = 1; dx <= 4; dx++) {
- const key = `${x + dx},${y + 1}`
+ for (const [dy, from, to] of INTERIOR) {
+ for (let dx = from; dx <= to; dx++) {
+ const key = `${x + dx},${y + dy}`
- expect(interiors.has(key)).toBe(false)
- interiors.add(key)
+ expect(interiors.has(key)).toBe(false)
+ interiors.add(key)
+ }
}
+ }
+ })
- expect(x).toBeGreaterThanOrEqual(0)
- expect(y).toBeGreaterThanOrEqual(0)
+ it('shares every wall with its six neighbours: drawing a neighbour never changes a wall the queen drew', () => {
+ const alone = new Grid(40, 21)
+ const { x, y } = cellOrigin(0, 0, 40, 21)
+
+ drawWalls(alone, x, y, 1)
+
+ for (const [q, r] of [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]] as const) {
+ const both = new Grid(40, 21)
+ const next = cellOrigin(q, r, 40, 21)
+
+ drawWalls(both, x, y, 1)
+ drawWalls(both, next.x, next.y, 2)
+
+ for (let cy = 0; cy < 21; cy++) for (let cx = 0; cx < 40; cx++) if (alone.glyph(cx, cy) !== 0x20) expect([cx, cy, at(both, cx, cy)]).toEqual([cx, cy, at(alone, cx, cy)])
}
})
- it('puts the queen in the centre and grows rings only as wide as the columns allow', () => {
+ it('crowns the queen in the centre and rings her workers by role, the free cells dim, one ring of rows until it is full', () => {
const grid = hivePicture(cellModel(6), 80, 0)
- const { x, y } = cellOrigin(0, 0, ringsFor(6, 80), 80)
+ const queen = cellOrigin(0, 0, 80, grid.rows)
+ const field = fieldOf(80, grid.rows)
+ const glyphAt = (i: number) => {
+ const { x, y } = cellOrigin(...(field[i] as [number, number]), 80, grid.rows)
+
+ return at(grid, x + 3, y + 2)
+ }
+
+ expect(at(grid, queen.x + 3, queen.y + 2)).toBe('♛')
+ expect(fg(grid, queen.x + 3, queen.y + 2)).toBe(HIVE_COLOR.gold)
+ // Two of each role, grouped: workers hold one arc of the ring, specialists the next, scouts the last.
+ expect([1, 2, 3, 4, 5, 6].map(glyphAt)).toEqual(['●', '●', '◆', '◆', '▲', '▲'])
+ expect(glyphAt(7)).toBe(' ')
+ const free = cellOrigin(...(field[field.length - 1] as [number, number]), 80, grid.rows)
- 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))
+ expect(fg(grid, free.x + 1, free.y + 1)).toBe(HIVE_COLOR.faint)
+ expect([heroRows(0), heroRows(6), heroRows(7), heroRows(60)]).toEqual([13, 13, 21, 21])
+ expect([0, 1_234, 99_999].map(t => hivePicture(cellModel(9), 80, t).rows)).toEqual([21, 21, 21])
})
- it('is still with no fresh event, and blinks for two seconds after one, at one size', () => {
+ it('shows liveness as brightness, on colours that stay distinct in 256 colours', () => {
+ const grid = hivePicture(cellModel(2), 60, 0)
+ const busy = cellOrigin(...(fieldOf(60, grid.rows)[1] as [number, number]), 60, grid.rows)
+
+ expect(bg(grid, busy.x + 3, busy.y + 2)).toBe(CELL_BG.worker.busy)
+
+ for (const role of ROLES) {
+ const levels = [CELL_BG[role].busy, CELL_BG[role].idle, CELL_BG[role].down].map(color => xterm256(color as number))
+
+ expect(new Set(levels).size).toBe(3)
+ }
+
+ expect(new Set([HIVE_COLOR.red, HIVE_COLOR.pink, HIVE_COLOR.green, HIVE_COLOR.wall].map(xterm256)).size).toBe(4)
+ })
+
+ it('drops each ballot as a dot in its voter\'s cell and walls a Byzantine voter in red', () => {
+ const voted = hivePicture({ ...cellModel(3), members: cellModel(3).members.map((cell, i) => ({ ...cell, vote: (['for', 'against', 'pending'] as const)[i] })) }, 60, 0)
+ const cells = fieldOf(60, voted.rows).slice(1, 4).map(([q, r]) => cellOrigin(q, r, 60, voted.rows))
+
+ expect(cells.map(({ x, y }) => [at(voted, x + 4, y + 1), fg(voted, x + 4, y + 1)])).toEqual([
+ ['●', HIVE_COLOR.green],
+ ['●', HIVE_COLOR.pink],
+ ['·', HIVE_COLOR.grey],
+ ])
+
+ const traitor = hivePicture(cellModel(3, { isByzantine: true, vote: 'for' }), 60, 0)
+ const { x, y } = cells[0] as { x: number; y: number }
+ let red = 0
+
+ for (let dy = 0; dy < CELL_H; dy++) for (let dx = 0; dx < CELL_W; dx++) if (fg(traitor, x + dx, y + dy) === HIVE_COLOR.red) red += 1
+
+ expect(at(traitor, x + 4, y + 1)).toBe('✖')
+ expect(red).toBeGreaterThan(6)
+ })
+
+ it('leaves a scar for each decision in the outermost free cells: ✔ passed, ✘ failed', () => {
+ const grid = hivePicture(cellModel(2, {}, [{ label: 'naming', isPassed: true }, { label: 'budget', isPassed: false }]), 70, 0)
+ const field = fieldOf(70, grid.rows)
+ const scar = (i: number) => {
+ const { x, y } = cellOrigin(...(field[field.length - 1 - i] as [number, number]), 70, grid.rows)
+
+ return [at(grid, x + 3, y + 2), stillOf(grid).split('\n')[y + 3]?.slice(x + 2, x + 6)]
+ }
+
+ expect([scar(0), scar(1)]).toEqual([
+ ['✔', 'nami'],
+ ['✘', 'budg'],
+ ])
+ })
+
+ it('beats the queen\'s heart on a fixed period, and only in her halo', () => {
const still = cellModel(8)
+ const grid = hivePicture(still, 90, 1_000)
+ const queen = cellOrigin(0, 0, 90, grid.rows)
+ const half = hivePicture(still, 90, 1_000 + HEARTBEAT_MS / 2)
+
+ expect(hivePicture(still, 90, 1_000 + HEARTBEAT_MS).encode()).toBe(grid.encode())
+ expect(half.encode()).not.toBe(grid.encode())
+
+ for (let y = 0; y < grid.rows; y++) {
+ for (let x = 0; x < grid.columns; x++) {
+ const isHalo = x >= queen.x - 6 && x < queen.x + 6 + CELL_W && y >= queen.y - 4 && y < queen.y + 4 + CELL_H
+
+ if (!isHalo) expect([x, y, fg(half, x, y), at(half, x, y)]).toEqual([x, y, fg(grid, x, y), at(grid, x, y)])
+ }
+ }
+ })
+
+ it('runs a wave from a voter to the queen for two seconds after the vote lands, and is still otherwise', () => {
+ const wave = { kind: 'for' as const, atMs: 10_000 }
+ const model = cellModel(12)
+ const waving = { ...model, members: model.members.map((cell, i) => (i === 11 ? { ...cell, wave } : cell)) }
+ const queen = cellOrigin(0, 0, 100, heroRows(12))
+ const head = (t: number) => {
+ const grid = hivePicture(waving, 100, t)
+
+ for (let y = 0; y < grid.rows; y++) for (let x = 0; x < grid.columns; x++) if (at(grid, x, y) === '◉') return Math.hypot(x - queen.x - 4, (y - queen.y - 2) * 2)
+
+ return null
+ }
+ const near = head(11_700)
+ const far = head(10_300)
+
+ expect(far).not.toBeNull()
+ expect(near).not.toBeNull()
+ expect(near as number).toBeLessThan(far as number)
+ expect(hivePicture(waving, 100, 10_300).encode()).not.toBe(hivePicture(model, 100, 10_300).encode())
+ expect(hivePicture(waving, 100, 12_000).encode()).toBe(hivePicture(model, 100, 12_000).encode())
+ expect(hivePicture(waving, 100, 9_000).encode()).toBe(hivePicture(model, 100, 9_000).encode())
+ expect(new Set([10_000, 10_500, 11_999, 12_000].map(t => `${hivePicture(waving, 100, t).columns}x${hivePicture(waving, 100, t).rows}`)).size).toBe(1)
+ })
+})
+
+describe('the hive\'s motion comes from events', () => {
+ it('reads a vote, a join and a leave from the words diffEvents writes, only while fresh', () => {
+ 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_000)
+
+ expect(waveOf(events, WORKERS[0], 5_100)).toEqual({ kind: 'for', atMs: 5_000 })
+ expect(waveOf(events, WORKERS[1], 5_100)).toEqual({ kind: 'against', atMs: 5_000 })
+ expect(waveOf(events, WORKERS[2], 5_100)).toEqual({ kind: 'join', atMs: 5_000 })
+ expect(waveOf(diffEvents(withHive(hive), withHive(before), 5_000), WORKERS[2], 5_100)).toEqual({ kind: 'leave', atMs: 5_000 })
+ expect(waveOf(events, WORKERS[0], 7_000)).toBeNull()
+ expect(waveOf(events, 'nobody', 5_100)).toBeNull()
+ })
+
+ it('says a broadcast arrived only once it is new: what the first read finds is old', () => {
+ const log = new Arrivals()
+
+ expect(log.arrivedAt('h1', ['a', 'b'], 5_000).get('a')).toBe(0)
+ expect(log.arrivedAt('h1', ['a', 'b', 'c'], 6_000).get('c')).toBe(6_000)
+ expect(log.arrivedAt('h1', ['a', 'b', 'c'], 7_000).get('c')).toBe(6_000)
+ expect(log.arrivedAt('h2', ['c'], 8_000).get('c')).toBe(0)
+ })
+})
+
+describe('the voting chambers', () => {
+ const chamber: Chamber = { label: 'design', note: 'raft T2', votesFor: 1, votesAgainst: 1, required: 2, nodes: 3, ballots: [{ tag: 'a1b2', isFor: true, atMs: 10_000 }, { tag: 'c3d4', isFor: false }], byzantine: ['e5f6'], isPicked: true }
+
+ it('fills for from the left and against from the right toward their quorum lines', () => {
+ expect(chamberLayout({ votesFor: 1, votesAgainst: 0, required: 2, nodes: 3 }, 30)).toEqual({ forCells: 10, againstCells: 0, passAt: 19, rejectAt: 10 })
+ expect(chamberLayout({ votesFor: 3, votesAgainst: 3, required: 2, nodes: 3 }, 30)).toMatchObject({ forCells: 30, againstCells: 0 })
+ expect(chamberLayout({ votesFor: 0, votesAgainst: 2, required: 2, nodes: 4 }, 20)).toEqual({ forCells: 0, againstCells: 10, passAt: 9, rejectAt: 10 })
+ })
- expect(hivePicture(still, 90, 1_000).encode()).toBe(hivePicture(still, 90, 987_654).encode())
+ it('puts a dot per ballot, a red ✖ for a Byzantine voter, and blinks a new ballot for two seconds only', () => {
+ const grid = chambersPicture([chamber], 100, 0)
+ const ballots = stillOf(grid).split('\n')[1] ?? ''
+
+ expect(grid.rows).toBe(chamberRows(1))
+ expect([...ballots].filter(ch => ch === '●')).toHaveLength(2)
+ expect(ballots).toContain('✖')
+ expect(stillOf(grid)).toContain('DESIGN')
+ expect(stillOf(grid)).toContain('1 for · 1 against · need 2 of 3')
+ expect(chambersPicture([chamber], 100, 10_100).encode()).not.toBe(grid.encode())
+ expect(chambersPicture([chamber], 100, 12_000).encode()).toBe(grid.encode())
+ expect([1, 4, 9].map(chamberRows)).toEqual([4, 16, 16])
+ })
+})
+
+describe('the strip', () => {
+ const model: StripModel = {
+ shield: { faulty: 1, of: 3, rule: 'raft f < n/2' },
+ strategy: 'raft',
+ startMs: 0,
+ nowMs: 100_000,
+ term: 2,
+ electedAtMs: 40_000,
+ marks: [
+ { atMs: 10_000, kind: 'passed', label: 'naming', term: 1 },
+ { atMs: 70_000, kind: 'opened', label: 'design', term: 2 },
+ ],
+ pheromones: [
+ { id: 'b', text: '[high] system: freeze the main branch', isLoud: true, arrivedAtMs: 50_000 },
+ { id: 'a', text: 'console-operator: standup in 5', isLoud: false, arrivedAtMs: 0 },
+ ],
+ keys: ['design-notes'],
+ }
+
+ it('draws the shield as f of n, and dim n/a where the strategy states no bound', () => {
+ expect(stillOf(stripPicture(model, 100, 0))).toMatch(/f 1 of 3/)
+ expect(stillOf(stripPicture({ ...model, shield: null, strategy: 'gossip' }, 100, 0))).toContain('f n/a')
+ })
+
+ it('marks the election and the dated decisions where their time falls, and the terms only the file records', () => {
+ const still = stillOf(stripPicture(model, 100, 0))
+
+ expect([axisAt(0, 0, 100, 11), axisAt(50, 0, 100, 11), axisAt(500, 0, 100, 11)]).toEqual([0, 5, 10])
+ expect(still).toContain('♛T2')
+ expect(still).toContain('T1')
+ expect(still).toContain('✔')
+ expect(still).toContain('◇')
+ })
+
+ it('slides a new pheromone in for two seconds, then holds still, at one size', () => {
+ expect(tickerShift(model.pheromones, 50_000)).toBe((model.pheromones[0]?.text.length ?? 0) + 5)
+ expect(tickerShift(model.pheromones, 51_000)).toBeGreaterThan(0)
+ expect(tickerShift(model.pheromones, 52_000)).toBe(0)
+ expect(stripPicture(model, 100, 51_000).encode()).not.toBe(stripPicture(model, 100, 60_000).encode())
+ expect(stripPicture(model, 100, 60_000).encode()).toBe(stripPicture(model, 100, 90_000).encode())
+ expect(stillOf(stripPicture(model, 100, 60_000))).toContain('[high] system: freeze the main branch ⬡ console-operator: standup in 5')
+ expect([0, 51_000].map(t => stripPicture(model, 100, t).rows)).toEqual([STRIP_ROWS, STRIP_ROWS])
+ })
+})
+
+describe('the empty comb', () => {
+ it('glows an egg in the centre cell, with no queen and no worker yet', () => {
+ const top = eggTopPicture(96)
+ const { x, y } = cellOrigin(0, 0, 96, EGG_TOP_ROWS)
+ const glyphs = new Set(stillOf(top).replace(/\s/g, ''))
+
+ expect([at(top, x + 3, y + 1), at(top, x + 3, y + 2), at(top, x + 3, y + 3)]).toEqual(['▄', '█', '▀'])
+ expect(bg(top, x + 3, y + 2)).not.toBe(DEFAULT)
+ expect([...glyphs].every(ch => '▁╱╲▄█▀'.includes(ch))).toBe(true)
+ expect([top.rows, eggBottomPicture(96).rows]).toEqual([EGG_TOP_ROWS, EGG_BOTTOM_ROWS])
+ })
+})
+
+describe('stills for review', () => {
+ it('records each state as text', () => {
+ const busy: HivePictureModel = {
+ queen: { tag: 'T2', isKnown: true },
+ members: [
+ ...cellModel(9).members.map((cell, i) => ({ ...cell, vote: i % 3 === 0 ? ('for' as const) : i % 3 === 1 ? ('against' as const) : ('pending' as const) })),
+ { id: 'bad', role: 'worker', glow: 'error', tag: 'e5f6', isByzantine: true },
+ { id: 'lost', role: 'unknown', glow: 'unknown', tag: 'zz99' },
+ ],
+ scars: [
+ { label: 'naming', isPassed: true },
+ { label: 'budget', isPassed: false },
+ ],
+ }
+ const waving = { ...busy, members: busy.members.map((cell, i) => (i === 7 ? { ...cell, wave: { kind: 'against' as const, atMs: 0 } } : cell)) }
+ const stills = {
+ 'empty comb (egg + start buttons between)': `${stillOf(eggTopPicture(96))}\n [▸ start a hive-mind (raft)] [▸ spawn 3 hive workers]\n${stillOf(eggBottomPicture(96))}`,
+ 'a queen and three workers': stillOf(hivePicture(cellModel(3), 96, 0)),
+ 'a busy hive: ballots, a byzantine voter, scars, a wave mid-flight at 900 ms': stillOf(hivePicture(waving, 110, 900)),
+ 'voting chambers': stillOf(chambersPicture([{ label: 'design', note: 'raft T2 · timed out', votesFor: 1, votesAgainst: 0, required: 2, nodes: 3, ballots: [{ tag: 'a1b2', isFor: true }], byzantine: [], isPicked: true }, { label: 'deploy', note: 'bft', votesFor: 0, votesAgainst: 1, required: 3, nodes: 3, ballots: [{ tag: 'c3d4', isFor: false }], byzantine: ['e5f6'], isPicked: false }], 110, 0)),
+ }
- 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}`))
+ for (const [name, still] of Object.entries(stills)) console.log(`── ${name} ──\n${still}\n`)
- 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())
+ expect(Object.values(stills).every(still => still.length > 0)).toBe(true)
})
})
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index 39a1187e2b..fab74b71ef 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -78,13 +78,17 @@ describe('views', () => {
})
test('hive: the honeycomb, quorum and fault tolerance, proposals, workers, decisions, broadcasts, no token', { options: { boot: false } }, async ($, on) => {
- worldOf(on, HIVE_FILES)
+ const world = worldOf(on, HIVE_FILES)
mock.clock(on)
await $.session.start(SESSION)
const { text, rasters, tree } = await drawn($, 'hive')
- expect(rasters).toEqual(['header', 'title', 'hive'])
+ // The comb, a chamber per open proposal, and the strip (shield, terms, pheromones); nothing asked, nothing run.
+ expect(rasters).toEqual(['header', 'title', 'hive', 'hive-chambers', 'hive-strip'])
+ expect(text).toContain('3 in the comb · 1 byzantine')
+ expect(text).toMatch(/voting chambers/i)
+ expect(world.runs.filter(argv => argv.includes('hive-mind') || argv.some(arg => arg.startsWith('hive-mind_')))).toEqual([])
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)')
@@ -101,6 +105,25 @@ describe('views', () => {
expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['hive-vote-yes', 'hive-vote-no', 'hive-spawn-worker']))
})
+ test('hive: with no hive, an empty comb with its egg holds the start buttons, and nothing runs unasked', { options: { boot: false } }, async ($, on) => {
+ const files = Object.fromEntries(Object.entries(HIVE_FILES).filter(([path]) => !path.startsWith('.claude-flow/hive-mind/')))
+ const world = worldOf(on, files)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const { text, rasters, tree } = await drawn($, 'hive')
+
+ expect(rasters).toEqual(['header', 'title', 'hive-egg', 'hive-egg-base'])
+ expect(text).toContain('the comb is empty · the egg is where the queen will sit')
+ expect(elementsOf(tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['start-hive', 'start-hive-workers']))
+
+ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })
+
+ await pane.press({ key: 'start-hive' })
+ await pane.unmount()
+ expect(world.runs.filter(argv => argv.includes('hive-mind'))).toEqual([])
+ })
+
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)