🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(console): show times as times, a swarm's own agents, and labels that match the gate
Dragan Spiridonov3c3ed992d0c5
diff --git a/plugins/ruflo-console/hooks/data/agentdb-mod.ts b/plugins/ruflo-console/hooks/data/agentdb-mod.tsindex c0fbb7d460..6efd3630cc 100644--- a/plugins/ruflo-console/hooks/data/agentdb-mod.ts+++ b/plugins/ruflo-console/hooks/data/agentdb-mod.ts@@ -1,5 +1,5 @@import { jsonObject, plain, recordOf } from './parse'-import { countOf } from './safe'+import { countOf, timeOf } from './safe'/** What the ruflo-agentdb mod last wrote to `.claude-flow/agentdb-mod/status.json` (ADR-445): its settings, counters and the last items it attached. */export type AgentdbMod = {@@ -7,7 +7,8 @@ export type AgentdbMod = {guard: booleansource: stringtool: string | null- updatedMs: number+ /** Epoch ms of the last write, or null when missing or not a time `Date` holds (never a count: a count is capped at 1e12, which turned a 2026 stamp into 2001). */+ updatedMs: number | nullattached: numberskipped: numbercached: number@@ -38,7 +39,7 @@ export function parseAgentdbMod(text: string | null): AgentdbMod | null {guard: value.guard === true,source: typeof value.source === 'string' ? plain(value.source, 16) : 'auto',tool: typeof value.lastTool === 'string' ? plain(value.lastTool, 24) : null,- updatedMs: whole(value.updatedMs),+ updatedMs: timeOf(value.updatedMs) ?? null,attached: whole(value.attached),skipped: whole(value.skipped),cached: whole(value.cached),diff --git a/plugins/ruflo-console/hooks/data/parse.ts b/plugins/ruflo-console/hooks/data/parse.tsindex 4167632288..a0063ba215 100644--- a/plugins/ruflo-console/hooks/data/parse.ts+++ b/plugins/ruflo-console/hooks/data/parse.ts@@ -179,7 +179,8 @@ export function parseSwarmStore(text: string | null): SwarmInfo | null {return [info]})- const byRecency = (a: SwarmInfo, b: SwarmInfo) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')+ // By instant, not text: "…T10:00+02:00" is older than "…T09:00Z" though it sorts after it as a string. Unparseable sorts last.+ const byRecency = (a: SwarmInfo, b: SwarmInfo) => (msOf(b.updatedAt) ?? -Infinity) - (msOf(a.updatedAt) ?? -Infinity) || 0return [...swarms.filter(swarm => swarm.status === 'running')].sort(byRecency)[0] ?? [...swarms].sort(byRecency)[0] ?? null}diff --git a/plugins/ruflo-console/hooks/data/safe.ts b/plugins/ruflo-console/hooks/data/safe.tsindex 6b1960f0d8..a28fdeee6f 100644--- a/plugins/ruflo-console/hooks/data/safe.ts+++ b/plugins/ruflo-console/hooks/data/safe.ts@@ -22,3 +22,15 @@ export const ratioOf = (value: unknown): number | undefined => (typeof value ===/** A value keyed by a name a file or the CLI supplied: an OWN key only, so `toString`, `constructor` or `__proto__` read as absent, never as a function. */export const own = <T>(record: Readonly<Record<string, T>>, key: unknown): T | undefined => (typeof key === 'string' && Object.hasOwn(record, key) ? record[key] : undefined)++/** 2000-01-01T00:00:00Z: no ruflo file was written before it. */+const EARLIEST_MS = 946_684_800_000+/** How far ahead of now a write time may be (a clock a little ahead) before it is not believed. */+const FUTURE_SLACK_MS = 86_400_000++/**+ * A write time fit to say "N ago" about: from 2000 to a day past now, else undefined (shown as n/a). timeOf alone admits ±8.64e15, which read+ * "100020735d ago", and a time in the future, which read "0s ago".+ */+export const sinceOf = (ms: number | null | undefined, nowMs: number): number | undefined =>+ typeof ms === 'number' && Number.isFinite(ms) && ms >= EARLIEST_MS && ms <= nowMs + FUTURE_SLACK_MS ? ms : undefineddiff --git a/plugins/ruflo-console/hooks/data/swarm-status.ts b/plugins/ruflo-console/hooks/data/swarm-status.tsnew file mode 100644index 0000000000..047e166dfc--- /dev/null+++ b/plugins/ruflo-console/hooks/data/swarm-status.ts@@ -0,0 +1,69 @@+import { msOf, type AgentRecord, type SwarmInfo } from './parse'+import { sinceOf } from './safe'++/** How long a "running" swarm may go with no sign of activity before it is called stale. */+export const SWARM_STALE_MS = 24 * 3_600_000++/** An agent status that means it is working now (the same words the Workflows roster reads as running). */+export const BUSY = /busy|active|running/i++export type SwarmStatus = {+ /** The status as the record wrote it. */+ status: string+ /** What to show: the status, or "stalled" for a stale "running" swarm. */+ shown: string+ /** When the record was last written; undefined when missing or not a believable time (sinceOf). */+ updatedMs: number | undefined+ isStale: boolean+ /** The agent ids the record lists, each once. */+ ids: string[]+ /** How many ids it lists, and how many of them the agent store holds. */+ listed: number+ found: number+ /** The listed agents the store holds, each once (the first record of an id wins). */+ members: AgentRecord[]+}++/** The agent store with each id once: the first record of an id wins, so a duplicated record is never counted twice. */+export function uniqueAgents(agents: readonly AgentRecord[]): AgentRecord[] {+ const seen = new Set<string>()++ return agents.filter(agent => !seen.has(agent.id) && seen.add(agent.id) !== undefined)+}++/**+ * The one reading of a swarm record that Overview, Swarm, the status bar, the topology graph and Workflows use: its status, when it was written,+ * whether a "running" swarm is stale, and its OWN agents: the ids it lists, each once. The agent store holds every agent ever spawned, in any+ * swarm, and is never this swarm's count (a 0-agent swarm once read "259 agents").+ *+ * Stale needs evidence of no activity, not just an old record: the CLI does not rewrite `updatedAt` when an agent is spawned or when the status+ * is read, so a healthy long-running swarm has an old record. A "running" swarm is stale only when its record is over a day old AND it has+ * members, none of them busy, and the newest of them was created over a day ago. With no member to judge by, it shows its age and is not called+ * stale.+ */+export function swarmStatusOf(swarm: SwarmInfo, nowMs: number, agents: readonly AgentRecord[]): SwarmStatus {+ const updatedMs = sinceOf(msOf(swarm.updatedAt), nowMs)+ const own = swarmMembersOf(swarm, agents)+ const newest = Math.max(...own.members.map(agent => sinceOf(agent.createdAtMs, nowMs) ?? Number.POSITIVE_INFINITY))+ const quiet = own.members.length > 0 && !own.members.some(agent => BUSY.test(agent.status)) && Number.isFinite(newest) && nowMs - newest > SWARM_STALE_MS+ const isStale = swarm.status === 'running' && updatedMs !== undefined && nowMs - updatedMs > SWARM_STALE_MS && quiet++ return { status: swarm.status, shown: isStale ? 'stalled' : swarm.status, updatedMs, isStale, ...own }+}++/** The swarm's own agents without a clock: the ids it lists, each once, how many of them the store holds, and those records. */+export function swarmMembersOf(swarm: SwarmInfo, agents: readonly AgentRecord[]): Pick<SwarmStatus, 'ids' | 'listed' | 'found' | 'members'> {+ const ids = [...new Set(swarm.agentIds)]+ const listed = new Set(ids)+ const members = uniqueAgents(agents).filter(agent => listed.has(agent.id))++ return { ids, listed: ids.length, found: members.length, members }+}++/** "2 agents", or "3 listed, 2 found" when the store lacks some of the listed ids. */+export const membersText = (status: Pick<SwarmStatus, 'listed' | 'found'>): string =>+ status.listed === status.found ? `${status.listed} agent${status.listed === 1 ? '' : 's'}` : `${status.listed} listed, ${status.found} found`++/** The record's status as a run state, so Workflows says what Overview says; null for a status it does not know. */+export const swarmRunState = (status: SwarmStatus): 'failed' | 'active' | 'stalled' | 'finished' | null =>+ /fail|error/i.test(status.status) ? 'failed' : /^running$|active/i.test(status.status) ? (status.isStale ? 'stalled' : 'active') : /terminat|stop|shut|complete|done|finish/i.test(status.status) ? 'finished' : nulldiff --git a/plugins/ruflo-console/hooks/data/wf-events.ts b/plugins/ruflo-console/hooks/data/wf-events.tsindex 778dc9b988..73b46653dc 100644--- a/plugins/ruflo-console/hooks/data/wf-events.ts+++ b/plugins/ruflo-console/hooks/data/wf-events.ts@@ -32,7 +32,8 @@ export function eventsBetween(prev: readonly WfRun[] | null, next: readonly WfRufor (const run of next) {const name = cleanText(run.name)- if (run.state === 'stalled' && before.has(run.id) && before.get(run.id) !== 'stalled') out.notices.push({ level: 'warn', text: `workflow ${name} looks stuck: nothing written for ${minutes} min`, key: `r-${tail(run.id)}-stuck`, go: 'workflows' })+ // A ruflo swarm's stall is its record's day-old write, not STALE_MS without a transcript line: no "N min" notice for it.+ if (run.kind === 'workflow' && run.state === 'stalled' && before.has(run.id) && before.get(run.id) !== 'stalled') out.notices.push({ level: 'warn', text: `workflow ${name} looks stuck: nothing written for ${minutes} min`, key: `r-${tail(run.id)}-stuck`, go: 'workflows' })for (const phase of run.phases) {for (const agent of phase.agents) {diff --git a/plugins/ruflo-console/hooks/data/wf-guide.ts b/plugins/ruflo-console/hooks/data/wf-guide.tsindex 6434106313..7cd1b09277 100644--- a/plugins/ruflo-console/hooks/data/wf-guide.ts+++ b/plugins/ruflo-console/hooks/data/wf-guide.ts@@ -17,6 +17,7 @@ import { cleanText } from './wf-clean'import { membersOf } from './hive'import type { AgentRecord, ClaimRecord, HiveAgentRecord, HiveInfo, SwarmInfo, TaskRecord } from './parse'import { idOf, plain } from './parse'+import { membersText, swarmMembersOf } from './swarm-status'import type { WfAgent, WfRun } from './workflows'export type NestKind = 'swarm' | 'hive' | 'queen' | 'worker' | 'claim' | 'task' | 'note'@@ -31,7 +32,7 @@ export function nestingOf(input: { swarm: SwarmInfo | null; hive: HiveInfo | nulconst { swarm, hive, agents, hiveAgents, claims, tasks } = inputconst rows: NestRow[] = []- rows.push(swarm === null ? { depth: 0, kind: 'note', label: 'no swarm', detail: 'swarm init has not run here' } : { depth: 0, kind: 'swarm', label: swarm.id, detail: `${swarm.topology}${swarm.strategy === undefined ? '' : ` · ${swarm.strategy}`} · ${swarm.status} · ${swarm.agentIds.length} agents` })+ rows.push(swarm === null ? { depth: 0, kind: 'note', label: 'no swarm', detail: 'swarm init has not run here' } : { depth: 0, kind: 'swarm', label: swarm.id, detail: `${swarm.topology}${swarm.strategy === undefined ? '' : ` · ${swarm.strategy}`} · ${swarm.status} · ${membersText(swarmMembersOf(swarm, agents))}` })if (hive === null) {rows.push({ depth: 1, kind: 'note', label: 'no hive-mind', detail: 'no queen and no workers: agents are not grouped under a hive' })diff --git a/plugins/ruflo-console/hooks/data/wf-swarm.ts b/plugins/ruflo-console/hooks/data/wf-swarm.tsnew file mode 100644index 0000000000..7461c3aef1--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-swarm.ts@@ -0,0 +1,66 @@+/**+ * ruflo's own agents as runs on the Workflows page (ADR-458): the swarm record as its own run, and the agents it does not list as a separate,+ * plainly named "ruflo agents on disk" run. A swarm is never credited with the agent store (every agent ever spawned, in any swarm).+ */+import { agentLabels, type AgentRecord, type SwarmInfo } from './parse'+import { swarmRunState, swarmStatusOf, uniqueAgents } from './swarm-status'+import { groupPhases, tally, type AgentState, type RunState, type WfAgent, type WfRun } from './workflows'++/**+ * The id of the run that holds the agents no swarm record lists. It is `ruflo-swarm`, the id this same roster had before swarms were split from+ * the store, so a drill or a pin saved on an older console (.claude-flow/console/wf-views.json) still finds it.+ */+export const RUFLO_AGENTS_ID = 'ruflo-swarm'++const RUFLO_STATE = (status: string): AgentState => (/error|fail/i.test(status) ? 'failed' : /busy|active|running/i.test(status) ? 'running' : /stop|terminat|offline/i.test(status) ? 'done' : 'idle')++/**+ * Agents as a run: its phases are the agent types (that is the only grouping the store has), a stopped agent counts as done, an idle one as+ * ready. ruflo records no model, tokens or worktree per agent, so those stay n/a.+ */+function rosterRun(id: string, name: string, records: readonly AgentRecord[], nowMs: number): WfRun {+ // A store that holds an id twice is one agent, not two (the first record wins, as in data/swarm-status.ts).+ const agents = uniqueAgents(records)+ const labels = agentLabels(agents)+ const rows: WfAgent[] = agents.map(agent => ({+ id: agent.id,+ label: labels.get(agent.id) ?? agent.type,+ phase: agent.type,+ state: RUFLO_STATE(agent.status),+ hasWorktree: false,+ ...(agent.createdAtMs !== undefined && { startedMs: agent.createdAtMs, elapsedMs: Math.max(0, nowMs - agent.createdAtMs) }),+ ruflo: agent,+ }))+ const counts = tally(rows)+ const state: RunState = counts.running > 0 ? 'active' : counts.failed > 0 ? 'failed' : 'finished'++ return { id, name, kind: 'ruflo-swarm', state, phases: groupPhases(rows, []), running: counts.running, done: counts.done, failed: counts.failed, idle: counts.idle, total: rows.length, totalTokens: null, isTokensPartial: false, hasRecord: false }+}++/**+ * The swarm record as a run, always (an empty swarm right after `swarm init` included): its own listed agents that the store holds, and the+ * record's status and age (data/swarm-status.ts), so Workflows says what Overview says. With no swarm record, the agents on disk, or null.+ */+export function swarmRun(swarm: SwarmInfo | null, agents: readonly AgentRecord[], nowMs: number): WfRun | null {+ if (swarm === null) return agents.length === 0 ? null : rosterRun(RUFLO_AGENTS_ID, 'ruflo agents on disk', agents, nowMs)++ const status = swarmStatusOf(swarm, nowMs, agents)+ const run = rosterRun(swarm.id, `ruflo swarm · ${swarm.topology}`, status.members, nowMs)++ return { ...run, state: swarmRunState(status) ?? run.state, isStale: status.isStale, listed: status.listed, ...(status.updatedMs !== undefined && { updatedMs: status.updatedMs }) }+}++/** Every ruflo run: the swarm (when there is a record), then the agents on disk that it does not list (when there are any). */+export function rufloRuns(swarm: SwarmInfo | null, agents: readonly AgentRecord[], nowMs: number): WfRun[] {+ const own = swarmRun(swarm, agents, nowMs)++ if (swarm === null) return own === null ? [] : [own]++ const listed = new Set(swarm.agentIds)+ const rest = agents.filter(agent => !listed.has(agent.id))++ return rest.length === 0 || own === null ? (own === null ? [] : [own]) : [own, rosterRun(RUFLO_AGENTS_ID, 'ruflo agents on disk', rest, nowMs)]+}++/** True while a run is live: a swarm run (the one with `listed`) by its record's state (a stale "running" one is stalled, not live), anything else by an agent running. */+export const isLiveRun = (run: WfRun): boolean => (run.kind === 'ruflo-swarm' && run.listed !== undefined ? run.state === 'active' : run.running > 0)diff --git a/plugins/ruflo-console/hooks/data/workflows-nav.ts b/plugins/ruflo-console/hooks/data/workflows-nav.tsindex 7496444123..8590c26671 100644--- a/plugins/ruflo-console/hooks/data/workflows-nav.ts+++ b/plugins/ruflo-console/hooks/data/workflows-nav.ts@@ -2,7 +2,8 @@* Where the cursor is in the workflows view, and how a key moves it (ADR-458). Pure, so the keys are tested without a* screen: j/k move within the focused column, h/l switch column, Enter inspects the row, [ and ] switch run.*/-import { currentPhase, swarmRun, type WfAgent, type WfPhase, type WfRun } from './workflows'+import { isLiveRun, rufloRuns } from './wf-swarm'+import { currentPhase, type WfAgent, type WfPhase, type WfRun } from './workflows'import type { AgentRecord, SwarmInfo } from './parse'export type WfColumn = 'phases' | 'agents'@@ -13,11 +14,10 @@ export const newWfUi = (): WfUi => ({ run: 0, phase: 0, agent: 0, column: 'phase/** Workflow runs and the ruflo swarm in one list: whatever is running first, the rest as they come (newest first). */export function allRuns(workflows: readonly WfRun[], swarm: SwarmInfo | null, agents: readonly AgentRecord[], nowMs: number): WfRun[] {- const own = swarmRun(swarm, agents, nowMs)- const runs = own === null ? [...workflows] : [...workflows, own]- const isLive = (run: WfRun) => run.running > 0+ const runs = [...workflows, ...rufloRuns(swarm, agents, nowMs)]- return [...runs.filter(isLive), ...runs.filter(run => !isLive(run))]+ // A swarm is live by its record's state (data/swarm-status.ts): a stale "running" record ranks with the finished runs.+ return [...runs.filter(isLiveRun), ...runs.filter(run => !isLiveRun(run))]}const clamp = (value: number, size: number): number => (size <= 0 ? 0 : Math.max(0, Math.min(size - 1, value)))diff --git a/plugins/ruflo-console/hooks/data/workflows.ts b/plugins/ruflo-console/hooks/data/workflows.tsindex 088fdee105..db092efd0b 100644--- a/plugins/ruflo-console/hooks/data/workflows.ts+++ b/plugins/ruflo-console/hooks/data/workflows.ts@@ -11,7 +11,7 @@* Unknown event types and keys are ignored, a half-written last line is dropped, and a missing source is a missing fact:* nothing here is estimated.*/-import { agentLabels, ESCAPES, HIDDEN, INVISIBLE, shortId, type AgentRecord, type SwarmInfo } from './parse'+import { ESCAPES, HIDDEN, INVISIBLE, shortId, type AgentRecord } from './parse'export type AgentState = 'running' | 'done' | 'failed' | 'stale' | 'idle' | 'queued'@@ -61,6 +61,10 @@ export type WfRun = {dir?: string/** True where the run record's `workflowProgress` gave the figures (a finished run), false where they were derived from journal and transcripts. */hasRecord: boolean+ /** A ruflo swarm run only (data/wf-swarm.ts): when its record was last written, whether a "running" one has gone stale, how many ids it lists. */+ updatedMs?: number+ isStale?: boolean+ listed?: number}const asRecord = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)@@ -380,7 +384,7 @@ export function buildRun(input: RunInput): WfRun {const lastEnd = (agents: readonly WfAgent[], fallback: number): number => agents.reduce((latest, agent) => (agent.startedMs !== undefined && agent.elapsedMs !== undefined ? Math.max(latest, agent.startedMs + agent.elapsedMs) : latest), fallback)-function tally(agents: readonly WfAgent[]): Record<AgentState, number> {+export function tally(agents: readonly WfAgent[]): Record<AgentState, number> {const counts: Record<AgentState, number> = { running: 0, done: 0, failed: 0, stale: 0, idle: 0, queued: 0 }for (const agent of agents) counts[agent.state] += 1@@ -413,44 +417,6 @@ export function currentPhase(phases: readonly WfPhase[]): number | null {return open >= 0 ? open : null}-const RUFLO_STATE = (status: string): AgentState => (/error|fail/i.test(status) ? 'failed' : /busy|active|running/i.test(status) ? 'running' : /stop|terminat|offline/i.test(status) ? 'done' : 'idle')--/**- * The ruflo swarm as one more run: its phases are the agent types (that is the only grouping the store has), a stopped agent- * counts as done, an idle one as ready. ruflo records no model, tokens or worktree per agent, so those stay n/a.- */-export function swarmRun(swarm: SwarmInfo | null, agents: readonly AgentRecord[], nowMs: number): WfRun | null {- if (swarm === null && agents.length === 0) return null-- const labels = agentLabels(agents)- const rows: WfAgent[] = agents.map(agent => ({- id: agent.id,- label: labels.get(agent.id) ?? agent.type,- phase: agent.type,- state: RUFLO_STATE(agent.status),- hasWorktree: false,- ...(agent.createdAtMs !== undefined && { startedMs: agent.createdAtMs, elapsedMs: Math.max(0, nowMs - agent.createdAtMs) }),- ruflo: agent,- }))- const counts = tally(rows)-- return {- id: swarm?.id ?? 'ruflo-swarm',- name: `ruflo swarm${swarm === null ? '' : ` · ${swarm.topology}`}`,- kind: 'ruflo-swarm',- state: counts.running > 0 ? 'active' : counts.failed > 0 ? 'failed' : 'finished',- phases: groupPhases(rows, []),- running: counts.running,- done: counts.done,- failed: counts.failed,- idle: counts.idle,- total: rows.length,- totalTokens: null,- isTokensPartial: false,- hasRecord: false,- }-}-/** 145.4k · 1.2M · 812 */export function fmtTokens(tokens: number | undefined, isPartial = false): string {if (tokens === undefined) return 'n/a'@@ -460,12 +426,14 @@ export function fmtTokens(tokens: number | undefined, isPartial = false): stringreturn `${isPartial ? '≥' : ''}${text}`}-/** 15s · 3m12s · 1h05m */+/** 15s · 3m12s · 1h05m · 68d06h (a day or more reads in days, as ago() does: never "1638h18m") */export function fmtElapsed(ms: number | undefined): string {if (ms === undefined) return 'n/a'const s = Math.round(ms / 1000)+ if (s >= 86_400) return `${Math.floor(s / 86_400)}d${String(Math.floor((s % 86_400) / 3600)).padStart(2, '0')}h`+return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`}diff --git a/plugins/ruflo-console/hooks/mission-palette.ts b/plugins/ruflo-console/hooks/mission-palette.tsindex 9a1d2b4b8b..b83ee8f88c 100644--- a/plugins/ruflo-console/hooks/mission-palette.ts+++ b/plugins/ruflo-console/hooks/mission-palette.ts@@ -30,7 +30,9 @@ export function missionPalette(state: State): PaletteEntry[] {const tasks = () => state.snapshot?.tasks ?? []return [- { id: 'mission-goal', group: 'missions', label: 'mission-goal <goal>: plan a goal as a SPARC goal-oriented plan (nothing is written)', run: text('mission-goal', value => local('plan the goal', () => planGoal(state, value, wired), 'write')) },+ // Declared 'write', like console_set goal: it REPLACES Mission Control's goal and plan (in memory: no file, no mission). The label says so+ // rather than "nothing is written", which contradicted the gate asking for write control.+ { id: 'mission-goal', group: 'missions', label: 'mission-goal <goal>: set the goal and plan it as a SPARC goal-oriented plan (replaces the current goal; no file, no mission yet)', run: text('mission-goal', value => local('plan the goal', () => planGoal(state, value, wired), 'write')) },{ id: 'mission-status', group: 'missions', label: 'mission status: progress, each task’s status, what is next', run: spec(() => local('mission status', () => undefined)) },{ id: 'mission-create', group: 'missions', label: 'create the mission and its tasks from the planned goal (asks first)', run: { kind: 'spec' as const, spec: wired === undefined || blocksCreate(mcOf(state).screen) ? null : createSpec(state, wired.host, () => undefined), why: createWhy(state) ?? why } },{diff --git a/plugins/ruflo-console/hooks/optimizer.ts b/plugins/ruflo-console/hooks/optimizer.tsindex 5cdd013212..72c2da23f5 100644--- a/plugins/ruflo-console/hooks/optimizer.ts+++ b/plugins/ruflo-console/hooks/optimizer.ts@@ -104,7 +104,7 @@ export function diagnose(state: State, nowMs: number, loadedAtMs: number): Findi}// ---- performance- out.push({ id: 'performance-unprofiled', area: 'performance', level: 'info', title: 'where the time goes has not been measured', why: 'find the bottleneck before optimising: a read shows it, and optimise applies ruflo’s own suggestions.', metric: 'bottlenecks n/a', fixes: [fix('perf-bottleneck', 'find bottlenecks', 'safe', 'a read'), fix('perf-optimize', 'optimise', 'balanced', 'local; applies ruflo’s suggested settings')] })+ out.push({ id: 'performance-unprofiled', area: 'performance', level: 'info', title: 'where the time goes has not been measured', why: 'find the bottleneck before optimising: a local measurement shows it, and optimise applies ruflo’s own suggestions.', metric: 'bottlenecks n/a', fixes: [fix('perf-bottleneck', 'find bottlenecks', 'safe', 'local measurement; writes a temporary probe file, so Claude needs write control'), fix('perf-optimize', 'optimise', 'balanced', 'local; applies ruflo’s suggested settings')] })// ---- health and the install (what the console already raises as alerts)for (const alert of alertsOf(state, nowMs, loadedAtMs)) {diff --git a/plugins/ruflo-console/hooks/perf.ts b/plugins/ruflo-console/hooks/perf.tsindex a74d2f7e51..c9d60a4f99 100644--- a/plugins/ruflo-console/hooks/perf.ts+++ b/plugins/ruflo-console/hooks/perf.ts@@ -127,7 +127,9 @@ export const reportReader: Reader = (stdout, stderr, state) => {}const LOCAL = '$0, local: measures in-process and writes nothing'-const PROBE = '$0, local: writes and removes a 4 KB probe file in .claude-flow/performance/'+// The note is read by Claude's gate (model-tools.ts classOf): it must name what the entry does in words that do not read as a delete. The probe+// file is the tool's own scratch, gone when it returns; "removes" here made the gate call these delete actions needing 'full' (they write locally).+const PROBE = '$0, local: writes a temporary 4 KB probe file in .claude-flow/performance/ (it does not stay)'export const PERF: readonly PerfEntry[] = [{ id: 'perf-metrics', name: 'METRICS', about: 'heap, rss, load and event-loop latency, now', label: 'performance metrics: memory, load and latency now', cost: 'read', args: ['performance', 'metrics', '--format', 'json'], read: metricsReader, note: LOCAL },diff --git a/plugins/ruflo-console/hooks/views/agentdb-mod.ts b/plugins/ruflo-console/hooks/views/agentdb-mod.tsindex ccda930dd5..121c5f377d 100644--- a/plugins/ruflo-console/hooks/views/agentdb-mod.ts+++ b/plugins/ruflo-console/hooks/views/agentdb-mod.ts@@ -1,5 +1,6 @@import type { RenderElement } from 'claude-code'+import { sinceOf } from '../data/safe'import { ago, count, kv, rule, text, THEME, type Ctx } from './common'const PLUGIN = 'ruflo-agentdb'@@ -33,12 +34,14 @@ export function agentdbModRows(ctx: Ctx): RenderElement[] {return rows}- const stale = ctx.nowMs - mod.updatedMs > STALE_MS+ // A time from before 2000 or more than a day ahead is not believed: n/a, never "100020735d ago" or "0s ago".+ const writtenMs = sinceOf(mod.updatedMs, ctx.nowMs)+ const stale = writtenMs !== undefined && ctx.nowMs - writtenMs > STALE_MSrows.push(kv(ctx, 'recall', mod.recall ? `on · ${mod.source}${mod.tool !== null ? ` · via ${mod.tool}` : ''}` : 'off (a plugin option: attaches the best few memories to each prompt as retrieved data)', mod.recall ? THEME.ok : undefined))rows.push(kv(ctx, 'secret guard', mod.guard ? 'on · memory writes holding a key, token or password are refused' : 'off', mod.guard ? THEME.ok : THEME.warn))rows.push(kv(ctx, 'attached', `${count(mod.attached)} · ${count(mod.cached)} from cache · ${count(mod.skipped)} skipped · ${count(mod.timedOut)} timed out${mod.lastMs === null ? '' : ` · last ${mod.lastMs} ms`}`))rows.push(kv(ctx, 'refused', `${count(mod.dropped)} memories dropped as unsafe · ${count(mod.blocked)} writes blocked${mod.errors > 0 ? ` · ${count(mod.errors)} errors` : ''}`, mod.dropped + mod.blocked > 0 ? THEME.warn : undefined))- rows.push(text(ctx, ` written ${ago(mod.updatedMs, ctx.nowMs)}${stale ? ' (an earlier session)' : ''} · /agentdb-mod status|recall|scan|recent`, { dimColor: true }))+ rows.push(text(ctx, ` written ${writtenMs === undefined ? 'n/a' : ago(writtenMs, ctx.nowMs)}${stale ? ' (an earlier session)' : ''} · /agentdb-mod status|recall|scan|recent`, { dimColor: true }))for (const item of mod.recent) {rows.push(text(ctx, ` ◆ ${item.snippet.slice(0, Math.max(20, ctx.columns - 30))} [${item.source}${item.score === null ? '' : ` ${item.score.toFixed(2)}`}]`, { color: THEME.info }))diff --git a/plugins/ruflo-console/hooks/views/bar.ts b/plugins/ruflo-console/hooks/views/bar.tsindex 5a9095ade9..7350ac3476 100644--- a/plugins/ruflo-console/hooks/views/bar.ts+++ b/plugins/ruflo-console/hooks/views/bar.ts@@ -10,6 +10,7 @@ import type { RenderElement } from 'claude-code'import { alertsOf, waitingApprovalsOf } from '../data/alerts'import { agentLabels } from '../data/parse'+import { swarmStatusOf } from '../data/swarm-status'import { secMemo } from '../secure'import type { State, ViewId } from '../state'import { sparkline } from '../memory-lines'@@ -139,9 +140,12 @@ export function barParts(state: State, nowMs: number = Date.now()): BarPart[] {// Nothing moving: say so, with how many agents stand ready. (When something did happen, the last event is a standing part below.)if (!parts.some(part => part.tone === 'live') && !isFresh && snap?.swarm != null) {- const ready = snap.agents.length+ // The swarm's own members (data/swarm-status.ts), not the agent store (every agent ever spawned, in any swarm). Only an agent the store+ // holds can be "ready": a listed id it lacks is counted as listed, never as ready.+ const { listed, found } = swarmStatusOf(snap.swarm, nowMs, snap.agents)+ const note = listed === found ? '' : ` (${listed} listed, ${found} found)`- parts.push({ text: ready > 0 ? `idle · ${ready} agent${ready === 1 ? '' : 's'} ready` : 'swarm, no agents', tone: 'plain', go: 'swarm' })+ parts.push({ text: found > 0 ? `idle · ${found} agent${found === 1 ? '' : 's'} ready${note}` : listed > 0 ? `swarm, ${listed} listed, none found` : 'swarm, no agents', tone: 'plain', go: 'swarm' })}// Standing context, on its own row: the last tool call or event with how long ago (it used to vanish after a minute, taking what Claudediff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.tsindex 52602696e7..27af26b495 100644--- a/plugins/ruflo-console/hooks/views/frames.ts+++ b/plugins/ruflo-console/hooks/views/frames.ts@@ -6,6 +6,7 @@import type { AuditTrend, HarnessScore, Intelligence } from '../data/cli'import { recentByAgent } from '../data/events'import { agentLabels } from '../data/parse'+import { swarmStatusOf } from '../data/swarm-status'import { getBootChecks } from '../boot-checks'import { bootFacts } from '../boot-facts'import { getBuild } from '../build'@@ -40,12 +41,14 @@ import { watchOf } from '../watch'const AXIS: Record<string, string> = { harnessFit: 'fit', compileConfidence: 'compile', taskCoverage: 'coverage', toolSafety: 'safety', memoryUsefulness: 'memory' }/** The swarm as a graph: the hive's queen leads where there is one, else the swarm itself stands at the root. */-export function topoModelOf(snapshot: Snapshot | null, pulses: Map<string, number> = new Map()): TopoModel | null {+export function topoModelOf(snapshot: Snapshot | null, pulses: Map<string, number> = new Map(), nowMs: number = Date.now()): TopoModel | null {const swarm = snapshot?.swarm ?? nullif (snapshot === null || (swarm === null && snapshot.hive === null && snapshot.agents.length === 0)) return null- const members = swarm !== null && swarm.agentIds.length > 0 ? snapshot.agents.filter(agent => swarm.agentIds.includes(agent.id)) : snapshot.agents+ // A swarm's members are the ids its record lists, even none: the agent store holds every agent ever spawned and is not this swarm.+ const status = swarm === null ? null : swarmStatusOf(swarm, nowMs, snapshot.agents)+ const members = status !== null ? snapshot.agents.filter(agent => status.ids.includes(agent.id)) : snapshot.agentsconst labels = agentLabels(snapshot.agents)const leaderId = snapshot.hive?.queen ?? swarm?.id ?? 'swarm'const leaderPulse = pulses.get(leaderId)@@ -53,7 +56,7 @@ export function topoModelOf(snapshot: Snapshot | null, pulses: Map<string, numbereturn {topology: swarm?.topology ?? snapshot.hive?.topology ?? 'hierarchical',nodes: [- { id: leaderId, label: snapshot.hive?.queen !== undefined ? 'queen' : 'swarm', status: snapshot.hive?.queen !== undefined ? 'leader' : (swarm?.status ?? 'unknown'), isLeader: true, ...(leaderPulse !== undefined && { pulseAtMs: leaderPulse }) },+ { id: leaderId, label: snapshot.hive?.queen !== undefined ? 'queen' : 'swarm', status: snapshot.hive?.queen !== undefined ? 'leader' : (status?.shown ?? 'unknown'), isLeader: true, ...(leaderPulse !== undefined && { pulseAtMs: leaderPulse }) },...members.slice(0, MAX_NODES - 1).map(agent => {const pulseAtMs = pulses.get(agent.id)@@ -195,7 +198,7 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numbpictures.set('activity', activityPicture([{ label: 'tool calls/5s', values: state.activity }, { label: 'state writes', values: state.writes }], width, t))breakcase 'swarm': {- const model = topoModelOf(snapshot, recentByAgent(state.events, nowMs, PULSE_MS + 600))+ const model = topoModelOf(snapshot, recentByAgent(state.events, nowMs, PULSE_MS + 600), nowMs)if (model !== null) pictures.set('topology', topologyPicture(model, width, topologyRows(width, model.nodes.length), t))breakdiff --git a/plugins/ruflo-console/hooks/views/overview.ts b/plugins/ruflo-console/hooks/views/overview.tsindex d2274c2170..f5811dfd8f 100644--- a/plugins/ruflo-console/hooks/views/overview.ts+++ b/plugins/ruflo-console/hooks/views/overview.ts@@ -5,6 +5,8 @@ import type { MemoryStats } from '../data/cli'import type { StartId } from '../starts'import { controlRows, isControlActive } from './control'import { optimizerRows } from './optimizer'+import { uniqueAgents } from '../data/swarm-status'+import { onDisk, swarmFacts } from './swarm'import { ago, button, col, count, kv, live, row, picture, rule, sourceLine, starts, text, THEME, type Ctx } from './common'/** Each subsystem in one line: what it is, from where, as of when. Nothing on this view is estimated. */@@ -75,7 +77,11 @@ export function overviewView(ctx: Ctx): RenderElement {rows.push(kv(ctx, 'mods reporting', modsSeen.length === 0 ? 'none yet' : `${modsSeen.length}${modsBlocked > 0 ? ` · ${modsBlocked} blocked something` : ''}`, modsBlocked > 0 ? THEME.warn : undefined))rows.push(row(ctx, [button(ctx, 'overview-mods', 'The Room: Mods', () => ctx.act.view('room'))], 'overview-mods-row'))- rows.push(kv(ctx, 'swarm', swarm === null ? 'n/a — no swarm on disk' : `${swarm.id} · ${swarm.topology} · ${swarm.status} · ${swarm.agentIds.length || (snap?.agents.length ?? 0)} agents`))+ // The swarm's own count, never the agent store's: the store holds every agent ever spawned, so a 0-agent swarm once read "259 agents".+ const facts = swarm === null ? null : swarmFacts(swarm, nowMs, snap?.agents ?? [])+ const stored = uniqueAgents(snap?.agents ?? []).length++ rows.push(kv(ctx, 'swarm', swarm === null || facts === null ? 'n/a — no swarm on disk' : `${swarm.id} · ${swarm.topology} · ${swarm.status} · ${facts.text}${stored > 0 ? ` · ${onDisk(stored)}` : ''}`, facts?.isStale === true ? THEME.warn : undefined))// What is missing here, each with the button that adds it, most basic first.const missing: StartId[] = []diff --git a/plugins/ruflo-console/hooks/views/swarm.ts b/plugins/ruflo-console/hooks/views/swarm.tsindex 161838655c..9f8192c0d9 100644--- a/plugins/ruflo-console/hooks/views/swarm.ts+++ b/plugins/ruflo-console/hooks/views/swarm.ts@@ -1,12 +1,27 @@import type { RenderElement } from 'claude-code'-import { agentLabels, shortId } from '../data/parse'-import { button, clip, col, kv, picture, row, rule, starts, text, THEME, type Ctx } from './common'+import { agentLabels, shortId, type AgentRecord, type SwarmInfo } from '../data/parse'+import { membersText, swarmStatusOf } from '../data/swarm-status'+import { ago, button, clip, col, kv, picture, row, rule, starts, text, THEME, type Ctx } from './common'import { selection } from './select'const STATUS_COLOR = (status: string): string | undefined =>/busy|active|running/i.test(status) ? THEME.warn : /error|fail/i.test(status) ? THEME.bad : /stop|terminat|offline/i.test(status) ? undefined : THEME.info+/** The swarm's own facts in words (data/swarm-status.ts): its agents, its cap, when its record was last written, and "stale". */+export function swarmFacts(swarm: SwarmInfo, nowMs: number, agents: readonly AgentRecord[]): { text: string; isStale: boolean; found: number } {+ const status = swarmStatusOf(swarm, nowMs, agents)++ return {+ text: `${membersText(status)}${swarm.maxAgents !== undefined ? ` · max ${swarm.maxAgents}` : ''} · updated ${status.updatedMs === undefined ? 'n/a' : ago(status.updatedMs, nowMs)}${status.isStale ? ' · stale' : ''}`,+ isStale: status.isStale,+ found: status.found,+ }+}++/** The agent store as what it is: every agent on disk, not the swarm's members. */+export const onDisk = (n: number): string => `${n} agent${n === 1 ? '' : 's'} on disk`+/*** The swarm as ruflo wrote it: a graph of its members with the leader marked, the agents (pick one with j/k, open it* with d), and the hive's votes. The tile board is ruflo-swarm's pane (/ruflo swarm pane); this view does not redraw it.@@ -27,10 +42,13 @@ export function swarmView(ctx: Ctx): RenderElement {return col(ctx, rows, 'swarm')}- rows.push(kv(ctx, 'topology', swarm === null ? `${hive?.topology ?? 'n/a'} (hive-mind)` : `${swarm.topology}${swarm.strategy !== undefined ? ` · ${swarm.strategy}` : ''} · ${swarm.status}${swarm.maxAgents !== undefined ? ` · max ${swarm.maxAgents}` : ''}`))- rows.push(picture(ctx, 'topology', `graph needs a terminal: ${agents.length} agents`))+ const facts = swarm === null ? null : swarmFacts(swarm, ctx.nowMs, agents)++ rows.push(kv(ctx, 'topology', swarm === null || facts === null ? `${hive?.topology ?? 'n/a'} (hive-mind)` : `${swarm.topology}${swarm.strategy !== undefined ? ` · ${swarm.strategy}` : ''} · ${swarm.status} · ${facts.text}`, facts?.isStale === true ? THEME.warn : undefined))+ // The graph draws the swarm's own members (frames.ts topoModelOf); with no swarm record it draws the agents on disk.+ rows.push(picture(ctx, 'topology', `graph needs a terminal: ${swarm === null ? onDisk(agents.length) : `${facts?.found ?? 0} swarm member${facts?.found === 1 ? '' : 's'}`}`))rows.push(text(ctx, '★ leader · ◉ busy (a dot runs to it while it works) · ● idle · grey stopped · a white flash = an event about that agent', { dimColor: true }))- rows.push(rule(ctx, 'Agents', `${agents.length} · j/k pick · d open · x actions`))+ rows.push(rule(ctx, 'Agents', `${onDisk(agents.length)} (every swarm) · j/k pick · d open · x actions`))const labels = agentLabels(agents)// The type column only earns its room when some agent has a name that is not its type.const hasTypes = agents.some(agent => agent.name !== undefined && agent.name !== agent.type)diff --git a/plugins/ruflo-console/hooks/views/workflows.ts b/plugins/ruflo-console/hooks/views/workflows.tsindex c88f5938ba..03f1396ab3 100644--- a/plugins/ruflo-console/hooks/views/workflows.ts+++ b/plugins/ruflo-console/hooks/views/workflows.ts@@ -5,7 +5,7 @@ import { fmtElapsed, fmtTokens, modelName, currentPhase, type AgentState, type Wimport { pick, type WfUi } from '../data/workflows-nav'import { CONTROL_TAB, controlLine } from '../data/wf-control'import { spawnAgent, stopAgent } from '../ops'-import { clip, col, kv, row, rule, text, THEME, type Ctx } from './common'+import { ago, clip, col, kv, row, rule, text, THEME, type Ctx } from './common'import { flow, runTag } from './wf-layout'import { slotsFor } from './wf-slots'@@ -37,7 +37,13 @@ const mb = (bytes: number): string => `${(bytes / 1_000_000).toFixed(1)} MB`function header(ctx: Ctx, run: WfRun, runs: readonly WfRun[], at: number): RenderElement[] {const tone = run.state === 'failed' ? THEME.bad : run.running > 0 || run.state === 'active' ? THEME.warn : run.state === 'completed' ? THEME.ok : undefinedconst counts = run.kind === 'ruflo-swarm' ? `${run.running} busy · ${run.idle} idle · ${run.done} stopped · ${run.failed} failed` : `${run.running} running · ${run.done} done · ${run.failed} failed`- const tokens = run.totalTokens === null ? 'tokens n/a' : `${fmtTokens(run.totalTokens, run.isTokensPartial)} tok`+ // ruflo records no tokens: a swarm run says when its record was written instead (the same words as Overview and Swarm).+ const listed = run.listed !== undefined && run.listed !== run.total ? ` · ${run.listed} listed, ${run.total} found` : ''+ const tokens =+ run.kind !== 'ruflo-swarm'+ ? run.totalTokens === null ? 'tokens n/a' : `${fmtTokens(run.totalTokens, run.isTokensPartial)} tok`+ : run.listed === undefined ? 'agents ruflo recorded that no swarm record lists'+ : `updated ${run.updatedMs === undefined ? 'n/a' : ago(run.updatedMs, ctx.nowMs)}${run.isStale === true ? ' · stale' : ''}${listed}`const span = run.durationMs === undefined ? '' : ` · ${fmtElapsed(run.durationMs)}`const tabs = runs.length > 1 ? runs.map((entry, i) => `${i === at ? '▸' : ' '}${i + 1} ${clip(entry.name, 18)}`).join(' ') : ''@@ -64,7 +70,8 @@ function phaseCell(ctx: Ctx, phase: WfPhase, index: number, flags: { isHere: boo/** Right cell: status mark, label, model, worktree badge, tokens, elapsed. A narrow screen drops the model, then the badge. */function agentCell(ctx: Ctx, agent: WfAgent, isHere: boolean, width: number): RenderElement {- const tail = `${fmtTokens(agent.tokens, agent.isTokensPartial)} tok`.padStart(10) + fmtElapsed(agent.elapsedMs).padStart(7)+ // A space between the two columns: an age wider than its column ("68d06h", once "1638h18m") ran into "n/a tok".+ const tail = `${`${fmtTokens(agent.tokens, agent.isTokensPartial)} tok`.padStart(10)} ${fmtElapsed(agent.elapsedMs).padStart(6)}`const model = agent.ruflo === undefined ? modelName(agent.model).padEnd(11) : ''const badge = agent.hasWorktree ? 'worktree '.padEnd(10) : agent.ruflo === undefined ? ' '.repeat(10) : ''const fixed = 3 + tail.length + (width >= 62 ? model.length : 0) + (width >= 74 ? badge.length : 0)diff --git a/plugins/ruflo-console/tests/display-truth.spec.ts b/plugins/ruflo-console/tests/display-truth.spec.tsnew file mode 100644index 0000000000..1ac5684bf7--- /dev/null+++ b/plugins/ruflo-console/tests/display-truth.spec.ts@@ -0,0 +1,216 @@+/**+ * What the console shows matches what is on disk and what the gate does (seen live 2026-10-09):+ * - an epoch-ms stamp is read as a time, never through the 1e12 count cap (agentdb-mod "written 9161d ago" for a file minutes old);+ * - a swarm's agent count is its own, never the agent store's (a 0-agent swarm read "running · 259 agents"), with the record's age;+ * - a palette entry's words agree with the control level Claude's gate asks for (mission-goal "nothing is written" yet gated as a write;+ * perf-bottleneck gated as a delete because its note said "removes").+ * npx vitest run plugins/ruflo-console/tests/display-truth.spec.ts+ */+import { describe, expect, it } from 'vitest'++import { parseAgentdbMod } from '../hooks/data/agentdb-mod'+import { parseSwarmStore } from '../hooks/data/parse'+import { sinceOf } from '../hooks/data/safe'+import { swarmStatusOf } from '../hooks/data/swarm-status'+import { readSnapshot } from '../hooks/data/snapshot'+import { mcOf } from '../hooks/mission-control'+import { callTool, classOf } from '../hooks/model-tools'+import { paletteEntries } from '../hooks/palette'+import { PERF } from '../hooks/perf'+import { SECURE } from '../hooks/secure'+import { settingsOf } from '../hooks/settings'+import { newState } from '../hooks/state'+import { barText } from '../hooks/views/bar'+import type { Actions } from '../hooks/views/common'+import { topoModelOf } from '../hooks/views/frames'+import { viewText } from '../hooks/views/pane'+import { readableFs } from './fixtures/hostile-fs'+import { rig } from './fixtures/real-rig'++// A real "now" in the range the console sees (2026-10-09): above the 1e12 count cap that turned such a stamp into 2001-09-09.+const NOW = 1_791_551_000_000+const act = new Proxy({}, { get: () => () => undefined }) as unknown as Actions++async function stateWith(files: Record<string, string>) {+ const state = newState({})++ state.snapshot = await readSnapshot(readableFs(files), new Map(), '/work', '/home/dev', {}, NOW)++ return state+}++describe('agentdb-mod: updatedMs is a time, not a count', () => {+ const file = (extra: Record<string, unknown>) => JSON.stringify({ version: 1, recall: true, guard: true, attached: 1, lastMs: 41, ...extra })++ it('keeps a Date.now()-scale stamp exactly (it was clamped to 1e12)', () => {+ expect(parseAgentdbMod(file({ updatedMs: NOW - 180_000 }))?.updatedMs).toBe(NOW - 180_000)+ expect(parseAgentdbMod(file({ updatedMs: NOW - 180_000 }))?.lastMs).toBe(41)+ })++ it('a missing, junk or out-of-Date stamp is null, never 0', () => {+ for (const bad of [undefined, 'soon', -0.5 * 1e20, 1e20, Number.NaN]) expect(parseAgentdbMod(file({ updatedMs: bad })), String(bad)).toMatchObject({ updatedMs: null })+ })++ it('the Memory page says "written 3m ago" for a file written three minutes ago, and n/a (not "56 years ago") for none', async () => {+ const at = (updatedMs: unknown) => stateWith({ '/work/.claude-flow/agentdb-mod/status.json': file({ updatedMs }) })+ const fresh = viewText({ state: await at(NOW - 180_000), nowMs: NOW, columns: 110, act }, 'memory')++ expect(fresh).toContain('written 3m ago')+ expect(fresh).not.toContain('an earlier session')++ const none = viewText({ state: await at(undefined), nowMs: NOW, columns: 110, act }, 'memory')++ expect(none).toContain('written n/a')+ expect(none).not.toMatch(/\d+d ago/)+ })+})++describe('an age is only said of a believable time', () => {+ it('sinceOf: 2000 to a day past now; Date\'s far edges and the future are n/a', () => {+ expect(sinceOf(NOW - 60_000, NOW)).toBe(NOW - 60_000)+ expect(sinceOf(NOW + 3_600_000, NOW)).toBe(NOW + 3_600_000)+ for (const bad of [8.64e15, -8.64e15, NOW + 2 * 86_400_000, 946_684_799_999, 0, null, undefined]) expect(sinceOf(bad, NOW), String(bad)).toBeUndefined()+ })++ it('agentdb-mod and the swarm say n/a, not "100020735d ago" or "0s ago"', async () => {+ for (const bad of [-8.64e15, 8.64e15, NOW + 2 * 86_400_000]) {+ const state = await stateWith({ '/work/.claude-flow/agentdb-mod/status.json': JSON.stringify({ version: 1, updatedMs: bad }) })++ expect(viewText({ state, nowMs: NOW, columns: 110, act }, 'memory'), String(bad)).toContain('written n/a')+ }++ const future = { id: 's', topology: 'mesh', status: 'running', agentIds: [], updatedAt: new Date(NOW + 30 * 86_400_000).toISOString() }++ expect(swarmStatusOf(future, NOW, [])).toMatchObject({ updatedMs: undefined, isStale: false })+ })+})++describe('the swarm record itself', () => {+ it('counts a listed id once, and says "listed, found" when the store lacks some', async () => {+ const state = await stateWith({+ '/work/.claude-flow/swarm/swarm-state.json': JSON.stringify({ swarms: { s: { swarmId: 's', topology: 'mesh', status: 'running', agents: ['a1', 'a1', 'gone'], updatedAt: new Date(NOW - 60_000).toISOString() } } }),+ '/work/.claude-flow/agents/store.json': JSON.stringify({ agents: { a1: { agentId: 'a1', agentType: 'coder', status: 'idle' } } }),+ })++ expect(viewText({ state, nowMs: NOW, columns: 140, act }, 'overview')).toContain('s · mesh · running · 2 listed, 1 found · updated 1m ago')+ })++ it('the newest swarm is chosen by instant, not by the text of its time', () => {+ const store = (a: string, b: string) => JSON.stringify({ swarms: { a: { swarmId: 'older', topology: 'mesh', status: 'running', agents: [], updatedAt: a }, b: { swarmId: 'newer', topology: 'mesh', status: 'running', agents: [], updatedAt: b } } })++ // 10:00+02:00 is 08:00Z: older than 09:00Z though it sorts after it as text.+ expect(parseSwarmStore(store('2026-10-09T10:00:00+02:00', '2026-10-09T09:00:00Z'))?.id).toBe('newer')+ })+})++describe('swarm: its own agent count and age, never the agent store', () => {+ const agents = Object.fromEntries(Array.from({ length: 259 }, (_, i) => [`agent-${i}`, { agentId: `agent-${i}`, agentType: 'coder', status: 'idle' }]))+ const swarmFile = (updatedAt: string, ids: string[] = []) =>+ JSON.stringify({ swarms: { 'swarm-1': { swarmId: 'swarm-1', topology: 'hierarchical', maxAgents: 3, status: 'running', agents: ids, updatedAt } } })+ const world = (updatedAt: string, ids: string[] = []) =>+ stateWith({ '/work/.claude-flow/swarm/swarm-state.json': swarmFile(updatedAt, ids), '/work/.claude-flow/agents/store.json': JSON.stringify({ agents }) })+ const WEEK_AGO = new Date(NOW - 7 * 86_400_000).toISOString()++ it('overview: a 0-agent swarm reads 0 agents with its age, the store is labelled "on disk"; no member to judge by, so not "stale"', async () => {+ const text = viewText({ state: await world(WEEK_AGO), nowMs: NOW, columns: 140, act }, 'overview')++ expect(text).toContain('swarm-1 · hierarchical · running · 0 agents · max 3 · updated 7d ago · 259 agents on disk')+ expect(text).not.toContain('stale')+ expect(text).toContain('259 agents on disk')+ expect(text).not.toMatch(/running · 259 agents/)+ })++ it('a fresh record is not stale and counts only the ids it lists', async () => {+ const text = viewText({ state: await world(new Date(NOW - 60_000).toISOString(), ['agent-1', 'agent-2']), nowMs: NOW, columns: 140, act }, 'overview')++ expect(text).toContain('running · 2 agents · max 3 · updated 1m ago')+ expect(text).not.toContain('stale')+ })++ it('swarm page: the topology row carries the swarm\'s count, the agent list is the store and says so', async () => {+ const text = viewText({ state: await world(WEEK_AGO), nowMs: NOW, columns: 140, act }, 'swarm')++ expect(text).toContain('running · 0 agents · max 3 · updated 7d ago')+ expect(text).toContain('graph needs a terminal: 0 swarm members')+ expect(text).toContain('259 agents on disk (every swarm)')+ })++ it('the graph draws only the swarm\'s members, and the status bar does not call the store "ready"', async () => {+ const state = await world(WEEK_AGO)++ expect(topoModelOf(state.snapshot, new Map(), NOW)?.nodes.map(node => [node.label, node.status])).toEqual([['swarm', 'running']])+ expect(barText(state, NOW)).toContain('swarm, no agents')+ expect(barText(state, NOW)).not.toContain('259')+ })+})++describe('labels agree with the gate', () => {+ it('every security and performance entry is gated as the cost tier it shows (writes → write, network → network)', () => {+ for (const entry of [...SECURE, ...PERF]) {+ if (entry.cost === 'read') continue++ expect(classOf({ label: entry.label, args: entry.args, expect: '', ...(entry.note !== undefined && { note: entry.note }) }), entry.id).toBe(entry.cost === 'writes' ? 'write' : 'network')+ }+ })++ it('perf-bottleneck at read is refused as a write (it was a delete needing full), and runs at write', async () => {+ const read = rig()++ Object.assign(settingsOf(read.state).ai, { modelControl: 'read', modelConfirm: 'auto' })+ expect(await callTool('console_run', { id: 'perf-bottleneck' }, read.deps)).toMatch(/is a write action/)++ const write = rig()++ Object.assign(settingsOf(write.state).ai, { modelControl: 'write', modelConfirm: 'auto' })+ expect(await callTool('console_run', { id: 'perf-bottleneck' }, write.deps)).not.toMatch(/^Refused/)+ })++ it('mission-goal does not claim "nothing is written": it is gated as a write, like console_set goal, and it replaces the goal', async () => {+ const world = rig()+ const entry = paletteEntries(world.state, NOW).find(candidate => candidate.id === 'mission-goal')++ expect(entry?.label).not.toMatch(/nothing is written/)+ expect(entry?.label).toMatch(/replaces the current goal/)+ world.control.setView('missions')+ Object.assign(settingsOf(world.state).ai, { modelControl: 'read', modelConfirm: 'auto' })+ expect(await callTool('console_run', { id: 'mission-goal', text: 'add a dark mode toggle' }, world.deps)).toMatch(/is a write action/)+ expect(mcOf(world.state).goal).toBe('')++ Object.assign(settingsOf(world.state).ai, { modelControl: 'write', modelConfirm: 'auto' })+ await callTool('console_run', { id: 'mission-goal', text: 'add a dark mode toggle' }, world.deps)+ expect(mcOf(world.state).goal).toBe('add a dark mode toggle')+ })+})++describe('stale needs evidence of no activity, not just an old record', () => {+ const DAY = 86_400_000+ const swarm = (ids: string[]) => ({ id: 's', topology: 'mesh', status: 'running', agentIds: ids, updatedAt: new Date(NOW - 7 * DAY).toISOString() })+ const agent = (id: string, status: string, createdAtMs?: number) => ({ id, type: 'coder', status, ...(createdAtMs !== undefined && { createdAtMs }) })++ it('an old record with a busy member is not stale (the CLI does not rewrite updatedAt on spawn or status reads)', () => {+ expect(swarmStatusOf(swarm(['a', 'b']), NOW, [agent('a', 'busy', NOW - 5 * DAY), agent('b', 'idle', NOW - 5 * DAY)])).toMatchObject({ isStale: false, shown: 'running' })+ })++ it('an old record whose newest member was created within a day is not stale', () => {+ expect(swarmStatusOf(swarm(['a', 'b']), NOW, [agent('a', 'idle', NOW - 5 * DAY), agent('b', 'idle', NOW - 3_600_000)])).toMatchObject({ isStale: false })+ })++ it('a member with no creation time, or no member at all, is no evidence: the age is shown, "stale" is not', () => {+ expect(swarmStatusOf(swarm(['a']), NOW, [agent('a', 'idle')])).toMatchObject({ isStale: false, updatedMs: NOW - 7 * DAY })+ expect(swarmStatusOf(swarm([]), NOW, [])).toMatchObject({ isStale: false, updatedMs: NOW - 7 * DAY })+ })++ it('an old record whose members are all idle and were created days ago is stale, and reads stalled', () => {+ expect(swarmStatusOf(swarm(['a', 'b']), NOW, [agent('a', 'idle', NOW - 5 * DAY), agent('b', 'stopped', NOW - 4 * DAY)])).toMatchObject({ isStale: true, shown: 'stalled' })+ })++ it('a duplicated store id is one agent, and the bar never calls a missing agent ready', async () => {+ const state = await stateWith({+ '/work/.claude-flow/swarm/swarm-state.json': JSON.stringify({ swarms: { s: { swarmId: 's', topology: 'mesh', status: 'running', agents: ['a1', 'a1', 'gone'], updatedAt: new Date(NOW - 60_000).toISOString() } } }),+ '/work/.claude-flow/agents/store.json': JSON.stringify({ agents: { x: { agentId: 'a1', agentType: 'coder', status: 'idle' }, y: { agentId: 'a1', agentType: 'coder', status: 'idle' } } }),+ })++ expect(swarmStatusOf(state.snapshot?.swarm as never, NOW, state.snapshot?.agents ?? [])).toMatchObject({ listed: 2, found: 1 })+ expect(barText(state, NOW)).toContain('idle · 1 agent ready (2 listed, 1 found)')+ })+})diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.tsindex 235d078763..1f9220e7ed 100644--- a/plugins/ruflo-console/tests/views.test.ts+++ b/plugins/ruflo-console/tests/views.test.ts@@ -54,7 +54,7 @@ describe('views', () => {const { text, rasters, tree } = await drawn($, 'swarm')expect(rasters).toEqual(['title', 'topology'])- expect(text).toContain('hierarchical · specialized · running · max 6')+ expect(text).toContain('hierarchical · specialized · running · 2 agents · max 6 · updated ')// One label per agent (no repeated type), then status; a short id instead of the full one.expect(text).toMatch(/▸● \ncoder\s+idle\s+tasks/)expect(text).toMatch(/· #[a-z0-9]{4,6}/)diff --git a/plugins/ruflo-console/tests/wf-replay-views.spec.ts b/plugins/ruflo-console/tests/wf-replay-views.spec.tsindex b1121ff30c..518e4fb856 100644--- a/plugins/ruflo-console/tests/wf-replay-views.spec.ts+++ b/plugins/ruflo-console/tests/wf-replay-views.spec.ts@@ -6,7 +6,7 @@import { beforeEach, describe, expect, it } from 'vitest'import type { ActionSpec } from '../hooks/actions'-import { swarmRun } from '../hooks/data/workflows'+import { swarmRun } from '../hooks/data/wf-swarm'import { newState } from '../hooks/state'import type { Host } from '../hooks/host'import { workflowsActions } from '../hooks/wf-actions'diff --git a/plugins/ruflo-console/tests/wf-replay.spec.ts b/plugins/ruflo-console/tests/wf-replay.spec.tsindex d78915ed5e..1e80b4e03e 100644--- a/plugins/ruflo-console/tests/wf-replay.spec.ts+++ b/plugins/ruflo-console/tests/wf-replay.spec.ts@@ -6,7 +6,7 @@import { describe, expect, it } from 'vitest'import { boardAt, buildTimeline, describeStep, isPlaying, jumpReplay, newReplay, offsetOf, phaseSteps, SPEEDS, stepNow, stepReplay } from '../hooks/data/wf-replay'-import { swarmRun } from '../hooks/data/workflows'+import { swarmRun } from '../hooks/data/wf-swarm'import { BASE, runOf } from './fixtures/wf-runs'const run = runOf('wf_a', BASE)diff --git a/plugins/ruflo-console/tests/wf-swarm.spec.ts b/plugins/ruflo-console/tests/wf-swarm.spec.tsnew file mode 100644index 0000000000..3adeb8257e--- /dev/null+++ b/plugins/ruflo-console/tests/wf-swarm.spec.ts@@ -0,0 +1,44 @@+/**+ * ruflo's runs on the Workflows page (data/wf-swarm.ts): ids a person may have saved stay stable, and a duplicated store id is one agent.+ * npx vitest run plugins/ruflo-console/tests/wf-swarm.spec.ts+ */+import { describe, expect, it } from 'vitest'++import { decodeSaved, pinsIn, restoreDrill } from '../hooks/data/wf-saved'+import { swarmRun } from '../hooks/data/wf-swarm'+import { allRuns, newWfUi } from '../hooks/data/workflows-nav'++const NOW = 1_791_551_000_000+const agents = [+ { id: 'agent-1-aaaaaa', type: 'coder', status: 'busy', createdAtMs: NOW - 20_000 },+ { id: 'agent-2-bbbbbb', type: 'coder', status: 'idle' },+ { id: 'agent-3-cccccc', type: 'tester', status: 'stopped' },+]+const swarm = { id: 'swarm-1', topology: 'hierarchical', status: 'running', agentIds: [] as string[] }++describe('ruflo runs on the Workflows page', () => {+ it('a drill and a pin saved on origin/main (run id "ruflo-swarm", before swarms were split from the store) still resolve', () => {+ // As origin/main wrote .claude-flow/console/wf-views.json for the no-swarm roster: id 'ruflo-swarm', name 'ruflo swarm'.+ const file = JSON.stringify({ version: 1, savedAtMs: 1, drill: { runId: 'ruflo-swarm', runName: 'ruflo swarm', phase: 'tester', agent: 'agent-3-cccccc', column: 'agents', isInspecting: true, tab: 'detail' }, filters: {}, search: '', pins: [{ runId: 'ruflo-swarm', name: 'ruflo swarm', pinnedAtMs: 1 }] })+ const { saved } = decodeSaved(file)++ for (const swarmNow of [null, { ...swarm, agentIds: ['agent-1-aaaaaa'] }]) {+ const runs = allRuns([], swarmNow, agents, NOW)+ const restored = restoreDrill(saved.drill, runs, newWfUi())+ const at = runs[restored?.ui.run ?? -1]++ expect(restored?.found, String(swarmNow)).toBe('exact')+ expect(at?.id).toBe('ruflo-swarm')+ expect(at?.phases[restored?.ui.phase ?? -1]?.title).toBe('tester')+ expect(pinsIn(saved, runs)[0]?.run?.id).toBe('ruflo-swarm')+ }+ })++ it('a duplicated store id is one agent in the roster, and the swarm run keeps "listed" apart from what was found', () => {+ const doubled = [...agents, { ...(agents[1] as (typeof agents)[number]) }]+ const run = swarmRun({ ...swarm, agentIds: ['agent-2-bbbbbb', 'agent-2-bbbbbb', 'agent-gone'], updatedAt: new Date(NOW - 60_000).toISOString() } as never, doubled, NOW)++ expect(run).toMatchObject({ total: 1, listed: 2 })+ expect(swarmRun(null, doubled, NOW)?.total).toBe(3)+ })+})diff --git a/plugins/ruflo-console/tests/workflows.spec.ts b/plugins/ruflo-console/tests/workflows.spec.tsindex 15a5574cb0..4a4a225d5d 100644--- a/plugins/ruflo-console/tests/workflows.spec.ts+++ b/plugins/ruflo-console/tests/workflows.spec.ts@@ -9,7 +9,8 @@ import { newState } from '../hooks/state'import type { ReadCache } from '../hooks/data/files'import { allRuns, newWfUi, pick, startOn, walk } from '../hooks/data/workflows-nav'import { readWorkflowRuns, slugOf, TRANSCRIPT_CAP, type WorkflowFs } from '../hooks/data/workflows-read'-import { buildRun, currentPhase, fmtElapsed, fmtTokens, jsonLines, modelName, parseAgentMeta, parseJournal, parseRunRecord, parseScriptMeta, parseTranscript, STALE_MS, swarmRun, type RunInput } from '../hooks/data/workflows'+import { buildRun, currentPhase, fmtElapsed, fmtTokens, jsonLines, modelName, parseAgentMeta, parseJournal, parseRunRecord, parseScriptMeta, parseTranscript, STALE_MS, type RunInput } from '../hooks/data/workflows'+import { swarmRun } from '../hooks/data/wf-swarm'import type { Ctx, Kit } from '../hooks/views/common'import { workflowsView } from '../hooks/views/workflows'import { journal, meta, record, result, SCRIPT, started, T0, transcript } from './fixtures/workflows'@@ -111,6 +112,8 @@ describe('parsers', () => {expect(fmtElapsed(15_000)).toBe('15s')expect(fmtElapsed(192_000)).toBe('3m12s')expect(fmtElapsed(3_900_000)).toBe('1h05m')+ // A day or more reads in days, as ago() does (a 68-day-old agent once read "1638h18m").+ expect(fmtElapsed(68 * 86_400_000 + 6 * 3_600_000 + 18 * 60_000)).toBe('68d06h')expect(modelName('claude-sonnet-5-5')).toBe('Sonnet 5.5')expect(modelName('claude-opus-5')).toBe('Opus 5')expect(modelName('gpt-x')).toBe('gpt-x')@@ -180,7 +183,7 @@ describe('ruflo swarm as a run', () => {const swarm = { id: 'swarm-1', topology: 'hierarchical', status: 'running', agentIds: [] }it('groups by agent type, never invents tokens or model', () => {- const run = swarmRun(swarm, agents, NOW)+ const run = swarmRun({ ...swarm, agentIds: agents.map(agent => agent.id) }, agents, NOW)expect(run).toMatchObject({ kind: 'ruflo-swarm', state: 'active', running: 1, idle: 1, done: 1, total: 3, totalTokens: null })expect(run?.phases.map(p => [p.title, p.total])).toEqual([['coder', 2], ['tester', 1]])@@ -189,10 +192,58 @@ describe('ruflo swarm as a run', () => {expect(swarmRun(null, [], NOW)).toBeNull()})- it('allRuns puts whatever is running first', () => {+ it('an empty swarm (right after swarm init) is still its own run with 0 agents; the store is a separate "agents on disk" run', () => {+ const fresh = { ...swarm, maxAgents: 3, updatedAt: new Date(NOW - 60_000).toISOString() }++ expect(swarmRun(fresh, agents, NOW)).toMatchObject({ id: 'swarm-1', name: 'ruflo swarm · hierarchical', state: 'active', total: 0, listed: 0 })+ expect(swarmRun(fresh, [], NOW)).toMatchObject({ id: 'swarm-1', state: 'active', total: 0 })+ expect(allRuns([], fresh, [], NOW).map(run => run.id)).toEqual(['swarm-1'])+ expect(allRuns([], fresh, agents, NOW).map(run => [run.id, run.name, run.total])).toEqual([+ ['swarm-1', 'ruflo swarm · hierarchical', 0],+ ['ruflo-swarm', 'ruflo agents on disk', 3],+ ])+ })++ it('a listed id is counted once, and one the store lacks makes the header say "listed, found"', () => {+ const run = swarmRun({ ...swarm, agentIds: ['agent-2-bbbbbb', 'agent-2-bbbbbb', 'agent-gone'], updatedAt: new Date(NOW - 60_000).toISOString() }, agents, NOW) as NonNullable<ReturnType<typeof swarmRun>>++ expect(run).toMatchObject({ total: 1, listed: 2 })+ expect(lines(workflowsView(ctxOf(110), { runs: [run], root: '/r', capBytes: TRANSCRIPT_CAP, skipped: 0, more: 0 }, newWfUi(), { ask: () => undefined, show: () => undefined })).join('\n')).toContain('updated 1m ago · 2 listed, 1 found')+ })++ it('a swarm that lists its agents is a run of those only, with the record\'s status and age (stale "running" is stalled)', () => {+ const weekOld = { ...swarm, agentIds: ['agent-2-bbbbbb'], updatedAt: new Date(NOW - 7 * 86_400_000).toISOString() }+ // Stale needs evidence: the one member is idle and was created days ago.+ const quiet = agents.map(agent => ({ ...agent, createdAtMs: NOW - 3 * 86_400_000 }))+ const run = swarmRun(weekOld, quiet, NOW)++ expect(run).toMatchObject({ id: 'swarm-1', name: 'ruflo swarm · hierarchical', state: 'stalled', isStale: true, total: 1, idle: 1, updatedMs: NOW - 7 * 86_400_000 })+ expect(swarmRun({ ...weekOld, updatedAt: new Date(NOW - 60_000).toISOString() }, quiet, NOW)?.state).toBe('active')+ expect(swarmRun({ ...weekOld, agentIds: ['agent-1-aaaaaa'] }, quiet, NOW)?.state).toBe('active')+ expect(swarmRun({ ...weekOld, status: 'terminated' }, quiet, NOW)?.state).toBe('finished')++ const shown = lines(workflowsView(ctxOf(110), { runs: [run as NonNullable<typeof run>], root: '/r', capBytes: TRANSCRIPT_CAP, skipped: 0, more: 0 }, newWfUi(), { ask: () => undefined, show: () => undefined })).join('\n')++ expect(shown).toContain('1 agents · 0 busy · 1 idle · 0 stopped · 0 failed · updated 7d ago · stale')+ expect(shown).toContain('stalled')+ })++ it('an agent row keeps "n/a tok" and its age apart, in days', () => {+ const old = [{ id: 'agent-r-jckxxx', type: 'researcher', status: 'idle', createdAtMs: NOW - 68 * 86_400_000 - 6 * 3_600_000 }]+ const run = swarmRun(null, old, NOW) as NonNullable<ReturnType<typeof swarmRun>>+ const shown = lines(workflowsView(ctxOf(110), { runs: [run], root: '/r', capBytes: TRANSCRIPT_CAP, skipped: 0, more: 0 }, newWfUi(), { ask: () => undefined, show: () => undefined })).join('\n')++ expect(shown).toMatch(/n\/a tok +68d06h/)+ expect(shown).not.toMatch(/tok\d/)+ })++ it('allRuns puts whatever is live first: a swarm by its record\'s state, so a stale "running" one is not live', () => {const idle = buildRun({ id: 'wf_old', journal: null, agents: new Map(), record: record(), script: null, nowMs: NOW })+ const listing = { ...swarm, agentIds: agents.map(agent => agent.id) }+ const quiet = agents.map(agent => ({ ...agent, status: 'idle', createdAtMs: NOW - 3 * 86_400_000 }))- expect(allRuns([idle], swarm, agents, NOW).map(r => r.kind)).toEqual(['ruflo-swarm', 'workflow'])+ expect(allRuns([idle], { ...listing, updatedAt: new Date(NOW - 60_000).toISOString() }, agents, NOW).map(r => r.kind)).toEqual(['ruflo-swarm', 'workflow'])+ expect(allRuns([idle], { ...listing, updatedAt: new Date(NOW - 7 * 86_400_000).toISOString() }, quiet, NOW).map(r => [r.id, r.state])).toEqual([['wf_old', expect.any(String)], ['swarm-1', 'stalled']])expect(allRuns([idle], null, [], NOW).map(r => r.id)).toEqual(['wf_old'])})})@@ -405,7 +456,7 @@ describe('view', () => {})it('a ruflo agent offers stop and spawn through the confirm hook with fixed argv', () => {- const swarm = swarmRun({ id: 's', topology: 'hierarchical', status: 'running', agentIds: [] }, [{ id: 'agent-9-zzzzzz', type: 'coder', status: 'busy' }], NOW) as NonNullable<ReturnType<typeof swarmRun>>+ const swarm = swarmRun({ id: 's', topology: 'hierarchical', status: 'running', agentIds: ['agent-9-zzzzzz'] }, [{ id: 'agent-9-zzzzzz', type: 'coder', status: 'busy' }], NOW) as NonNullable<ReturnType<typeof swarmRun>>const asked: string[][] = []const ui = { ...newWfUi(), column: 'agents' as const, isInspecting: true }const tree = workflowsView(ctxOf(110), model([swarm]), ui, { ask: spec => asked.push([...spec.args]), show: () => undefined })