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(console): 0.36.0 integration: eventsPersist option, shared whole-batch append argv, hostile-time hardening, init ignores console/

ruv1ac200432cf4
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json
index f477c27a65..7dccc6dd0d 100644
--- a/plugins/ruflo-console/.claude-plugin/plugin.json
+++ b/plugins/ruflo-console/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-console",
"description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",
- "version": "0.35.0",
+ "version": "0.36.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -98,6 +98,12 @@
"description": "With the bbs look, play a dial-up boot screen (modem connect, the RUFLO logo drawing in, every area of the console coming online in a log, a loading bar for the first ruflo reads) when the cockpit opens. At least 5.4 s, at most 8 s.",
"default": true
},
+ "eventsPersist": {
+ "type": "boolean",
+ "title": "Keep Events history",
+ "description": "Keep the Events and Timeline history on disk in this project (.claude-flow/console/: events.jsonl, lanes.jsonl, events-prefs.json, exports/) so a restart does not empty the pages. Text is masked before it is written (credentials, home-directory user names, control characters); nothing leaves the machine and no model reads it. Off writes nothing; the pages still work for the session.",
+ "default": true
+ },
"wfBudgetRunUsd": {
"type": "number",
"title": "Workflow budget per run (USD)",
diff --git a/plugins/ruflo-console/hooks/activity-io.ts b/plugins/ruflo-console/hooks/activity-io.ts
new file mode 100644
index 0000000000..70e42d2ad2
--- /dev/null
+++ b/plugins/ruflo-console/hooks/activity-io.ts
@@ -0,0 +1,163 @@
+/**
+ * The one write path for the Events and Timeline files (ADR-474), with the host's `fs` and `run` passed in so a test supplies its own.
+ * Lines are queued in memory and written in batches (never one write per event): at most one write per file is in flight, each batch
+ * is at most BATCH_MAX bytes, and a failure is remembered and retried later, never thrown. A write appends through the journal's fixed
+ * argv (GNU `dd oflag=append`, no shell: the path is one element, and an O_APPEND write keeps a batch whole when two consoles share the file). A file past its cap is cut to its newest half through a temporary file and a rename.
+ * The folder is created once, and nothing is written through a link.
+ */
+import { checkNoLinks } from './data/wf-file'
+import { appendArgv } from './data/append-argv'
+import { dirOf, newFileArgv, replaceFileArgv } from './data/wf-file'
+import { keepNewestHalf, READ_MAX } from './data/activity-store'
+import type { Host } from './host'
+
+export type IoHost = Pick<Host, 'fs' | 'run'>
+
+export const BATCH_MAX = 32 * 1024
+
+/** The append argv is shared with the autopilot journal (data/append-argv.ts): one block per batch, so two consoles never tear a line. A batch is at most BATCH_MAX plus one line. */
+export { appendArgv }
+
+/** The folder's own `.gitignore` (`*`): `.claude-flow/.gitignore` from `ruflo init` does not list `console/`, and these files hold a person's history. */
+export const IGNORE_BODY = '# the ruflo console\'s own history: local state, never committed\n*\n'
+export const PENDING_MAX = 2_000
+export const RETRY_MS = 30_000
+const WRITE_TIMEOUT_MS = 10_000
+
+type Channel = { path: string; cap: number; pending: string[]; isWriting: boolean; size: number | null; retryAtMs: number; error: string | null; isDirReady: boolean; clearAtMs: number; writes: number; rotations: number }
+
+const channels = new Map<string, Channel>()
+const ignored = new Set<string>()
+
+export const channelOf = (path: string, cap: number): Channel => {
+ const found = channels.get(path)
+
+ if (found !== undefined) return found
+
+ const made: Channel = { path, cap, pending: [], isWriting: false, size: null, retryAtMs: 0, error: null, isDirReady: false, clearAtMs: 0, writes: 0, rotations: 0 }
+
+ channels.set(path, made)
+
+ return made
+}
+
+/** For tests: forgets every channel. */
+export const resetIo = (): void => {
+ channels.clear()
+ ignored.clear()
+}
+
+/** Queues one line; the oldest queued lines go when a failing disk lets the queue grow past PENDING_MAX. */
+export function queueLine(path: string, cap: number, line: string): void {
+ const channel = channelOf(path, cap)
+
+ channel.pending.push(line)
+ if (channel.pending.length > PENDING_MAX) channel.pending.splice(0, channel.pending.length - PENDING_MAX)
+}
+
+export const pendingOf = (path: string): number => channels.get(path)?.pending.length ?? 0
+export const errorOf = (path: string): string | null => channels.get(path)?.error ?? null
+export const forgetChannel = (path: string): void => void channels.delete(path)
+
+const tmpOf = (path: string): string => `${path}.tmp`
+
+/** Writes `<dir>/.gitignore` once per folder if there is none (`conv=excl` fails, harmlessly, where one exists). Never throws. */
+async function ensureIgnored(host: IoHost, dir: string): Promise<void> {
+ if (ignored.has(dir)) return
+
+ ignored.add(dir)
+ await host.run(['dd', `of=${dir}/.gitignore`, 'conv=excl', 'status=none'], WRITE_TIMEOUT_MS, IGNORE_BODY).catch(() => undefined)
+}
+
+async function rotate(host: IoHost, channel: Channel): Promise<void> {
+ const stat = await host.fs.stat(channel.path).catch(() => undefined)
+
+ if (stat === undefined) return
+
+ const size = stat.size ?? channel.size ?? 0
+ const kept = size > READ_MAX ? '' : keepNewestHalf(await host.fs.read(channel.path).catch(() => ''), channel.cap)
+ await host.run(['rm', '-f', '--', tmpOf(channel.path)], WRITE_TIMEOUT_MS)
+
+ const written = await host.run(newFileArgv(tmpOf(channel.path), true), WRITE_TIMEOUT_MS, kept)
+
+ if (written.exitCode !== 0) return
+
+ const moved = await host.run(['mv', '-f', '--', tmpOf(channel.path), channel.path], WRITE_TIMEOUT_MS)
+
+ if (moved.exitCode === 0) {
+ channel.size = kept.length
+ channel.rotations++
+ }
+}
+
+/** One pass for one file: writes what is queued if nothing is in flight and no recent failure is waiting out. Never throws. */
+export async function flush(host: IoHost, cwd: string, path: string, nowMs: number = Date.now()): Promise<void> {
+ const channel = channels.get(path)
+
+ if (channel === undefined || channel.pending.length === 0 || channel.isWriting || nowMs < channel.retryAtMs) return
+
+ channel.isWriting = true
+
+ const batch: string[] = []
+ let bytes = 0
+
+ while (channel.pending.length > 0 && bytes + (channel.pending[0] as string).length <= BATCH_MAX) {
+ const line = channel.pending.shift() as string
+
+ batch.push(line)
+ bytes += line.length
+ }
+
+ if (batch.length === 0) batch.push(channel.pending.shift() as string)
+
+ try {
+ const clear = await checkNoLinks(host.fs, path, { cwd: cwd.replace(/\/+$/, '') }, { allowExisting: true })
+
+ if (!clear.ok) throw new Error(clear.why)
+
+ if (!channel.isDirReady) {
+ const made = await host.run(['mkdir', '-p', '--', dirOf(path)], WRITE_TIMEOUT_MS)
+
+ if (made.exitCode !== 0) throw new Error(`the folder could not be made (exit ${made.exitCode})`)
+ channel.isDirReady = true
+ }
+
+ await ensureIgnored(host, dirOf(path))
+
+ if (channel.size === null) channel.size = (await host.fs.stat(path).catch(() => undefined))?.size ?? 0
+
+ const result = await host.run(appendArgv(path), WRITE_TIMEOUT_MS, batch.join(''))
+
+ if (result.exitCode !== 0) throw new Error(`the write exited ${result.exitCode}`)
+
+ channel.size += bytes
+ channel.writes++
+ channel.error = null
+
+ if (channel.size > channel.cap) await rotate(host, channel)
+ } catch (error) {
+ channel.pending.unshift(...batch)
+ channel.error = (error instanceof Error ? error.message : 'the write was refused').slice(0, 80)
+ channel.retryAtMs = nowMs + RETRY_MS
+ } finally {
+ channel.isWriting = false
+ }
+}
+
+/** Replaces a small state file whole (the prefs): checked for links, written in place. Returns the problem, or null. */
+export async function replaceFile(host: IoHost, cwd: string, path: string, content: string): Promise<string | null> {
+ try {
+ const clear = await checkNoLinks(host.fs, path, { cwd: cwd.replace(/\/+$/, '') }, { allowExisting: true })
+
+ if (!clear.ok) return clear.why.slice(0, 80)
+
+ const hasDir = (await host.fs.stat(dirOf(path)).catch(() => undefined)) !== undefined
+ const result = await host.run(replaceFileArgv(path, hasDir), WRITE_TIMEOUT_MS, content)
+
+ if (result.exitCode === 0) await ensureIgnored(host, dirOf(path))
+
+ return result.exitCode === 0 ? null : `the write exited ${result.exitCode}`
+ } catch (error) {
+ return error instanceof Error ? error.message.slice(0, 80) : 'the write was refused'
+ }
+}
diff --git a/plugins/ruflo-console/hooks/activity-live.ts b/plugins/ruflo-console/hooks/activity-live.ts
new file mode 100644
index 0000000000..8d7f7d57b7
--- /dev/null
+++ b/plugins/ruflo-console/hooks/activity-live.ts
@@ -0,0 +1,304 @@
+/**
+ * The Events and Timeline pages' live side (ADR-474): one record per console state that holds the retained event log, the lane store,
+ * the saved searches, pins and alert rules, loads them from `.claude-flow/console/` once, and every 1.5 s takes in what is new:
+ * events the diff recorded, events derived from the Workflows runs, the autopilot, Anatole, the band's notices, denies and mods,
+ * lane samples and tool calls. New lines are queued and written in batches through hooks/activity-io.ts (the single write path), and
+ * alert rules are evaluated over the NEW events only. Everything is fail-open: a disk problem is a note on the page, never a crash.
+ * The option `eventsPersist` (default on) turns the writing off; the page and `/ruflo events forget` can still clear what exists.
+ */
+import { channelOf, flush, forgetChannel, pendingOf, queueLine, replaceFile, errorOf, type IoHost } from './activity-io'
+import { storeOf } from './ap-live'
+import { decodeEvents, decodeLanes, decodePrefs, emptyPrefs, encodeEvent, encodeLane, encodePrefs, EVENTS_CAP, EVENTS_FILE, LANES_CAP, LANES_FILE, MAX_LOG, PREFS_FILE, READ_MAX, type Prefs, type LaneRow } from './data/activity-store'
+import { evaluateRules } from './data/event-rules'
+import { anatoleEvents, apEvents, denyEvents, modEvents, newMemo, noticeEvents, runEvents, type Memo } from './data/event-sources'
+import { agentLabels } from './data/parse'
+import { readBounded } from './data/files'
+import { addTools, completeTicks, loadRows, newLaneStore, observe, setInterval, trim, type LaneStore, type Sample } from './data/timeline-model'
+import type { ConsoleEvent } from './data/events'
+import { levelOf } from './data/event-severity'
+import type { Host } from './host'
+import { addNotice } from './notices'
+import type { State } from './state'
+
+export const TICK_MS = 1_500
+export const FLUSH_MS = 4_000
+const PREFS_GAP_MS = 2_000
+
+export type Loaded = { isLoaded: boolean; events: number; eventsBytes: number; lanesBytes: number; bad: number; newer: number; problem: string | null }
+
+export type Activity = {
+ /** The retained log, oldest first, at most MAX_LOG. The sequence number of log[i] is seqBase + i. */
+ log: ConsoleEvent[]
+ seqBase: number
+ /** Bumps whenever the log changes: a memo key. */
+ version: number
+ lanes: LaneStore
+ prefs: Prefs
+ prefsProblem: string | null
+ isPrefsForeign: boolean
+ isPrefsDirty: boolean
+ prefsWriteMs: number
+ memo: Memo
+ /** The last state.events item taken in. */
+ cursor: ConsoleEvent | null
+ loaded: Loaded
+ session: string
+ /** New events since the last rule pass. */
+ fresh: ConsoleEvent[]
+ lastFlushMs: number
+ isLoading: boolean
+ ruleHits: number
+}
+
+const held = new WeakMap<State, Activity>()
+
+export function activityOf(state: State): Activity {
+ let found = held.get(state)
+
+ if (found === undefined) {
+ found = { log: [], seqBase: 0, version: 0, lanes: newLaneStore(), prefs: emptyPrefs(), prefsProblem: null, isPrefsForeign: false, isPrefsDirty: false, prefsWriteMs: 0, memo: newMemo(), cursor: null, loaded: { isLoaded: false, events: 0, eventsBytes: 0, lanesBytes: 0, bad: 0, newer: 0, problem: null }, session: Math.random().toString(36).slice(2, 8), fresh: [], lastFlushMs: 0, isLoading: false, ruleHits: 0 }
+ held.set(state, found)
+ }
+
+ return found
+}
+
+export const seqOf = (act: Activity): number => act.seqBase + act.log.length
+
+export const pathsOf = (cwd: string): { events: string; lanes: string; prefs: string } => {
+ const root = cwd.replace(/\/+$/, '')
+
+ return { events: `${root}/${EVENTS_FILE}`, lanes: `${root}/${LANES_FILE}`, prefs: `${root}/${PREFS_FILE}` }
+}
+
+/** Adds events to the log (oldest first), keeping MAX_LOG. */
+export function append(act: Activity, events: readonly ConsoleEvent[]): void {
+ if (events.length === 0) return
+
+ act.log.push(...events)
+
+ if (act.log.length > MAX_LOG) {
+ const drop = act.log.length - MAX_LOG
+
+ act.log.splice(0, drop)
+ act.seqBase += drop
+ }
+
+ act.version++
+}
+
+/** Reads the three files once: the tail of each log (cap shown by the page) and the prefs. Never throws. */
+export async function loadActivity(state: State, host: IoHost): Promise<void> {
+ const act = activityOf(state)
+
+ if (act.loaded.isLoaded || act.isLoading) return
+
+ act.isLoading = true
+
+ try {
+ const paths = pathsOf(state.cwd)
+ const [events, lanes, prefs] = await Promise.all([readBounded(host.fs, state.cache, paths.events, READ_MAX, true), readBounded(host.fs, state.cache, paths.lanes, READ_MAX, true), readBounded(host.fs, state.cache, paths.prefs, 70_000, true)])
+ const e = decodeEvents(events.text)
+ const l = decodeLanes(lanes.text)
+ const p = decodePrefs(prefs.text)
+ const problem = events.text === null && events.reason === 'too-large' ? 'the events file is over the read cap, so only new events are kept until it rotates' : null
+ const live = act.log.splice(0)
+
+ act.log = [...e.items, ...live].sort((a, b) => a.atMs - b.atMs)
+ if (act.log.length > MAX_LOG) act.log.splice(0, act.log.length - MAX_LOG)
+ loadRows(act.lanes, l.items as LaneRow[])
+ act.prefs = p.prefs
+ act.prefsProblem = p.problem
+ act.isPrefsForeign = p.isForeign
+ act.loaded = { isLoaded: true, events: e.items.length, eventsBytes: e.bytes, lanesBytes: l.bytes, bad: e.bad + l.bad, newer: e.newer + l.newer, problem }
+ act.version++
+ } catch {
+ act.loaded = { ...act.loaded, isLoaded: true, problem: 'the history could not be read' }
+ } finally {
+ act.isLoading = false
+ }
+}
+
+const BUSY = /busy|active|working|running/i
+
+function laneSamples(state: State): { ruflo: Sample[] } {
+ const agents = state.snapshot?.agents ?? []
+ const labels = agentLabels(agents)
+
+ return { ruflo: agents.slice(0, 200).map(agent => ({ lane: `ruflo:${agent.id}`, group: 'ruflo' as const, label: labels.get(agent.id) ?? agent.type, busy: BUSY.test(agent.status) })) }
+}
+
+/** Feeds the lane store from the state: ruflo agent statuses, Claude Code tool calls, workflow agents, mission tasks, autopilot steps. Returns the rows to persist. */
+export function feedLanes(state: State, act: Activity, nowMs: number): LaneRow[] {
+ const rows: LaneRow[] = [...observe(act.lanes, 'ruflo', laneSamples(state).ruflo, nowMs)]
+
+ for (const [who, calls] of state.toolsByAgent) rows.push(...addTools(act.lanes, who === 'main' ? 'claude:main' : `claude:${who}`, 'claude', who === 'main' ? 'claude (main)' : `subagent ${who.replace(/[^a-z0-9]/gi, '').slice(-6)}`, calls, nowMs))
+
+ for (const run of state.wf.read?.runs ?? []) {
+ if (run.kind !== 'workflow') continue
+
+ for (const phase of run.phases) {
+ for (const agent of phase.agents) {
+ if (agent.startedMs === undefined) continue
+
+ const row = setInterval(act.lanes, `workflow:${run.id}/${agent.id}`, 'workflow', `${run.name === run.id ? run.id : run.name}/${agent.label}`, agent.startedMs, agent.state === 'running' ? null : agent.startedMs + Math.max(0, agent.elapsedMs ?? 0), true)
+
+ if (row !== null) rows.push(row)
+ }
+ }
+ }
+
+ for (const task of state.snapshot?.tasks ?? []) {
+ if (task.startedAtMs === undefined) continue
+
+ const done = task.completedAtMs ?? (/complete|done|fail|cancel/i.test(task.status) ? task.startedAtMs : null)
+ const row = setInterval(act.lanes, `mission:${task.id}`, 'mission', task.description.slice(0, 40) || task.id, task.startedAtMs, done, true)
+
+ if (row !== null) rows.push(row)
+ }
+
+ for (const step of storeOf(state).loop.steps) {
+ const row = setInterval(act.lanes, `autopilot:${step.id}`, 'autopilot', `step ${step.id}`, step.startedAt, step.status === 'started' ? null : (step.endedAt ?? step.startedAt), step.status !== 'failed')
+
+ if (row !== null) rows.push(row)
+ }
+
+ rows.push(...completeTicks(act.lanes, nowMs))
+ trim(act.lanes, nowMs)
+
+ return rows
+}
+
+/** Takes in the events the diff of reads and the tool calls recorded since the last call: cheap enough to run on every draw, so a page never lags a tick behind. */
+export function takeRing(state: State, act: Activity): void {
+ const ring = state.events
+ const at = act.cursor === null ? -1 : ring.lastIndexOf(act.cursor)
+ const fresh = ring.slice(at + 1)
+
+ if (fresh.length === 0) return
+
+ act.cursor = ring[ring.length - 1] as ConsoleEvent
+ append(act, fresh)
+ act.fresh.push(...fresh)
+
+ if (state.options.eventsPersist) {
+ const path = pathsOf(state.cwd).events
+
+ for (const event of fresh) queueLine(path, EVENTS_CAP, encodeEvent(event, act.session))
+ }
+}
+
+/** What the sources the console already holds say happened since the last pass (oldest first); the first pass of each is a baseline. */
+export function gather(state: State, act: Activity, nowMs: number): ConsoleEvent[] {
+ const out: ConsoleEvent[] = [...runEvents(act.memo, state.wf.read?.runs ?? [], nowMs)]
+ const loop = storeOf(state).loop
+ const store = storeOf(state)
+
+ out.push(...apEvents(act.memo, { phase: loop.phase, steps: loop.steps, killed: store.killed, parked: loop.parked, reason: loop.reason }, nowMs))
+ out.push(...anatoleEvents(act.memo, state.snapshot?.anatole?.alerts ?? [], nowMs))
+ out.push(...noticeEvents(act.memo, state.notices, state.noticeSeq))
+ out.push(...denyEvents(act.memo, state.denied))
+ out.push(...modEvents(act.memo, state.mods, nowMs))
+
+ return out.sort((a, b) => a.atMs - b.atMs)
+}
+
+/** One pass: takes in what is new, evaluates alert rules over it, queues lines, and writes what is due. Never throws. */
+export async function tick(state: State, host: Host, nowMs: number = Date.now()): Promise<boolean> {
+ try {
+ const act = activityOf(state)
+
+ if (!act.loaded.isLoaded) {
+ await loadActivity(state, host)
+
+ return true
+ }
+
+ takeRing(state, act)
+
+ const derived = gather(state, act, nowMs)
+ const rows = feedLanes(state, act, nowMs)
+ const paths = pathsOf(state.cwd)
+
+ append(act, derived)
+
+ const fresh = [...act.fresh.splice(0), ...derived]
+
+ if (fresh.length > 0) {
+ for (const rule of evaluateRules(act.prefs.rules, fresh, nowMs)) {
+ act.ruleHits++
+ addNotice(state, { level: rule.level, text: `events rule "${rule.rule}": ${rule.count} new · ${rule.newest.text.slice(0, 60)}`, key: `events-rule:${rule.rule}`, go: 'events' }, nowMs)
+ }
+ }
+
+ if (state.options.eventsPersist) {
+ for (const event of derived) queueLine(paths.events, EVENTS_CAP, encodeEvent(event, act.session))
+ for (const row of rows) queueLine(paths.lanes, LANES_CAP, encodeLane(row))
+
+ if (nowMs - act.lastFlushMs >= FLUSH_MS) {
+ act.lastFlushMs = nowMs
+ await Promise.all([flush(host, state.cwd, paths.events, nowMs), flush(host, state.cwd, paths.lanes, nowMs)])
+ }
+ }
+
+ // The option turns off every write: the saved searches, pins and rules (pinned text is event text) stay in memory only.
+ if (state.options.eventsPersist && act.isPrefsDirty && !act.isPrefsForeign && nowMs - act.prefsWriteMs >= PREFS_GAP_MS) {
+ act.isPrefsDirty = false
+ act.prefsWriteMs = nowMs
+ act.prefsProblem = await replaceFile(host, state.cwd, paths.prefs, encodePrefs(act.prefs))
+ }
+
+ return fresh.length > 0 || rows.length > 0
+ } catch {
+ return false
+ }
+}
+
+/** Starts the 1.5 s pass (once per state). The page redraws only when something changed and it is the one in front. */
+export function wireActivity(state: State, host: Host): void {
+ if (state.timers.has('activity')) return
+
+ state.timers.set(
+ 'activity',
+ host.every(TICK_MS, () => {
+ void tick(state, host).then(changed => {
+ if (changed && (state.view === 'events' || state.view === 'timeline')) host.invalidate()
+ })
+ }),
+ )
+ void loadActivity(state, host)
+}
+
+export const markPrefsDirty = (state: State): void => {
+ activityOf(state).isPrefsDirty = true
+}
+
+/** What the page says about the files: the cap, the bytes read, a problem. */
+export function storeNote(state: State): string {
+ const act = activityOf(state)
+ const paths = pathsOf(state.cwd)
+ const ch = channelOf(paths.events, EVENTS_CAP)
+ const parts = [state.options.eventsPersist ? `kept in ${EVENTS_FILE} (cap ${EVENTS_CAP / 1_048_576} MiB, newest half kept past it)` : 'not kept: the eventsPersist option is off', act.loaded.isLoaded ? `read ${act.loaded.events} events from ${Math.round(act.loaded.eventsBytes / 1000)} kB` : 'reading history…']
+
+ if (act.loaded.bad > 0) parts.push(`${act.loaded.bad} bad lines skipped`)
+ if (act.loaded.newer > 0) parts.push(`${act.loaded.newer} lines from a newer console skipped`)
+ if (act.loaded.problem !== null) parts.push(act.loaded.problem)
+ if (pendingOf(paths.events) > 0) parts.push(`${pendingOf(paths.events)} waiting to write`)
+ if (errorOf(paths.events) !== null || ch.error !== null) parts.push(`write failed: ${errorOf(paths.events)}`)
+
+ return parts.join(' · ')
+}
+
+export const clearMemory = (state: State): void => {
+ const act = activityOf(state)
+ const paths = pathsOf(state.cwd)
+
+ act.log = []
+ act.seqBase = 0
+ act.lanes = newLaneStore()
+ act.version++
+ forgetChannel(paths.events)
+ forgetChannel(paths.lanes)
+}
+
+export { levelOf }
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index f504857d31..92971f9b22 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -12,6 +12,9 @@ import { navActions } from './nav-state'
import { roomActions } from './room'
import { roomPages } from './views/room'
import { watchActions } from './watch'
+import { wireActivity } from './activity-live'
+import { eventsActions } from './events-ui'
+import { timelineActions } from './timeline-ui'
import { workflowsActions } from './wf-actions'
import { missionActions } from './mission-control'
import { catalogActions } from './plugin-catalog'
@@ -68,8 +71,10 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
// The Workflows page keeps its own cursor (run, phase, agent): /ruflo next and prev move it as j and k do.
if (view === 'workflows') return actions.workflows.key(by > 0 ? 'j' : 'k')
+ if (view === 'events') return actions.events.move(by)
+ if (view === 'timeline') return actions.timeline.move(by)
- const key = view === 'claims' ? 'claim' : view === 'swarm' || view === 'timeline' || view === 'agent' ? 'agent' : 'item'
+ const key = view === 'claims' ? 'claim' : view === 'swarm' || view === 'agent' ? 'agent' : 'item'
state.select[key] += by
@@ -82,6 +87,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
wireAnatole(state, host)
wireWorkflows(state, host)
+ wireActivity(state, host)
const actions: Actions = {
view: setView,
remember: () => {
@@ -378,6 +384,8 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
loops: loopActions(state, host, runner),
optimizer: optimizerActions(state, () => host.invalidate(), id => void runner.runById(id, ''), question => actions.ask.ask(question, 'overview')),
watch: watchActions(state, () => host.invalidate(), (question, view) => actions.ask.ask(question, view)),
+ events: eventsActions(state, host, () => host.invalidate(), (spec, why = 'that cannot run here') => runner.ask(spec, why), question => actions.ask.ask(question, 'events')),
+ timeline: timelineActions(state, host, () => host.invalidate(), id => setView(id), (spec, why = 'that cannot run here') => runner.ask(spec, why), question => actions.ask.ask(question, 'timeline')),
room: roomActions(state, () => host.invalidate(), (id, text) => runner.runById(id, text), () => roomPages(state)),
navigator: navActions(state, () => host.invalidate(), view => actions.view(view)),
catalog: catalogActions(state, host, runner, text => actions.term.load('claude', text)),
diff --git a/plugins/ruflo-console/hooks/commands.ts b/plugins/ruflo-console/hooks/commands.ts
index a6f93dd922..29d20d9786 100644
--- a/plugins/ruflo-console/hooks/commands.ts
+++ b/plugins/ruflo-console/hooks/commands.ts
@@ -27,6 +27,8 @@ export type Intent =
| { kind: 'notices'; isClear: boolean }
| { kind: 'quiet'; arg: string }
| { kind: 'autopilot'; arg: string }
+ | { kind: 'events'; args: string[] }
+ | { kind: 'timeline'; args: string[] }
| { kind: 'unknown'; word: string }
export function parseRuflo(args: string): Intent {
@@ -93,6 +95,11 @@ export function parseRuflo(args: string): Intent {
case 'dump':
case 'text':
return { kind: 'dump', view: second === '' ? null : viewOf(second) }
+ // `/ruflo events [kind|level|since:15m|"query"|window <w>|clear|forget|export <path>|follow <ref>|pin|rule]` and `/ruflo timeline [5m|…|session|zoom in|out|follow <ref>|export <path>]` (ADR-474); bare, each just opens its page.
+ case 'events':
+ return words.length === 1 ? { kind: 'open', view: 'events' } : { kind: 'events', args: words.slice(1) }
+ case 'timeline':
+ return words.length === 1 ? { kind: 'open', view: 'timeline' } : { kind: 'timeline', args: words.slice(1) }
case 'filter':
return { kind: 'filter', filter: (EVENT_KINDS as readonly string[]).includes(second) ? (second as EventKind) : 'all' }
default: {
@@ -124,7 +131,10 @@ export const HELP = [
' /ruflo palette [query] the command palette (key p): spawn, claims, swarm, votes, workers, memory',
' /ruflo run <entry> [text] run a palette entry by id, e.g. run spawn-coder, run route fix the login bug',
' /ruflo next | prev move the selection (keys j / k)',
- ' /ruflo filter <kind> events view filter: all, swarm, claims, federation, learning, tools, mods, missions',
+ ' /ruflo filter <kind> events view filter: all, swarm, claims, federation, learning, tools, mods, missions, workflows, autopilot, anatole, notices',
+ ' /ruflo events [kind|level|since:15m|"query"|window <session|15m|1h|24h|all>|clear|forget|export <path>|follow <ref>|pin|rule]',
+ ' the Events page: filter, search (words "phrase" -not kind:x level:bad agent:x src:x since:1h a|b /re/), follow an agent, claim or run, export, forget the kept history',
+ ' /ruflo timeline [5m|15m|1h|6h|24h|session|zoom <in|out>|follow <ref>|export <path>] the Timeline page window, zoom, a lane\'s events, a lane summary export',
'',
'Other mods (answered by their own plugin)',
' /ruflo mods ruflo-mods: what this session routed, recorded and tightened (was /ruflo-mods)',
diff --git a/plugins/ruflo-console/hooks/data/activity-store.ts b/plugins/ruflo-console/hooks/data/activity-store.ts
new file mode 100644
index 0000000000..ad3ac64b67
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/activity-store.ts
@@ -0,0 +1,265 @@
+/**
+ * The one persisted store behind the Events and Timeline pages (ADR-474). Three files under the project's `.claude-flow/console/`:
+ * `events.jsonl` (what happened), `lanes.jsonl` (when each lane was busy, and its tool calls per minute) and `events-prefs.json`
+ * (saved searches, pins, alert rules). Every line is `{"v":1,...}`; a line that is not JSON, is cut off, or says a newer version is
+ * counted and skipped, never thrown on. Everything written is washed first (data/event-mask.ts): only masked text reaches the disk.
+ * This module is pure (text in, text out); the one write path that appends and rotates is hooks/activity-io.ts.
+ */
+import { countOf, timeOf } from './safe'
+import { maskLine } from './event-mask'
+import { isLevel, levelOf, type Level } from './event-severity'
+import { isEventKind, type ConsoleEvent, type EventKind } from './events'
+
+export const DIR = '.claude-flow/console'
+export const EVENTS_FILE = `${DIR}/events.jsonl`
+export const LANES_FILE = `${DIR}/lanes.jsonl`
+export const PREFS_FILE = `${DIR}/events-prefs.json`
+export const EXPORT_DIR = `${DIR}/exports`
+
+export const SCHEMA = 1
+export const EVENTS_CAP = 2 * 1024 * 1024
+export const LANES_CAP = 1024 * 1024
+export const PREFS_CAP = 64 * 1024
+/** A file is read whole only up to this (the cap plus one batch); the page parses the last TAIL_BYTES of it. */
+export const READ_MAX = 2_400_000
+export const TAIL_BYTES = 1_000_000
+export const MAX_LOG = 10_000
+export const MAX_LANE_ROWS = 20_000
+export const LINE_MAX = 1_000
+
+export type Decoded<T> = { items: T[]; bad: number; newer: number; /** Bytes parsed, for the page to show next to the cap. */ bytes: number }
+
+const parseObject = (line: string): Record<string, unknown> | null => {
+ if (line.length < 2 || line.length > LINE_MAX * 3 || line[0] !== '{') return null
+
+ try {
+ const value: unknown = JSON.parse(line)
+
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null
+ } catch {
+ return null
+ }
+}
+
+/** The lines of the last `tailBytes` of `text`, without a first line that may have been cut in two. */
+export function tailLines(text: string, tailBytes = TAIL_BYTES): { lines: string[]; bytes: number } {
+ const cut = text.length > tailBytes
+ const body = cut ? text.slice(text.length - tailBytes) : text
+ const lines = body.split('\n')
+
+ if (cut) lines.shift()
+
+ return { lines: lines.filter(line => line !== ''), bytes: body.length }
+}
+
+// ---------------------------------------------------------------------------------------------------------------- events
+
+/** One event as a line (with its newline): level decided now, text washed, every field a known type. */
+export function encodeEvent(event: ConsoleEvent, session = ''): string {
+ const text = maskLine(event.text, 240)
+ const ref = event.ref === undefined ? undefined : maskLine(event.ref, 80)
+ const agent = event.agentId === undefined ? undefined : maskLine(event.agentId, 80)
+
+ return `${JSON.stringify({ v: SCHEMA, t: Math.round(event.atMs), kind: event.kind, level: levelOf(event.kind, text), text, ...(agent !== undefined && agent !== '' && { agent }), ...(ref !== undefined && ref !== '' && { ref }), ...(event.src !== undefined && { src: maskLine(event.src, 24) }), ...(session !== '' && { s: session }) })}\n`
+}
+
+/** One line to an event, or null (also null for a newer schema: counted by the caller). An unknown kind becomes `other` with its name kept in the words. */
+export function decodeEvent(line: string): ConsoleEvent | 'newer' | null {
+ const r = parseObject(line)
+
+ if (r === null) return null
+ if (typeof r.v === 'number' && r.v > SCHEMA) return 'newer'
+ const at = timeOf(r.t)
+
+ if (r.v !== SCHEMA || at === undefined || at < 0 || typeof r.text !== 'string' || typeof r.kind !== 'string') return null
+
+ const kind: EventKind = isEventKind(r.kind) ? r.kind : 'other'
+ const text = maskLine(kind !== 'other' || r.kind === 'other' ? r.text : `[${maskLine(r.kind, 20)}] ${r.text}`, 240)
+
+ return {
+ atMs: at,
+ kind,
+ text,
+ ...(typeof r.agent === 'string' && r.agent !== '' && { agentId: maskLine(r.agent, 80) }),
+ ...(typeof r.ref === 'string' && r.ref !== '' && { ref: maskLine(r.ref, 80) }),
+ src: typeof r.src === 'string' ? maskLine(r.src, 24) : 'history',
+ }
+}
+
+/** The events in the tail of a log file, oldest first, one of each (two consoles may have logged the same observation), at most MAX_LOG. */
+export function decodeEvents(text: string | null, tailBytes = TAIL_BYTES): Decoded<ConsoleEvent> {
+ if (text === null) return { items: [], bad: 0, newer: 0, bytes: 0 }
+
+ const { lines, bytes } = tailLines(text, tailBytes)
+ const seen = new Set<string>()
+ const items: ConsoleEvent[] = []
+ let bad = 0
+ let newer = 0
+
+ for (const line of lines) {
+ const event = decodeEvent(line)
+
+ if (event === null) bad++
+ else if (event === 'newer') newer++
+ else {
+ const key = `${Math.floor(event.atMs / 1000)}|${event.kind}|${event.text}`
+
+ if (!seen.has(key)) {
+ seen.add(key)
+ items.push(event)
+ }
+ }
+ }
+
+ items.sort((a, b) => a.atMs - b.atMs)
+
+ return { items: items.length > MAX_LOG ? items.slice(items.length - MAX_LOG) : items, bad, newer, bytes }
+}
+
+/** The newest part of a log, from a line start, about half of `cap`: what is kept when the file passes its cap. */
+export function keepNewestHalf(text: string, cap: number): string {
+ if (text.length <= cap) return text
+
+ const from = text.length - Math.floor(cap / 2)
+ const at = text.indexOf('\n', from)
+
+ return at === -1 ? '' : text.slice(at + 1)
+}
+
+// ---------------------------------------------------------------------------------------------------------------- lanes
+
+export type LaneGroup = 'ruflo' | 'claude' | 'workflow' | 'mission' | 'autopilot'
+export const LANE_GROUPS: readonly LaneGroup[] = ['ruflo', 'claude', 'workflow', 'mission', 'autopilot']
+export const isLaneGroup = (value: unknown): value is LaneGroup => (LANE_GROUPS as readonly unknown[]).includes(value)
+
+export type LaneSpan = { lane: string; group: LaneGroup; label: string; fromMs: number; toMs: number; busy: boolean }
+/** Tool calls of one lane in one minute (`min` is the minute index since the epoch), by tool. */
+export type LaneTick = { lane: string; group: LaneGroup; label: string; min: number; n: number; tools: Record<string, number> }
+export type LaneRow = ({ k: 'span' } & LaneSpan) | ({ k: 'tick' } & LaneTick)
+
+export function encodeLane(row: LaneRow): string {
+ const base = { v: SCHEMA, t: row.k, l: maskLine(row.lane, 80), g: row.group, n: maskLine(row.label, 60) }
+
+ if (row.k === 'span') return `${JSON.stringify({ ...base, a: Math.round(row.fromMs), b: Math.round(row.toMs), y: row.busy ? 1 : 0 })}\n`
+
+ const tools = Object.fromEntries(Object.entries(row.tools).slice(0, 12).map(([name, n]) => [maskLine(name, 40), Math.max(0, Math.round(n))]))
+
+ return `${JSON.stringify({ ...base, m: row.min, c: row.n, tools })}\n`
+}
+
+export function decodeLane(line: string): LaneRow | 'newer' | null {
+ const r = parseObject(line)
+
+ if (r === null) return null
+ if (typeof r.v === 'number' && r.v > SCHEMA) return 'newer'
+ if (r.v !== SCHEMA || typeof r.l !== 'string' || !isLaneGroup(r.g) || typeof r.n !== 'string') return null
+
+ const lane = maskLine(r.l, 80)
+ const label = maskLine(r.n, 60)
+
+ const from = timeOf(r.a)
+ const to = timeOf(r.b)
+
+ if (r.t === 'span' && from !== undefined && to !== undefined && to >= from && from >= 0) return { k: 'span', lane, group: r.g, label, fromMs: from, toMs: to, busy: r.y === 1 }
+
+ const minute = countOf(r.m)
+ const calls = countOf(r.c)
+
+ if (r.t === 'tick' && minute !== undefined && calls !== undefined) {
+ const tools = Object.create(null) as Record<string, number>
+
+ if (typeof r.tools === 'object' && r.tools !== null) {
+ for (const [name, n] of Object.entries(r.tools as Record<string, unknown>).slice(0, 12)) {
+ const n2 = countOf(n)
+
+ if (n2 !== undefined) tools[maskLine(name, 40)] = n2
+ }
+ }
+
+ return { k: 'tick', lane, group: r.g, label, min: minute, n: calls, tools }
+ }
+
+ return null
+}
+
+export function decodeLanes(text: string | null, tailBytes = TAIL_BYTES): Decoded<LaneRow> {
+ if (text === null) return { items: [], bad: 0, newer: 0, bytes: 0 }
+
+ const { lines, bytes } = tailLines(text, tailBytes)
+ const items: LaneRow[] = []
+ let bad = 0
+ let newer = 0
+
+ for (const line of lines) {
+ const row = decodeLane(line)
+
+ if (row === null) bad++
+ else if (row === 'newer') newer++
+ else items.push(row)
+ }
+
+ return { items: items.length > MAX_LANE_ROWS ? items.slice(items.length - MAX_LANE_ROWS) : items, bad, newer, bytes }
+}
+
+// ---------------------------------------------------------------------------------------------------------------- prefs
+
+export const MAX_SEARCHES = 20
+export const MAX_PINS = 50
+export const MAX_RULES = 10
+
+export type SavedSearch = { name: string; q: string }
+export type Pin = { atMs: number; kind: ConsoleEvent['kind']; text: string; level: Level }
+export type Prefs = { searches: SavedSearch[]; pins: Pin[]; rules: SavedSearch[] }
+export type PrefsRead = { prefs: Prefs; problem: string | null; isForeign: boolean }
+
+export const emptyPrefs = (): Prefs => ({ searches: [], pins: [], rules: [] })
+
+const named = (list: unknown, max: number): SavedSearch[] => {
+ if (!Array.isArray(list)) return []
+
+ return list.flatMap(item => {
+ const r = typeof item === 'object' && item !== null ? (item as Record<string, unknown>) : null
+
+ if (r === null || typeof r.name !== 'string' || typeof r.q !== 'string') return []
+
+ const name = maskLine(r.name, 24)
+ const q = maskLine(r.q, 200)
+
+ return name === '' || q === '' ? [] : [{ name, q }]
+ }).slice(0, max)
+}
+
+/** The prefs file read tolerantly: a newer schema is kept untouched (isForeign: never written over), damage gives the empty set and a problem. */
+export function decodePrefs(text: string | null): PrefsRead {
+ if (text === null) return { prefs: emptyPrefs(), problem: null, isForeign: false }
+
+ let value: unknown
+
+ try {
+ value = JSON.parse(text)
+ } catch {
+ return { prefs: emptyPrefs(), problem: 'the saved searches file could not be read, so it starts empty and is replaced on the next change', isForeign: false }
+ }
+
+ const r = typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null
+
+ if (r === null) return { prefs: emptyPrefs(), problem: 'the saved searches file is not an object', isForeign: false }
+ if (typeof r.v === 'number' && r.v > SCHEMA) return { prefs: emptyPrefs(), problem: `the saved searches file is from a newer console (v${r.v}) and is left as it is`, isForeign: true }
+
+ const pins = (Array.isArray(r.pins) ? r.pins : []).flatMap((item): Pin[] => {
+ const p = typeof item === 'object' && item !== null ? (item as Record<string, unknown>) : null
+
+ const pinAt = p === null ? undefined : timeOf(p.atMs)
+
+ if (p === null || pinAt === undefined || typeof p.text !== 'string') return []
+
+ const kind = isEventKind(p.kind) ? p.kind : 'other'
+ const text = maskLine(p.text, 240)
+
+ return [{ atMs: pinAt, kind, text, level: isLevel(p.level) ? p.level : levelOf(kind, text) }]
+ })
+
+ return { prefs: { searches: named(r.searches, MAX_SEARCHES), pins: pins.slice(0, MAX_PINS), rules: named(r.rules, MAX_RULES) }, problem: null, isForeign: false }
+}
+
+export const encodePrefs = (prefs: Prefs): string => `${JSON.stringify({ v: SCHEMA, searches: prefs.searches.slice(0, MAX_SEARCHES), pins: prefs.pins.slice(0, MAX_PINS), rules: prefs.rules.slice(0, MAX_RULES) })}\n`
diff --git a/plugins/ruflo-console/hooks/data/ap-journal.ts b/plugins/ruflo-console/hooks/data/ap-journal.ts
index b87020ce7e..b0849685dc 100644
--- a/plugins/ruflo-console/hooks/data/ap-journal.ts
+++ b/plugins/ruflo-console/hooks/data/ap-journal.ts
@@ -8,6 +8,7 @@
import { ESCAPES, HIDDEN, INVISIBLE } from './parse'
import { maskSecrets } from './workflows'
import { AUTOPILOT_DIR } from './ap-envelope'
+import { appendArgv } from './append-argv'
export const JOURNAL_FILE = `${AUTOPILOT_DIR}/journal.jsonl`
/** A journal over this is read no further (the cap is drawn): the loop then compacts by checkpoint (data/ap-loop.ts `compactState`). */
@@ -171,8 +172,8 @@ export function parseJournal(text: string | null): ParsedJournal {
return { events, bad: lines.length - events.length, isCapped: false }
}
-/** Fixed argv that appends stdin to the journal: GNU dd with O_APPEND; no shell, the path is one element. */
-export const appendArgv = (path: string): readonly string[] => ['dd', `of=${path}`, 'oflag=append', 'conv=notrunc', 'status=none']
+/** Fixed argv that appends stdin to the journal: the shared GNU dd append (data/append-argv.ts), one O_APPEND block per batch. */
+export { appendArgv }
/** Fixed argv that creates a flag file (the kill switch) and its folder: GNU install -D from an empty stdin. */
export const touchArgv = (path: string): readonly string[] => ['install', '-D', '-m', '600', '/dev/null', path]
diff --git a/plugins/ruflo-console/hooks/data/append-argv.ts b/plugins/ruflo-console/hooks/data/append-argv.ts
new file mode 100644
index 0000000000..c99b855f0a
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/append-argv.ts
@@ -0,0 +1,8 @@
+/**
+ * The one argv that appends stdin to a log: GNU `dd` with O_APPEND, no shell, the path one element. Shared by the Events store
+ * (activity-io.ts) and the autopilot journal (ap-journal.ts), so both keep a batch whole when two consoles write one file.
+ * `bs=1M iflag=fullblock` matters: dd's default 512-byte blocks write a batch from a pipe in many short `write` calls, so two
+ * writers' batches interleave in the middle of a line (measured: 1094 of 4800 lines torn with two writers). One block is one
+ * O_APPEND write, which the kernel keeps whole. A leaf: no imports.
+ */
+export const appendArgv = (path: string): readonly string[] => ['dd', `of=${path}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none']
diff --git a/plugins/ruflo-console/hooks/data/event-export.ts b/plugins/ruflo-console/hooks/data/event-export.ts
new file mode 100644
index 0000000000..48924b88f2
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-export.ts
@@ -0,0 +1,149 @@
+/**
+ * Exporting what the Events and Timeline pages show (ADR-474): events as markdown or JSONL, lane summaries as markdown or CSV. The
+ * target is a name under `.claude-flow/console/exports/` or a path inside the project; `..`, a link on the way, a bad extension and an
+ * existing file are all refused, and the text is washed and capped before it is built. The write itself is a confirm-gated fixed argv.
+ */
+import { isoOf } from './safe'
+import type { ActionSpec } from '../actions'
+import { levelOf } from './event-severity'
+import { maskLine } from './event-mask'
+import type { ConsoleEvent } from './events'
+import { refOf } from './events'
+import { EXPORT_DIR } from './activity-store'
+import { checkNoLinks, dirOf, newFileArgv, type PathCheck } from './wf-file'
+import { clockOf, type Concurrency, type LaneView } from './timeline-model'
+import type { ReaderFs } from './files'
+
+export type Format = 'md' | 'jsonl' | 'csv'
+export const MAX_EXPORT_BYTES = 400_000
+export const MAX_EXPORT_EVENTS = 2_000
+
+const NAME = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,99}\.(md|jsonl|csv)$/
+const bytes = (text: string): number => new TextEncoder().encode(text).length
+
+export const formatOf = (path: string): Format | null => (/\.md$/.test(path) ? 'md' : /\.jsonl$/.test(path) ? 'jsonl' : /\.csv$/.test(path) ? 'csv' : null)
+
+/** The absolute path a name or relative path means (a bare file name goes under the exports folder), or why it is refused. Lexical only; see `checkNoLinks` for the disk half. */
+export function resolveTarget(input: string, cwd: string, allowed: readonly Format[]): PathCheck {
+ const raw = input.trim()
+ const root = cwd.replace(/\/+$/, '')
+
+ if (raw === '') return { ok: false, why: 'give a file name ending in .md, .jsonl or .csv' }
+ if (raw.length > 300) return { ok: false, why: 'a path over 300 characters is refused' }
+ // eslint-disable-next-line no-control-regex
+ if (/[\u0000-\u001f\u007f-\u009f\\]/.test(raw)) return { ok: false, why: 'a path with control characters or a backslash is refused' }
+ if (raw.startsWith('~')) return { ok: false, why: 'write the path out: ~ is not expanded here' }
+ if (raw.split('/').includes('..')) return { ok: false, why: 'a path with .. is refused: name a file inside the project' }
+ if (root === '' || !root.startsWith('/')) return { ok: false, why: 'no project folder is known, so the path cannot be placed' }
+
+ const absolute = raw.startsWith('/') ? raw : raw.includes('/') ? `${root}/${raw}` : `${root}/${EXPORT_DIR}/${raw}`
+ const parts = absolute.split('/').filter(part => part !== '' && part !== '.')
+ const path = `/${parts.join('/')}`
+ const name = parts[parts.length - 1] ?? ''
+ const format = formatOf(name)
+
+ if (!NAME.test(name) || format === null) return { ok: false, why: 'the file name must be letters, digits, dots, dashes, underscores or spaces, and end in .md, .jsonl or .csv' }
+ if (!allowed.includes(format)) return { ok: false, why: `this export can be ${allowed.map(item => `.${item}`).join(' or ')}, not .${format}` }
+ if (!path.startsWith(`${root}/`)) return { ok: false, why: `outside the project: only paths under ${root} are written` }
+
+ // A markdown file is a command, an agent or a skill when it lands in `.claude/`, and a hook sample in `.git/`: event words are agent output, so those folders are not export targets.
+ const hidden = path.slice(root.length + 1).split('/').slice(0, -1).find(part => part.startsWith('.') && part !== '.claude-flow')
+
+ if (hidden !== undefined) return { ok: false, why: `${hidden} is a hidden folder: exports go to .claude-flow/console/exports/ or a visible folder in the project` }
+
+ return { ok: true, path }
+}
+
+const cell = (value: string): string => maskLine(value, 120).replace(/[|]/g, '/')
+const csv = (value: string | number): string => {
+ const text = String(value)
+ // A leading = + - @ would be a formula in a spreadsheet.
+ const safe = /^[=+\-@]/.test(text) ? `'${text}` : text
+
+ return /[",\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe
+}
+
+function capped(text: string, isPlain = false): string {
+ if (bytes(text) <= MAX_EXPORT_BYTES) return text
+
+ let head = text.slice(0, Math.floor(MAX_EXPORT_BYTES * 0.9))
+
+ while (bytes(head) > MAX_EXPORT_BYTES - 200) head = head.slice(0, Math.floor(head.length * 0.9))
+
+ const kept = head.slice(0, Math.max(0, head.lastIndexOf('\n')))
+
+ return isPlain ? `${kept}\n` : `${kept}\n\n> cut here: capped at ${MAX_EXPORT_BYTES / 1000} kB\n`
+}
+
+/** The events (newest last, at most MAX_EXPORT_EVENTS of the newest) as markdown or JSONL. `title` says what the filter was. */
+export function eventsText(events: readonly ConsoleEvent[], format: 'md' | 'jsonl', title: string, nowMs: number): string {
+ const list = events.slice(-MAX_EXPORT_EVENTS)
+
+ if (format === 'jsonl') return capped(list.map(event => `${JSON.stringify({ v: 1, t: event.atMs, kind: event.kind, level: levelOf(event.kind, event.text), text: maskLine(event.text, 240), ...(refOf(event) !== undefined && { ref: maskLine(refOf(event) as string, 80) }) })}\n`).join(''), true)
+
+ return capped(
+ [
+ `# Events: ${cell(title)}`,
+ '',
+ `${list.length} of ${events.length} events, exported ${new Date(nowMs).toISOString()}. Text is washed: credentials, control characters and home paths are masked.`,
+ '',
+ '| time | level | kind | event |',
+ '|---|---|---|---|',
+ ...list.map(event => `| ${isoOf(event.atMs).slice(0, 19)}Z | ${levelOf(event.kind, event.text)} | ${event.kind} | ${cell(event.text)} |`),
+ '',
+ ].join('\n'),
+ )
+}
+
+export type LaneExport = { lanes: readonly LaneView[]; concurrency: Concurrency; fromMs: number; toMs: number; busiest: { atMs: number; n: number } | null }
+
+/** Lane summaries and the concurrency figures, as markdown or CSV. */
+export function lanesText(data: LaneExport, format: 'md' | 'csv', nowMs: number): string {
+ const rows = data.lanes.slice(0, 500)
+
+ if (format === 'csv') return capped(['group,lane,busy_pct,busy_s,observed_s,calls,longest_busy_s,last_seen', ...rows.map(lane => [lane.group, cell(lane.label), lane.busyPct ?? '', Math.round(lane.busyMs / 1000), Math.round(lane.observedMs / 1000), lane.calls, Math.round(lane.longestMs / 1000), lane.lastAtMs > 0 ? isoOf(lane.lastAtMs) : ''].map(csv).join(',')), ''].join('\n'), true)
+
+ return capped(
+ [
+ `# Timeline ${clockOf(data.fromMs, true)} to ${clockOf(data.toMs, true)}`,
+ '',
+ `${rows.length} lanes, exported ${new Date(nowMs).toISOString()}.`,
+ '',
+ `Concurrency: peak ${data.concurrency.peak}, mean ${data.concurrency.mean} lanes busy at once${data.concurrency.peakAtMs === null ? '' : ` (peak at ${clockOf(data.concurrency.peakAtMs)})`}.${data.busiest === null ? '' : ` Busiest minute ${clockOf(data.busiest.atMs)} with ${data.busiest.n} tool calls.`}`,
+ '',
+ '| group | lane | busy | calls | longest busy | last seen |',
+ '|---|---|---|---|---|---|',
+ ...rows.map(lane => `| ${lane.group} | ${cell(lane.label)} | ${lane.busyPct === null ? 'n/a' : `${lane.busyPct}%`} | ${lane.calls} | ${Math.round(lane.longestMs / 1000)} s | ${lane.lastAtMs > 0 ? clockOf(lane.lastAtMs, true) : 'n/a'} |`),
+ '',
+ ].join('\n'),
+ )
+}
+
+/** The checked, confirm-gated write: refuses a link or an existing file before it ever asks. */
+export async function exportSpecFor(fs: Pick<ReaderFs, 'stat'>, cwd: string, target: string, content: string, label: string, allowed: readonly Format[]): Promise<{ ok: true; spec: ActionSpec } | { ok: false; why: string }> {
+ const placed = resolveTarget(target, cwd, allowed)
+
+ if (!placed.ok) return placed
+
+ const clear = await checkNoLinks(fs, placed.path, { cwd: cwd.replace(/\/+$/, '') })
+
+ if (!clear.ok) return clear
+
+ const hasDir = (await fs.stat(dirOf(placed.path)).catch(() => undefined)) !== undefined
+
+ return {
+ ok: true,
+ spec: {
+ label: `write ${label}`,
+ args: [],
+ argv: newFileArgv(placed.path, hasDir),
+ stdin: content,
+ expect: `a new file at ${placed.path}`,
+ declared: 'write',
+ shows: `write ${placed.path} (${bytes(content)} bytes; never overwrites)`,
+ note: 'writes one new file inside the project; a file that already exists makes it fail instead of replacing it (a missing folder is made with GNU install, which macOS lacks)',
+ timeoutMs: 10_000,
+ verifyLocal: async host => (await host.fs.stat(placed.path).catch(() => undefined)) !== undefined,
+ },
+ }
+}
diff --git a/plugins/ruflo-console/hooks/data/event-group.ts b/plugins/ruflo-console/hooks/data/event-group.ts
new file mode 100644
index 0000000000..8bb15dc0c6
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-group.ts
@@ -0,0 +1,93 @@
+/**
+ * Grouping and correlation for the Events page (ADR-474): bursts of the same kind of line collapse into one row with a count, a ref
+ * (an agent, a claim, a run) gathers its events, and `follow` keeps one ref's events with whatever happened within 30 s of them.
+ * Pure over an oldest-first list.
+ */
+import { refOf, type ConsoleEvent } from './events'
+
+export const BURST_GAP_MS = 30_000
+export const FOLLOW_SPAN_MS = 30_000
+
+/** The line with its numbers, hex runs and quoted names turned into placeholders: two lines of one template share it. */
+export function templateOf(text: string): string {
+ return text.replace(/\b[0-9a-f]{6,}\b/gi, '#').replace(/\d+(?:\.\d+)?/g, '#').replace(/"[^"]*"/g, '"_"').toLowerCase()
+}
+
+export type Row = {
+ /** The newest event of the burst: what the row shows. */
+ event: ConsoleEvent
+ /** Every event of the burst, oldest first (one for a plain row). */
+ members: ConsoleEvent[]
+ /** `<atMs>:<kind>:<length>:<hash>` of the newest member, the row's identity (the page adds `~n` where two rows are still identical). */
+ id: string
+}
+
+export const idOf = (event: ConsoleEvent): string => `${event.atMs}:${event.kind}:${event.text.length}:${hashOf(event.text)}`
+
+/** A short hash of the words (FNV-1a, 32 bits, base 36): two events of one millisecond and one length no longer share an id. */
+function hashOf(text: string): string {
+ let h = 0x811c9dc5
+
+ for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193)
+
+ return (h >>> 0).toString(36)
+}
+
+/** Newest-last events as rows: neighbours of one kind and template inside `gapMs` of each other are one row. */
+export function collapse(events: readonly ConsoleEvent[], gapMs = BURST_GAP_MS): Row[] {
+ const rows: Row[] = []
+ const open = new Map<string, Row>()
+
+ for (const event of events) {
+ const key = `${event.kind}|${event.agentId ?? ''}|${templateOf(event.text)}`
+ const row = open.get(key)
+
+ if (row !== undefined && event.atMs - row.event.atMs <= gapMs) {
+ row.members.push(event)
+ row.event = event
+ row.id = idOf(event)
+ continue
+ }
+
+ const fresh: Row = { event, members: [event], id: idOf(event) }
+
+ open.set(key, fresh)
+ rows.push(fresh)
+ }
+
+ return rows
+}
+
+/** The events of `ref`, and every event within `spanMs` before or after any of them. A ref nothing matches gives []. */
+export function follow(events: readonly ConsoleEvent[], ref: string, spanMs = FOLLOW_SPAN_MS): { own: number; events: ConsoleEvent[] } {
+ const wanted = ref.toLowerCase()
+ const own = events.filter(event => (refOf(event) ?? '').toLowerCase() === wanted || `agent:${event.agentId ?? ''}`.toLowerCase() === wanted)
+
+ if (own.length === 0) return { own: 0, events: [] }
+
+ const marks = own.map(event => event.atMs).sort((x, y) => x - y)
+
+ return {
+ own: own.length,
+ events: events.filter(event => {
+ let lo = 0
+ let hi = marks.length
+
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1
+
+ if ((marks[mid] as number) < event.atMs) lo = mid + 1
+ else hi = mid
+ }
+
+ return Math.abs((marks[lo] ?? Infinity) - event.atMs) <= spanMs || Math.abs((marks[lo - 1] ?? Infinity) - event.atMs) <= spanMs
+ }),
+ }
+}
+
+/** The `n` events before and after `events[index]`, oldest first; nothing for an index outside the list. */
+export function neighbours(events: readonly ConsoleEvent[], index: number, n = 5): { before: ConsoleEvent[]; after: ConsoleEvent[] } {
+ if (index < 0 || index >= events.length) return { before: [], after: [] }
+
+ return { before: events.slice(Math.max(0, index - n), index), after: events.slice(index + 1, index + 1 + n) }
+}
diff --git a/plugins/ruflo-console/hooks/data/event-mask.ts b/plugins/ruflo-console/hooks/data/event-mask.ts
new file mode 100644
index 0000000000..b684338edd
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-mask.ts
@@ -0,0 +1,33 @@
+/**
+ * One washing function for everything the Events and Timeline pages persist, draw, copy or export (ADR-474): escapes, control, bidi and
+ * tag characters are dropped, credential-shaped text is masked, and a home-directory path loses its user name. Pure.
+ */
+import { ESCAPES, HIDDEN, INVISIBLE } from './parse'
+import { maskSecrets } from './workflows'
+
+/** `token=abc`, `password: hunter2`, `Authorization: Basic xyz`: a key word followed by a value. */
+const KEYED = /\b(?:token|secret|passw(?:or)?d|passwd|api[_-]?key|apikey|authorization|credential|private[_-]?key)\b(\s*[=:]\s*)(?:Bearer\s+|Basic\s+)?\S+/gi
+const HOME_PATH = /\/(?:home|Users)\/[^/\s'"]+/g
+const TAGS = /[\u{E0000}-\u{E007F}]/gu
+/** A control character that is not white space is deleted, not turned into a space: `sk-ant-AAAA<NUL>BBBB` is one credential, and a space would leave `BBBB` unmasked on disk. */
+// eslint-disable-next-line no-control-regex
+const CONTROLS = /[\u0000-\u0008\u000e-\u001f\u007f-\u0084\u0086-\u009f]/g
+/** `[email protected]` (bounded, so a long run of word characters cannot make it slow). */
+const EMAIL = /\b[\w.+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})+\b/g
+/** A cookie header carries a session: the whole rest of the line goes. */
+const COOKIE = /\b((?:set-)?cookie)\b(\s*[=:]\s*)\S.*/gi
+/** A base64 secret with `/` or `+` in it (an AWS secret key is 40 of them); maskSecrets' long-run rule stops at the slash. Needs all three of upper, lower and digit, so a path or a word is left alone. */
+const BASE64 = /\b(?=[A-Za-z0-9+/]{32,})(?=[A-Za-z0-9+/]*[A-Z])(?=[A-Za-z0-9+/]*[a-z])(?=[A-Za-z0-9+/]*\d)[A-Za-z0-9+/]{32,}={0,2}/g
+const WIN_HOME = /\b[A-Za-z]:\\Users\\[^\\\s'"]+/g
+
+export const MASK = '‹masked›'
+
+/** `value` washed and clipped to `max` characters (an ellipsis marks a cut). Never throws; a non-string is ''. */
+export function maskLine(value: unknown, max = 240): string {
+ if (typeof value !== 'string') return ''
+
+ const washed = value.slice(0, max * 4).replace(ESCAPES, '').replace(TAGS, '').replace(INVISIBLE, '').replace(CONTROLS, '').replace(HIDDEN, ' ').replace(/\s+/g, ' ').trim()
+ const masked = maskSecrets(washed.replace(COOKIE, (_all, name: string, sep: string) => `${name}${sep}${MASK}`).replace(KEYED, (_all, sep: string) => `credential${sep}${MASK}`)).replace(BASE64, MASK).replace(EMAIL, MASK).replace(HOME_PATH, '~').replace(WIN_HOME, '~')
+
+ return masked.length > max ? `${masked.slice(0, Math.max(0, max - 1))}…` : masked
+}
diff --git a/plugins/ruflo-console/hooks/data/event-query.ts b/plugins/ruflo-console/hooks/data/event-query.ts
new file mode 100644
index 0000000000..c8c6b7c101
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-query.ts
@@ -0,0 +1,331 @@
+/**
+ * The Events page's query language (ADR-474), small and safe:
+ * words (all must match) · "a quoted phrase" · -negation · kind:swarm level:bad agent:tester src:autopilot ref:run:wf_1 since:15m
+ * a|b inside a value is OR · /regex/ (or /regex/i) with a size cap, no nested quantifiers, no back-references, and a text cap.
+ * `parseQuery` never throws: a problem is returned as an error line for the page to show, and the rest of the query still applies.
+ * `matches` is pure over an event and runs on text the page already bounded.
+ */
+import type { ConsoleEvent } from './events'
+import { refOf } from './events'
+import { levelOf, type Level } from './event-severity'
+
+export const QUERY_MAX = 200
+export const REGEX_MAX = 48
+/** An event's text is cut to this before a regex sees it, so no pattern can run for long. */
+export const REGEX_TEXT_MAX = 200
+const MAX_TERMS = 12
+const MAX_ALTS = 8
+const FIELDS = ['kind', 'level', 'agent', 'src', 'ref'] as const
+
+export type Field = (typeof FIELDS)[number]
+export type Term = { neg: boolean; type: 'word' | 'field' | 'regex'; field?: Field; /** Lower-cased alternatives (OR); one word or phrase for a plain term. */ alts: string[]; re?: RegExp }
+export type Query = { terms: Term[]; sinceMs: number | null; errors: string[]; /** The query as typed, trimmed and capped. */ source: string }
+
+/**
+ * A pattern is also refused when it is slow in aggregate: even one quantifier is O(n^2) of the 200 characters on a text that does not
+ * match (`.*.*x` cost about 280 microseconds a line, so 10 000 lines held the page for seconds). Callers that scan many events pass
+ * a Budget; once its milliseconds are spent a regex term stops being evaluated and the caller says how many events were not searched.
+ */
+export type Budget = { ms: number; spentMs: number; skipped: number }
+export const budgetOf = (ms: number): Budget => ({ ms, spentMs: 0, skipped: 0 })
+export const REGEX_BUDGET_MS = 120
+
+export const EMPTY_QUERY: Query = { terms: [], sinceMs: null, errors: [], source: '' }
+
+const UNIT: Record<string, number> = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }
+
+/** `15m`, `1h`, `2d`, `90s` as milliseconds (at most 30 days), or null. */
+export function durationOf(value: string): number | null {
+ const found = /^(\d{1,4})([smhd])$/.exec(value.trim().toLowerCase())
+
+ if (found === null) return null
+
+ const ms = Number(found[1]) * (UNIT[found[2] as string] as number)
+
+ return ms > 0 && ms <= 30 * 86_400_000 ? ms : null
+}
+
+/** True where a group that is itself quantified (`+`, `*`, `{`) holds a quantifier or an alternation anywhere inside it: the shape of catastrophic backtracking. */
+function unsafeGroup(source: string): boolean {
+ const stack: { risky: boolean }[] = []
+ let inClass = false
+
+ for (let i = 0; i < source.length; i++) {
+ const ch = source[i] as string
+
+ if (ch === '\\') {
+ i++
+ continue
+ }
+
+ if (inClass) {
+ if (ch === ']') inClass = false
+ continue
+ }
+
+ if (ch === '[') inClass = true
+ else if (ch === '(') stack.push({ risky: false })
+ else if (ch === '+' || ch === '*' || ch === '{' || ch === '|' || (ch === '?' && source[i - 1] !== '(')) {
+ const top = stack[stack.length - 1]
+
+ if (top !== undefined) top.risky = true
+ } else if (ch === ')') {
+ const group = stack.pop()
+
+ if (group === undefined) continue
+ if (group.risky && /[+*{]/.test(source[i + 1] ?? '')) return true
+
+ const parent = stack[stack.length - 1]
+
+ if (parent !== undefined && group.risky) parent.risky = true
+ }
+ }
+
+ return false
+}
+
+/** Why a pattern is refused, or null when it is safe to compile: short, no group quantified in a way that can blow up, no back-references. */
+export function regexProblem(source: string): string | null {
+ if (source === '') return 'an empty pattern'
+ if (source.length > REGEX_MAX) return `a pattern over ${REGEX_MAX} characters`
+ if (/\\[1-9]|\\k</.test(source)) return 'a back-reference'
+ if (unsafeGroup(source)) return 'a quantified group that holds a quantifier or an alternation'
+ if (/\(\?[<=!]/.test(source)) return 'a lookaround'
+ // `?` counts: `a?a?a?...a{n}` is exponential too (the first review missed it: 20 of them took 18 ms on a 20-character text).
+ if ((source.match(/[+*]|(?<!\()\?|\{\d*,\d*\}/g) ?? []).length > 2) return 'more than two quantifiers'
+
+ return null
+}
+
+type Raw = { text: string; quoted: boolean }
+
+/** The query cut into raw tokens: quoted phrases keep their spaces, a /regex/ keeps its slashes, a leading - is kept on the token. */
+function tokens(input: string, errors: string[]): Raw[] {
+ const out: Raw[] = []
+ let i = 0
+
+ while (i < input.length && out.length < MAX_TERMS * 2) {
+ while (input[i] === ' ') i++
+ if (i >= input.length) break
+
+ const start = i
+ const neg = input[i] === '-' && i + 1 < input.length && input[i + 1] !== ' '
+
+ if (neg) i++
+
+ if (input[i] === '"') {
+ const end = input.indexOf('"', i + 1)
+
+ if (end === -1) {
+ errors.push('a quote is not closed: the rest is taken as one phrase')
+ out.push({ text: `${neg ? '-' : ''}${input.slice(i + 1)}`, quoted: true })
+ break
+ }
+
+ out.push({ text: `${neg ? '-' : ''}${input.slice(i + 1, end)}`, quoted: true })
+ i = end + 1
+ } else if (input[i] === '/') {
+ let end = i + 1
+
+ while (end < input.length && (input[end] !== '/' || input[end - 1] === '\\')) end++
+
+ if (end >= input.length) {
+ errors.push('a /regex/ is not closed with a second slash')
+ i = input.length
+ } else {
+ let stop = end + 1
+
+ while (stop < input.length && input[stop] === 'i') stop++
+
+ out.push({ text: input.slice(start, stop), quoted: false })
+ i = stop
+ }
+ } else {
+ while (i < input.length && input[i] !== ' ') {
+ if (input[i] === '"' && input[i - 1] === ':') {
+ const end = input.indexOf('"', i + 1)
+
+ if (end !== -1) {
+ i = end + 1
+ continue
+ }
+ }
+
+ i++
+ }
+
+ out.push({ text: input.slice(start, i), quoted: false })
+ }
+ }
+
+ return out
+}
+
+export function parseQuery(input: string, nowMs = 0): Query {
+ void nowMs
+
+ const source = input.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, QUERY_MAX)
+ const errors: string[] = []
+ const terms: Term[] = []
+ let sinceMs: number | null = null
+
+ for (const raw of tokens(source, errors)) {
+ if (terms.length >= MAX_TERMS) {
+ errors.push(`only the first ${MAX_TERMS} terms are used`)
+ break
+ }
+
+ const neg = raw.text.startsWith('-') && raw.text.length > 1
+ const body = neg ? raw.text.slice(1) : raw.text
+
+ if (body === '') continue
+
+ if (!raw.quoted && body.startsWith('/')) {
+ const flags = body.endsWith('/i') ? 'i' : ''
+ const pattern = body.slice(1, body.length - 1 - flags.length)
+ const why = regexProblem(pattern)
+
+ if (why !== null) {
+ errors.push(`/${pattern.slice(0, 20)}${pattern.length > 20 ? '…' : ''}/ refused: ${why}`)
+ continue
+ }
+
+ try {
+ terms.push({ neg, type: 'regex', alts: [pattern], re: new RegExp(pattern, flags) })
+ } catch {
+ errors.push(`/${pattern.slice(0, 20)}/ is not a valid pattern`)
+ }
+
+ continue
+ }
+
+ const field = raw.quoted ? null : /^([a-z]+):(.*)$/.exec(body)
+
+ if (field !== null) {
+ const name = field[1] as string
+ const value = (field[2] as string).replace(/^"|"$/g, '')
+
+ if (name === 'since') {
+ const ms = durationOf(value)
+
+ if (ms === null) errors.push(`since: wants 90s, 15m, 1h or 2d, not "${value.slice(0, 12)}"`)
+ else sinceMs = sinceMs === null ? ms : Math.min(sinceMs, ms)
+
+ continue
+ }
+
+ if ((FIELDS as readonly string[]).includes(name)) {
+ if (value === '') {
+ errors.push(`${name}: needs a value`)
+ continue
+ }
+
+ terms.push({ neg, type: 'field', field: name as Field, alts: value.toLowerCase().split('|').filter(Boolean).slice(0, MAX_ALTS) })
+ continue
+ }
+ }
+
+ terms.push({ neg, type: 'word', alts: (raw.quoted ? [body] : body.split('|')).map(word => word.toLowerCase()).filter(Boolean).slice(0, MAX_ALTS) })
+ }
+
+ return { terms, sinceMs, errors, source }
+}
+
+
+const fieldValue = (event: ConsoleEvent, field: Field): string => {
+ switch (field) {
+ case 'kind':
+ return event.kind
+ case 'level':
+ return levelOf(event.kind, event.text)
+ case 'agent':
+ return (event.agentId ?? '').toLowerCase()
+ case 'src':
+ return (event.src ?? (event.kind === 'tools' ? 'session' : 'observed')).toLowerCase()
+ case 'ref':
+ return (refOf(event) ?? '').toLowerCase()
+ }
+}
+
+/** Whether one event satisfies one term, before negation. A field match is exact for kind, level and src; a substring for agent and ref. */
+function hit(event: ConsoleEvent, term: Term, lower: string, budget?: Budget): boolean {
+ if (term.type === 'regex') {
+ if (budget === undefined) return (term.re as RegExp).test(event.text.slice(0, REGEX_TEXT_MAX))
+ if (budget.spentMs > budget.ms) {
+ budget.skipped++
+
+ return false
+ }
+
+ const from = performance.now()
+ const found = (term.re as RegExp).test(event.text.slice(0, REGEX_TEXT_MAX))
+
+ budget.spentMs += performance.now() - from
+
+ return found
+ }
+
+ if (term.type === 'field') {
+ const value = fieldValue(event, term.field as Field)
+
+ return term.alts.some(alt => (term.field === 'agent' || term.field === 'ref' ? value.includes(alt) : value === alt))
+ }
+
+ return term.alts.some(alt => lower.includes(alt))
+}
+
+export function matches(event: ConsoleEvent, query: Query, nowMs: number, budget?: Budget): boolean {
+ if (query.sinceMs !== null && nowMs - event.atMs > query.sinceMs) return false
+ if (query.terms.length === 0) return true
+
+ const lower = `${event.text} ${event.kind}`.toLowerCase()
+
+ return query.terms.every(term => hit(event, term, lower, budget) !== term.neg)
+}
+
+/** The [start, end) ranges of `text` the positive word, phrase and regex terms hit, merged and sorted, for the row to colour. */
+export function highlights(text: string, query: Query): [number, number][] {
+ const lower = text.toLowerCase()
+ const found: [number, number][] = []
+
+ for (const term of query.terms) {
+ if (term.neg || term.type === 'field') continue
+
+ if (term.type === 'regex') {
+ const global = new RegExp((term.re as RegExp).source, `${(term.re as RegExp).flags}g`)
+ const cut = text.slice(0, REGEX_TEXT_MAX)
+
+ for (const hitAt of cut.matchAll(global)) {
+ if (hitAt[0] === '') break
+ found.push([hitAt.index as number, (hitAt.index as number) + hitAt[0].length])
+ if (found.length > 20) break
+ }
+
+ continue
+ }
+
+ for (const alt of term.alts) {
+ let at = lower.indexOf(alt)
+
+ while (at !== -1 && found.length < 40) {
+ found.push([at, at + alt.length])
+ at = lower.indexOf(alt, at + alt.length)
+ }
+ }
+ }
+
+ found.sort((a, b) => a[0] - b[0])
+
+ const merged: [number, number][] = []
+
+ for (const range of found) {
+ const last = merged[merged.length - 1]
+
+ if (last !== undefined && range[0] <= last[1]) last[1] = Math.max(last[1], range[1])
+ else merged.push([range[0], range[1]])
+ }
+
+ return merged
+}
+
+export type { Level }
diff --git a/plugins/ruflo-console/hooks/data/event-rules.ts b/plugins/ruflo-console/hooks/data/event-rules.ts
new file mode 100644
index 0000000000..148a7f46ab
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-rules.ts
@@ -0,0 +1,45 @@
+/**
+ * Alert rules for the Events page (ADR-474): a saved query that raises a band notice when a NEW event matches it. A rule is evaluated
+ * over the events that arrived since the last pass, never over history, so loading a log or changing a rule announces nothing old.
+ * Pure; the notice itself goes through notices.ts `addNotice` (one per rule per minute).
+ */
+import { levelOf, type Level } from './event-severity'
+import { budgetOf, matches, parseQuery, type Query } from './event-query'
+import type { SavedSearch } from './activity-store'
+import type { ConsoleEvent } from './events'
+
+export type Hit = { rule: string; count: number; newest: ConsoleEvent; level: Level }
+
+const parsed = new Map<string, Query>()
+
+const queryOf = (source: string): Query => {
+ let found = parsed.get(source)
+
+ if (found === undefined) {
+ found = parseQuery(source)
+ if (parsed.size > 64) parsed.clear()
+ parsed.set(source, found)
+ }
+
+ return found
+}
+
+/** Which rules the new events hit: the count and the newest event of each. A rule whose query has errors or no terms never fires. */
+export function evaluateRules(rules: readonly SavedSearch[], fresh: readonly ConsoleEvent[], nowMs: number): Hit[] {
+ const out: Hit[] = []
+ // A slow pattern cannot hold the 1.5 s pass for long: all the rules together may spend this much on regexes.
+ const budget = budgetOf(40)
+
+ for (const rule of rules) {
+ const query = queryOf(rule.q)
+
+ if (query.terms.length === 0 || query.errors.length > 0) continue
+
+ const hits = fresh.filter(event => matches(event, query, nowMs, budget))
+ const newest = hits[hits.length - 1]
+
+ if (newest !== undefined) out.push({ rule: rule.name, count: hits.length, newest, level: levelOf(newest.kind, newest.text) })
+ }
+
+ return out
+}
diff --git a/plugins/ruflo-console/hooks/data/event-severity.ts b/plugins/ruflo-console/hooks/data/event-severity.ts
new file mode 100644
index 0000000000..e47161f5a7
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-severity.ts
@@ -0,0 +1,46 @@
+/**
+ * How serious an event is (ADR-474): ok, info, warn or bad, decided in one pure place from the kind and the words. A bad word wins over a
+ * warn word, which wins over an ok word; an event with none of them is info.
+ */
+export type Level = 'ok' | 'info' | 'warn' | 'bad'
+
+export const LEVELS: readonly Level[] = ['bad', 'warn', 'ok', 'info']
+
+const BAD = /\b(?:fail(?:ed|ure|s)?|error|blocked|denied|deny|refused|critical|crash(?:ed)?|killed|timed out|stuck|stalled|unhealthy|violation)\b/i
+const WARN = /\b(?:parked|degraded|paused|stale|left the (?:store|hive)|released|warn(?:ing)?|idle for|retry|empty|mismatch|cancel(?:l?ed)?|notified|stopped|dropped|slow|unreachable|missing)\b/i
+const OK = /\b(?:done|completed?|finished|verified|succe(?:ss|eded)|joined the hive|spawned|appeared|resumed|started|approved|passed|learned|judged)\b/i
+
+/** Words that are not a problem even though they contain one (`0 failed`, `no errors`). */
+const CALM = /\b(?:0|no|zero|without)\s+(?:fail(?:ed|ures?)?|errors?|denied|blocked)\b|\b(?:fail(?:ed|ures?)?|errors?|denied|blocked)\s*[:=]\s*0\b/gi
+
+/** A tool event's words are an agent's name and a tool's name (`error-handler: Bash`), which say nothing about how it went: only a deny or an unrun confirm is a problem. */
+const TOOL_PROBLEM = /^(?:permission denied|confirm for )/i
+
+export function levelOf(kind: string, text: string): Level {
+ const words = text.replace(CALM, '')
+
+ if (kind === 'tools' && !TOOL_PROBLEM.test(text)) return 'info'
+ if (kind === 'anatole') return /\bnotified\b/i.test(words) && !BAD.test(words) ? 'warn' : 'bad'
+ if (BAD.test(words)) return 'bad'
+ if (WARN.test(words)) return 'warn'
+ if (OK.test(words)) return 'ok'
+
+ return 'info'
+}
+
+export const isLevel = (value: unknown): value is Level => value === 'ok' || value === 'info' || value === 'warn' || value === 'bad'
+export const rankOf = (level: Level): number => (level === 'bad' ? 3 : level === 'warn' ? 2 : level === 'info' ? 1 : 0)
+
+const cache = new WeakMap<object, Level>()
+
+/** `levelOf` for an event object, remembered: filtering ten thousand events decides each level once. */
+export function levelOfEvent(event: { kind: string; text: string }): Level {
+ let found = cache.get(event)
+
+ if (found === undefined) {
+ found = levelOf(event.kind, event.text)
+ cache.set(event, found)
+ }
+
+ return found
+}
diff --git a/plugins/ruflo-console/hooks/data/event-sources.ts b/plugins/ruflo-console/hooks/data/event-sources.ts
new file mode 100644
index 0000000000..0531a7c982
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-sources.ts
@@ -0,0 +1,178 @@
+/**
+ * What the Events page derives from state the console already holds (ADR-474): workflow runs, the autopilot's steps, Anatole alerts,
+ * the band's notices, permission denies and plugin or mod load changes. Each source is a pure function of the previous memo and the
+ * current facts; the first call for a source is a baseline and yields nothing (what was already there is not "an event"). The text of
+ * every event is washed by the caller before it is drawn or written.
+ */
+import type { AnatoleAlert } from './anatole'
+import type { StepRec } from './ap-loop'
+import type { ConsoleEvent, EventKind } from './events'
+import type { WfRun } from './workflows'
+import { maskLine } from './event-mask'
+
+type Make = (kind: EventKind, text: string, src: string, ref?: string) => ConsoleEvent
+
+const maker = (atMs: number): Make => (kind, text, src, ref) => ({ atMs, kind, text: maskLine(text, 200), src, ...(ref !== undefined && { ref }) })
+
+export type Memo = {
+ runs: Map<string, string> | null
+ steps: Map<string, string> | null
+ phase: string | null
+ killed: boolean | null
+ parked: Set<string> | null
+ alerts: Set<string> | null
+ noticeSeq: number | null
+ /** The denies seen last pass, as `<atMs>|<tool>|<reason>`: the console keeps only its newest 20, so a count of them cannot say what is new. */
+ denied: Set<string> | null
+ mods: Map<string, boolean> | null
+}
+
+export const newMemo = (): Memo => ({ runs: null, steps: null, phase: null, killed: null, parked: null, alerts: null, noticeSeq: null, denied: null, mods: null })
+
+/** Run started, finished, failed, stuck or empty: from the state of each run between two reads. */
+export function runEvents(memo: Memo, runs: readonly WfRun[], atMs: number): ConsoleEvent[] {
+ const make = maker(atMs)
+ const out: ConsoleEvent[] = []
+ const next = new Map(runs.filter(run => run.kind === 'workflow').map(run => [run.id, run.state === 'completed' && run.total === 0 ? 'empty' : run.state]))
+
+ if (memo.runs !== null) {
+ for (const run of runs) {
+ if (run.kind !== 'workflow') continue
+
+ const was = memo.runs.get(run.id)
+ const now = next.get(run.id) as string
+ const ref = `run:${run.id}`
+ const name = run.name === run.id ? run.id : `${run.name} (${run.id})`
+
+ if (was === now) continue
+ if (was === undefined) out.push(make('workflows', `run ${name} ${now === 'running' || now === 'active' ? 'started' : `seen ${now}`}`, 'workflows', ref))
+ else if (now === 'failed') out.push(make('workflows', `run ${name} failed (${run.failed} of ${run.total} agents)`, 'workflows', ref))
+ else if (now === 'stalled') out.push(make('workflows', `run ${name} is stuck: no progress`, 'workflows', ref))
+ else if (now === 'empty') out.push(make('workflows', `run ${name} finished empty: no agents`, 'workflows', ref))
+ else if (now === 'completed' || now === 'finished') out.push(make('workflows', `run ${name} finished: ${run.done} of ${run.total} agents done`, 'workflows', ref))
+ else out.push(make('workflows', `run ${name}: ${was} → ${now}`, 'workflows', ref))
+ }
+ }
+
+ memo.runs = next
+
+ return out
+}
+
+export type ApFacts = { phase: string; steps: readonly StepRec[]; killed: boolean; parked: readonly { id: string; question: string; answer?: string }[]; reason: string | null }
+
+/** Start, stop, a step handed over, done, failed or parked, and the kill flag. */
+export function apEvents(memo: Memo, facts: ApFacts, atMs: number): ConsoleEvent[] {
+ const make = maker(atMs)
+ const out: ConsoleEvent[] = []
+ const steps = new Map(facts.steps.map(step => [step.id, step.status]))
+ const parked = new Set(facts.parked.filter(item => item.answer === undefined).map(item => item.id))
+
+ if (memo.steps !== null && memo.parked !== null) {
+ if (memo.phase !== facts.phase) {
+ if (facts.phase === 'running' && memo.phase !== 'paused') out.push(make('autopilot', 'autopilot started', 'autopilot'))
+ else if (facts.phase === 'running') out.push(make('autopilot', 'autopilot resumed', 'autopilot'))
+ else if (facts.phase === 'paused') out.push(make('autopilot', `autopilot paused${facts.reason === null ? '' : `: ${facts.reason}`}`, 'autopilot'))
+ else if (facts.phase === 'stopped') out.push(make('autopilot', `autopilot stopped${facts.reason === null ? '' : `: ${facts.reason}`}`, 'autopilot'))
+ }
+
+ for (const step of facts.steps) {
+ const was = memo.steps.get(step.id)
+ const ref = `step:${step.id}`
+
+ if (was === step.status) continue
+ if (step.status === 'started') out.push(make('autopilot', `step ${step.id} handed over: ${step.task.slice(0, 60)}`, 'autopilot', ref))
+ else if (step.status === 'done') out.push(make('autopilot', `step ${step.id} done${step.verified === true ? ' (verified)' : ''}`, 'autopilot', ref))
+ else out.push(make('autopilot', `step ${step.id} failed${step.why === undefined ? '' : `: ${step.why.slice(0, 80)}`}`, 'autopilot', ref))
+ }
+
+ for (const item of facts.parked) {
+ if (parked.has(item.id) && !memo.parked.has(item.id)) out.push(make('autopilot', `step ${item.id} parked: ${item.question.slice(0, 80)}`, 'autopilot', `step:${item.id}`))
+ }
+
+ if (memo.killed === false && facts.killed) out.push(make('autopilot', 'kill flag set: the autopilot is blocked', 'autopilot'))
+ if (memo.killed === true && !facts.killed) out.push(make('autopilot', 'kill flag cleared', 'autopilot'))
+ }
+
+ memo.steps = steps
+ memo.parked = parked
+ memo.phase = facts.phase
+ memo.killed = facts.killed
+
+ return out
+}
+
+/** Each Anatole alert not seen before: blocked or notified, with its rule. */
+export function anatoleEvents(memo: Memo, alerts: readonly AnatoleAlert[], atMs: number): ConsoleEvent[] {
+ const ids = new Set(alerts.map(alert => alert.id))
+ const out: ConsoleEvent[] = []
+
+ if (memo.alerts !== null) {
+ for (const alert of alerts) {
+ if (memo.alerts.has(alert.id)) continue
+
+ out.push({ atMs: alert.atMs ?? atMs, kind: 'anatole', text: maskLine(`Anatole ${alert.action} ${alert.tool}: rule ${alert.rule} (${alert.severity})`, 200), src: 'anatole', ref: `rule:${maskLine(alert.rule, 40)}` })
+ }
+ }
+
+ memo.alerts = ids
+
+ return out
+}
+
+export type NoticeLike = { id: number; level: string; text: string; key: string; atMs: number }
+
+/** Each band notice raised since the last pass. A notice an alert rule raised is not turned back into an event. */
+export function noticeEvents(memo: Memo, notices: readonly NoticeLike[], seq: number): ConsoleEvent[] {
+ const out: ConsoleEvent[] = []
+
+ if (memo.noticeSeq !== null) {
+ for (const notice of notices) {
+ if (notice.id <= memo.noticeSeq || notice.key.startsWith('events-rule:')) continue
+
+ out.push({ atMs: notice.atMs, kind: 'notices', text: maskLine(`band: ${notice.text}`, 200), src: 'notices' })
+ }
+ }
+
+ memo.noticeSeq = seq
+
+ return out
+}
+
+/** Permission denies new since the last pass. */
+export function denyEvents(memo: Memo, denied: readonly { tool: string; reason: string; atMs: number }[]): ConsoleEvent[] {
+ const out: ConsoleEvent[] = []
+ const keyOf = (item: { tool: string; reason: string; atMs: number }): string => `${item.atMs}|${item.tool}|${item.reason}`
+
+ if (memo.denied !== null) {
+ for (const item of denied) {
+ if (!memo.denied.has(keyOf(item))) out.push({ atMs: item.atMs, kind: 'tools', text: maskLine(`permission denied: ${item.tool}${item.reason === '' ? '' : ` (${item.reason})`}`, 200), src: 'permissions' })
+ }
+ }
+
+ memo.denied = new Set(denied.map(keyOf))
+
+ return out
+}
+
+/** A plugin or mod that loaded or was refused since the last pass. */
+export function modEvents(memo: Memo, mods: readonly { name: string; isLoaded: boolean; reason?: string }[], atMs: number): ConsoleEvent[] {
+ const make = maker(atMs)
+ const out: ConsoleEvent[] = []
+ const next = new Map(mods.map(mod => [mod.name, mod.isLoaded]))
+
+ if (memo.mods !== null) {
+ for (const mod of mods) {
+ const was = memo.mods.get(mod.name)
+
+ if (was === mod.isLoaded) continue
+ out.push(make('mods', `mod ${mod.name} ${mod.isLoaded ? 'loaded' : `refused${mod.reason === undefined ? '' : `: ${mod.reason.slice(0, 80)}`}`}`, 'mods'))
+ }
+
+ for (const name of memo.mods.keys()) if (!next.has(name)) out.push(make('mods', `mod ${name} left the list`, 'mods'))
+ }
+
+ memo.mods = next
+
+ return out
+}
diff --git a/plugins/ruflo-console/hooks/data/event-stats.ts b/plugins/ruflo-console/hooks/data/event-stats.ts
new file mode 100644
index 0000000000..0ce7877589
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/event-stats.ts
@@ -0,0 +1,90 @@
+/**
+ * The numbers behind the Events page's charts (ADR-474): a window of time, how it is cut into bars, how many events of each kind or
+ * level fall in each bar, and a day by hour strip. Pure.
+ */
+import { levelOf, type Level } from './event-severity'
+import type { ConsoleEvent } from './events'
+
+export type WindowId = 'session' | '15m' | '1h' | '24h' | 'all'
+
+export const WINDOWS: readonly { id: WindowId; label: string; ms: number | null }[] = [
+ { id: 'session', label: 'session', ms: null },
+ { id: '15m', label: '15 min', ms: 15 * 60_000 },
+ { id: '1h', label: '1 h', ms: 3_600_000 },
+ { id: '24h', label: '24 h', ms: 86_400_000 },
+ { id: 'all', label: 'all kept', ms: null },
+]
+
+export const isWindowId = (value: unknown): value is WindowId => WINDOWS.some(entry => entry.id === value)
+
+/** The earliest time a window shows: null for all kept, the console's load time for the session. */
+export function windowStart(id: WindowId, nowMs: number, loadedAtMs: number): number | null {
+ const entry = WINDOWS.find(item => item.id === id)
+
+ if (id === 'session') return loadedAtMs
+ if (entry?.ms === null || entry === undefined) return null
+
+ return nowMs - entry.ms
+}
+
+/** Bars by minute up to an hour, by ten minutes up to a day, by hour past that. */
+export function bucketMs(spanMs: number): number {
+ return spanMs <= 3_600_000 ? 60_000 : spanMs <= 86_400_000 ? 600_000 : 3_600_000
+}
+
+export type Bars = { fromMs: number; stepMs: number; stacks: number[][] }
+
+/** `n` bars ending at `nowMs`, each a stack by `keys` (kinds or levels). Events outside the span are not counted. */
+export function bars(events: readonly ConsoleEvent[], keys: readonly string[], keyOf: (event: ConsoleEvent) => string, spanMs: number, nowMs: number, maxBars = 48): Bars {
+ const step = Math.max(bucketMs(spanMs), Math.ceil(spanMs / maxBars / 60_000) * 60_000)
+ const count = Math.max(1, Math.min(maxBars, Math.ceil(spanMs / step)))
+ const fromMs = nowMs - count * step
+ const stacks = Array.from({ length: count }, () => new Array<number>(keys.length).fill(0))
+
+ for (const event of events) {
+ const at = Math.floor((event.atMs - fromMs) / step)
+ const k = keys.indexOf(keyOf(event))
+
+ if (at >= 0 && at < count && k >= 0) (stacks[at] as number[])[k] = ((stacks[at] as number[])[k] ?? 0) + 1
+ }
+
+ return { fromMs, stepMs: step, stacks }
+}
+
+export const levelKey = (event: ConsoleEvent): Level => levelOf(event.kind, event.text)
+
+const BLOCKS = '▁▂▃▄▅▆▇█'
+
+/** One text line of a stack: the height of each bar, scaled to the tallest. Empty bars are a dot. */
+export function barsLine(data: Bars): string {
+ const totals = data.stacks.map(stack => stack.reduce((a, b) => a + b, 0))
+ const top = Math.max(1, ...totals)
+
+ return totals.map(total => (total === 0 ? '·' : (BLOCKS[Math.min(BLOCKS.length - 1, Math.ceil((total / top) * BLOCKS.length) - 1)] as string))).join('')
+}
+
+/** 7 days by 24 hours of counts (local time), newest day last, for a window past a day. Rows are days, columns hours. */
+export function dayHour(events: readonly ConsoleEvent[], nowMs: number, days = 7): number[][] {
+ const grid = Array.from({ length: days }, () => new Array<number>(24).fill(0))
+ const today = new Date(nowMs)
+
+ today.setHours(0, 0, 0, 0)
+
+ for (const event of events) {
+ const at = new Date(event.atMs)
+ const back = Math.round((today.getTime() - new Date(at.getFullYear(), at.getMonth(), at.getDate()).getTime()) / 86_400_000)
+
+ if (back >= 0 && back < days) (grid[days - 1 - back] as number[])[at.getHours()]!++
+ }
+
+ return grid
+}
+
+export const heatLine = (counts: readonly number[]): string => {
+ const top = Math.max(1, ...counts)
+
+ return counts.map(n => (n === 0 ? '·' : (BLOCKS[Math.min(BLOCKS.length - 1, Math.ceil((n / top) * BLOCKS.length) - 1)] as string))).join('')
+}
+
+/** The window one bar names: the narrowed span when a bar is pressed. */
+export const narrow = (fromMs: number, stepMs: number, index: number): { fromMs: number; toMs: number } => ({ fromMs: fromMs + index * stepMs, toMs: fromMs + (index + 1) * stepMs })
diff --git a/plugins/ruflo-console/hooks/data/events.ts b/plugins/ruflo-console/hooks/data/events.ts
index 70e1de336f..f7e4b26055 100644
--- a/plugins/ruflo-console/hooks/data/events.ts
+++ b/plugins/ruflo-console/hooks/data/events.ts
@@ -5,7 +5,7 @@
*/
import type { Snapshot } from './snapshot'
-export type EventKind = 'swarm' | 'claims' | 'federation' | 'learning' | 'tools' | 'mods' | 'missions'
+export type EventKind = 'swarm' | 'claims' | 'federation' | 'learning' | 'tools' | 'mods' | 'missions' | 'workflows' | 'autopilot' | 'anatole' | 'notices' | 'other'
export type ConsoleEvent = {
atMs: number
@@ -13,9 +13,29 @@ export type ConsoleEvent = {
text: string
/** The ruflo agent the event concerns, when one does: the topology pulses along that agent's edge. */
agentId?: string
+ /** What the event is about, as `agent:<id>`, `claim:<id>`, `run:<id>`, `task:<id>`, `mission:<id>` or `step:<id>`; derived by `refOf` when absent. */
+ ref?: string
+ /** Which part of the console saw it, when not the diff of two reads: `autopilot`, `workflows`, `anatole`, `notices`, `session`. */
+ src?: string
}
-export const EVENT_KINDS: readonly EventKind[] = ['swarm', 'claims', 'federation', 'learning', 'tools', 'mods', 'missions']
+export const EVENT_KINDS: readonly EventKind[] = ['swarm', 'claims', 'federation', 'learning', 'tools', 'mods', 'missions', 'workflows', 'autopilot', 'anatole', 'notices', 'other']
+
+export const isEventKind = (value: unknown): value is EventKind => typeof value === 'string' && (EVENT_KINDS as readonly string[]).includes(value)
+
+/** What an event is about: its own `ref`, else the agent it names, else the first issue or mission id in the words of a claims or missions event. */
+export function refOf(event: ConsoleEvent): string | undefined {
+ if (event.ref !== undefined) return event.ref
+ if (event.agentId !== undefined) return `agent:${event.agentId}`
+
+ const word = /^(?:task |mission |proposal )?([A-Za-z0-9][\w.:-]{2,60})/.exec(event.text)?.[1]
+
+ if (word === undefined) return undefined
+ if (event.kind === 'claims') return `${event.text.startsWith('task ') ? 'task' : 'claim'}:${word}`
+ if (event.kind === 'missions') return `mission:${word}`
+
+ return undefined
+}
export const MAX_EVENTS = 300
const ev = (atMs: number, kind: EventKind, text: string, agentId?: string): ConsoleEvent => ({ atMs, kind, text, ...(agentId !== undefined && { agentId }) })
diff --git a/plugins/ruflo-console/hooks/data/timeline-lines.ts b/plugins/ruflo-console/hooks/data/timeline-lines.ts
new file mode 100644
index 0000000000..c5979ac97a
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/timeline-lines.ts
@@ -0,0 +1,91 @@
+/**
+ * The Timeline page as lines of coloured cells (ADR-474): one axis line, one line for the events, a header per lane group, a line per
+ * lane and a parallelism strip. The same lines are drawn as a picture where the terminal has a Raster, and as text where it has not:
+ * the two carry exactly the same information because they are built from this one list. Pure.
+ */
+import type { LaneStore, LaneView, Span } from './timeline-model'
+import { axisLine, cellsOf, markerIndex } from './timeline-model'
+import type { Concurrency } from './timeline-model'
+import type { ConsoleEvent } from './events'
+
+export type Tone = 'busy' | 'idle' | 'tool' | 'none' | 'warn' | 'bad' | 'dim' | 'plain'
+export type Cell = { ch: string; tone: Tone }
+export type Line = { kind: 'axis' | 'events' | 'group' | 'lane' | 'conc'; label: string; cells: Cell[]; laneId?: string; isCursor?: boolean }
+
+const BLOCKS = '▁▂▃▄▅▆▇█'
+const CELL: Cell[] = [
+ { ch: '·', tone: 'none' },
+ { ch: '▁', tone: 'idle' },
+ { ch: '█', tone: 'busy' },
+ { ch: '▮', tone: 'tool' },
+]
+
+export const labelWidthOf = (columns: number): number => Math.max(8, Math.min(16, Math.floor(columns / 5)))
+const fit = (label: string, width: number): string => (label.length > width ? `${label.slice(0, width - 1)}…` : label.padEnd(width))
+
+/** The group header for a window page: `▾ ruflo (3)`. */
+export const groupLabel = (group: string, count: number, isOpen: boolean): string => `${isOpen ? '▾' : '▸'} ${group} (${count})`
+
+export type PageEntry = { type: 'group'; group: string; count: number; isOpen: boolean } | { type: 'lane'; lane: LaneView }
+
+export function buildLines(entries: readonly PageEntry[], store: LaneStore, events: readonly ConsoleEvent[], allLanes: readonly LaneView[], win: Span, conc: Concurrency, columns: number, cursorLane: string | null): Line[] {
+ const labelW = labelWidthOf(columns)
+ const cellsN = Math.max(8, columns - labelW - 1)
+ const lines: Line[] = [{ kind: 'axis', label: fit('', labelW), cells: [...axisLine(win, cellsN)].map(ch => ({ ch, tone: 'dim' as const })) }]
+ const index = markerIndex(events, allLanes, win, cellsN)
+ const top = index.get('') ?? new Array(cellsN).fill(null)
+
+ lines.push({ kind: 'events', label: fit('events', labelW), cells: top.map(level => (level === 'bad' ? { ch: '▲', tone: 'bad' as const } : level === 'warn' ? { ch: '△', tone: 'warn' as const } : { ch: '·', tone: 'none' as const })) })
+
+ for (const entry of entries) {
+ if (entry.type === 'group') {
+ lines.push({ kind: 'group', label: fit(groupLabel(entry.group, entry.count, entry.isOpen), labelW + 8).trimEnd(), cells: [] })
+ continue
+ }
+
+ const grid = cellsOf(entry.lane, win, cellsN, store)
+ const marks = index.get(entry.lane.lane) ?? []
+
+ lines.push({
+ kind: 'lane',
+ label: fit(entry.lane.label, labelW),
+ laneId: entry.lane.lane,
+ isCursor: entry.lane.lane === cursorLane,
+ cells: Array.from({ length: cellsN }, (_, i) => {
+ const mark = marks[i]
+
+ if (mark === 'bad') return { ch: '▲', tone: 'bad' as const }
+ if (mark === 'warn') return { ch: '△', tone: 'warn' as const }
+
+ return CELL[grid[i] as number] as Cell
+ }),
+ })
+ }
+
+ const top2 = Math.max(1, conc.peak)
+
+ lines.push({ kind: 'conc', label: fit('parallel', labelW), cells: Array.from({ length: cellsN }, (_, i) => {
+ const n = conc.counts[Math.min(conc.counts.length - 1, Math.floor((i / cellsN) * conc.counts.length))] ?? 0
+
+ return n === 0 ? { ch: '·', tone: 'none' as const } : { ch: BLOCKS[Math.min(BLOCKS.length - 1, Math.ceil((n / top2) * BLOCKS.length) - 1)] as string, tone: 'busy' as const }
+ }) })
+
+ return lines
+}
+
+/** Runs of cells of one tone, for a row of Text elements. */
+export function runsOf(cells: readonly Cell[]): { text: string; tone: Tone }[] {
+ const out: { text: string; tone: Tone }[] = []
+
+ for (const cell of cells) {
+ const last = out[out.length - 1]
+
+ if (last !== undefined && last.tone === cell.tone) last.text += cell.ch
+ else out.push({ text: cell.ch, tone: cell.tone })
+ }
+
+ return out
+}
+
+/** The legend, one line: what each cell means. */
+export const LEGEND = '█ busy · ▁ idle · ▮ tool call · △ warn ▲ bad event · · not observed'
diff --git a/plugins/ruflo-console/hooks/data/timeline-model.ts b/plugins/ruflo-console/hooks/data/timeline-model.ts
new file mode 100644
index 0000000000..61f353374f
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/timeline-model.ts
@@ -0,0 +1,459 @@
+/**
+ * The Timeline's data (ADR-474): lanes in groups, their busy and idle spans and tool calls per minute, held in one bounded store that
+ * the persisted `lanes.jsonl` fills at start and the live reads extend. Windows, buckets, the concurrency strip, idle gaps and the
+ * busiest minute are pure functions of that store. Nothing is invented: a lane has the spans something observed.
+ */
+import { MAX_LANE_ROWS, type LaneGroup, type LaneRow, type LaneSpan, type LaneTick } from './activity-store'
+import type { ConsoleEvent } from './events'
+import { refOf } from './events'
+import { levelOfEvent, rankOf, type Level } from './event-severity'
+
+export type LaneStore = {
+ spans: LaneSpan[]
+ ticks: Map<string, LaneTick>
+ open: Map<string, { group: LaneGroup; label: string; fromMs: number; busy: boolean }>
+ known: Set<string>
+ persistedTicks: Set<string>
+ cursors: Map<string, number>
+ /** Bumps on every change: a memo key. */
+ version: number
+}
+
+export const newLaneStore = (): LaneStore => ({ spans: [], ticks: new Map(), open: new Map(), known: new Set(), persistedTicks: new Set(), cursors: new Map(), version: 0 })
+
+const minuteOf = (ms: number): number => Math.floor(ms / 60_000)
+const tickKey = (lane: string, min: number): string => `${lane}|${min}`
+
+function pushSpan(store: LaneStore, span: LaneSpan): void {
+ store.spans.push(span)
+ if (store.spans.length > MAX_LANE_ROWS) store.spans.splice(0, store.spans.length - MAX_LANE_ROWS)
+ store.known.add(`${span.lane}|${span.fromMs}`)
+}
+
+/** Fills the store from what was persisted (spans, ticks); a tick read back is already persisted. */
+export function loadRows(store: LaneStore, rows: readonly LaneRow[]): void {
+ for (const row of rows) {
+ if (row.k === 'span') {
+ if (!store.known.has(`${row.lane}|${row.fromMs}`)) pushSpan(store, row)
+ } else {
+ const key = tickKey(row.lane, row.min)
+
+ store.ticks.set(key, row)
+ store.persistedTicks.add(key)
+ }
+ }
+
+ store.spans.sort((a, b) => a.fromMs - b.fromMs)
+ store.version++
+}
+
+export type Sample = { lane: string; group: LaneGroup; label: string; busy: boolean }
+
+/** A status read: each sampled lane is busy or idle now. A lane of `group` that is not in the sample has gone, and its open span closes. Returns the spans that closed. */
+export function observe(store: LaneStore, group: LaneGroup, samples: readonly Sample[], nowMs: number): LaneRow[] {
+ const out: LaneRow[] = []
+ const seen = new Set<string>()
+
+ for (const sample of samples) {
+ seen.add(sample.lane)
+
+ const held = store.open.get(sample.lane)
+
+ if (held !== undefined && held.busy === sample.busy) continue
+
+ if (held !== undefined && nowMs > held.fromMs) {
+ const span = { lane: sample.lane, group, label: held.label, fromMs: held.fromMs, toMs: nowMs, busy: held.busy }
+
+ pushSpan(store, span)
+ out.push({ k: 'span', ...span })
+ }
+
+ store.open.set(sample.lane, { group, label: sample.label, fromMs: nowMs, busy: sample.busy })
+ store.version++
+ }
+
+ for (const [lane, held] of [...store.open]) {
+ if (held.group !== group || seen.has(lane)) continue
+
+ if (nowMs > held.fromMs) {
+ const span = { lane, group, label: held.label, fromMs: held.fromMs, toMs: nowMs, busy: held.busy }
+
+ pushSpan(store, span)
+ out.push({ k: 'span', ...span })
+ }
+
+ store.open.delete(lane)
+ store.version++
+ }
+
+ return out
+}
+
+/** An interval something else timed (a workflow agent, an autopilot step, a mission task). Running (`toMs` null) is held open; finished is stored once, whatever number of reads show it. */
+export function setInterval(store: LaneStore, lane: string, group: LaneGroup, label: string, fromMs: number, toMs: number | null, busy = true): LaneRow | null {
+ if (!Number.isFinite(fromMs) || fromMs <= 0) return null
+
+ if (toMs === null) {
+ if (!store.open.has(lane) && !store.known.has(`${lane}|${fromMs}`)) {
+ store.open.set(lane, { group, label, fromMs, busy })
+ store.version++
+ }
+
+ return null
+ }
+
+ store.open.delete(lane)
+
+ if (store.known.has(`${lane}|${fromMs}`) || toMs < fromMs) return null
+
+ const span = { lane, group, label, fromMs, toMs, busy }
+
+ pushSpan(store, span)
+ store.version++
+
+ return { k: 'span', ...span }
+}
+
+/** Tool calls newer than this lane's cursor, counted into minutes by tool. Returns the minutes that are complete and not yet persisted. */
+export function addTools(store: LaneStore, lane: string, group: LaneGroup, label: string, calls: readonly { atMs: number; tool: string }[], nowMs: number): LaneRow[] {
+ const cursor = store.cursors.get(lane) ?? 0
+ let newest = cursor
+
+ for (const call of calls) {
+ if (call.atMs <= cursor) continue
+
+ const key = tickKey(lane, minuteOf(call.atMs))
+ // A tool named `constructor` or `__proto__` must count like any other: a null-prototype table has no inherited names.
+ const tick = store.ticks.get(key) ?? { lane, group, label, min: minuteOf(call.atMs), n: 0, tools: Object.create(null) as Record<string, number> }
+ const tool = call.tool.slice(0, 40)
+
+ tick.n++
+ tick.tools[tool] = (tick.tools[tool] ?? 0) + 1
+ store.ticks.set(key, tick)
+ newest = Math.max(newest, call.atMs)
+ }
+
+ if (newest > cursor) {
+ store.cursors.set(lane, newest)
+ store.version++
+ }
+
+ return completeTicks(store, nowMs)
+}
+
+/** The ticks of finished minutes that were not persisted yet (marked now). */
+export function completeTicks(store: LaneStore, nowMs: number): LaneRow[] {
+ const out: LaneRow[] = []
+
+ for (const [key, tick] of store.ticks) {
+ if (tick.min < minuteOf(nowMs) && !store.persistedTicks.has(key)) {
+ store.persistedTicks.add(key)
+ out.push({ k: 'tick', ...tick })
+ }
+ }
+
+ return out
+}
+
+/** Drops ticks older than a day from memory (the file keeps its own rotation). */
+export function trim(store: LaneStore, nowMs: number, keepMs = 7 * 86_400_000): void {
+ for (const [key, tick] of store.ticks) if (tick.min * 60_000 < nowMs - keepMs) store.ticks.delete(key)
+}
+
+// ---------------------------------------------------------------------------------------------------------------- windows
+
+export type TlWindowId = '5m' | '15m' | '1h' | '6h' | '24h' | 'session'
+
+export const TL_WINDOWS: readonly { id: TlWindowId; label: string; ms: number | null }[] = [
+ { id: '5m', label: '5 min', ms: 5 * 60_000 },
+ { id: '15m', label: '15 min', ms: 15 * 60_000 },
+ { id: '1h', label: '1 h', ms: 3_600_000 },
+ { id: '6h', label: '6 h', ms: 6 * 3_600_000 },
+ { id: '24h', label: '24 h', ms: 86_400_000 },
+ { id: 'session', label: 'session', ms: null },
+]
+
+export const isTlWindow = (value: unknown): value is TlWindowId => TL_WINDOWS.some(entry => entry.id === value)
+
+export type Span = { fromMs: number; toMs: number }
+
+/** The span of time shown: `spanMs` long, ending `offsetMs` before now (0 is the live edge). A session is as long as the console has been up (at least a minute). */
+export function windowOf(id: TlWindowId, offsetMs: number, nowMs: number, loadedAtMs: number): Span & { spanMs: number } {
+ const entry = TL_WINDOWS.find(item => item.id === id)
+ const spanMs = entry?.ms ?? Math.max(60_000, nowMs - loadedAtMs)
+ const toMs = nowMs - Math.max(0, offsetMs)
+
+ return { fromMs: toMs - spanMs, toMs, spanMs }
+}
+
+/** The next wider or narrower window, or the same one at the end of the list. */
+export function zoomed(id: TlWindowId, by: 1 | -1): TlWindowId {
+ const order = TL_WINDOWS.filter(entry => entry.ms !== null).map(entry => entry.id)
+ const at = order.indexOf(id)
+
+ return order[Math.max(0, Math.min(order.length - 1, (at === -1 ? 1 : at) + by))] ?? id
+}
+
+// ---------------------------------------------------------------------------------------------------------------- lanes
+
+export type LaneView = {
+ lane: string
+ group: LaneGroup
+ label: string
+ spans: LaneSpan[]
+ calls: number
+ byTool: [string, number][]
+ busyMs: number
+ observedMs: number
+ /** Busy share of the time the lane was observed in the window, or null where it was not observed. */
+ busyPct: number | null
+ longestMs: number
+ lastAtMs: number
+ /** The minutes (since the epoch) in which the lane called a tool, for drawing without scanning every minute of the window. */
+ tickMins: number[]
+}
+
+const clip = (a: number, b: number, win: Span): number => Math.max(0, Math.min(b, win.toMs) - Math.max(a, win.fromMs))
+
+/** Every lane that has a span or a tool call in the window. Open spans run to now. One pass over the store. */
+export function lanesIn(store: LaneStore, win: Span, nowMs: number): LaneView[] {
+ const views = new Map<string, LaneView & { tools: Map<string, number> }>()
+ const view = (lane: string, group: LaneGroup, label: string) => {
+ let held = views.get(lane)
+
+ if (held === undefined) {
+ held = { lane, group, label, spans: [], calls: 0, byTool: [], busyMs: 0, observedMs: 0, busyPct: null, longestMs: 0, lastAtMs: 0, tickMins: [], tools: new Map() }
+ views.set(lane, held)
+ }
+
+ return held
+ }
+ const addSpan = (span: LaneSpan) => {
+ const used = clip(span.fromMs, span.toMs, win)
+
+ if (used <= 0) return
+
+ const held = view(span.lane, span.group, span.label)
+
+ held.spans.push(span)
+ held.observedMs += used
+ held.lastAtMs = Math.max(held.lastAtMs, Math.min(span.toMs, win.toMs))
+ if (span.busy) {
+ held.busyMs += used
+ held.longestMs = Math.max(held.longestMs, used)
+ }
+ }
+
+ for (const span of store.spans) if (span.toMs > win.fromMs && span.fromMs < win.toMs) addSpan(span)
+ for (const [lane, held] of store.open) addSpan({ lane, group: held.group, label: held.label, fromMs: held.fromMs, toMs: nowMs, busy: held.busy })
+
+ for (const tick of store.ticks.values()) {
+ const at = tick.min * 60_000
+
+ if (at + 60_000 <= win.fromMs || at >= win.toMs) continue
+
+ const held = view(tick.lane, tick.group, tick.label)
+
+ held.calls += tick.n
+ held.tickMins.push(tick.min)
+ held.lastAtMs = Math.max(held.lastAtMs, at)
+ for (const [tool, n] of Object.entries(tick.tools)) held.tools.set(tool, (held.tools.get(tool) ?? 0) + n)
+ }
+
+ return [...views.values()].map(({ tools, ...rest }) => ({ ...rest, byTool: [...tools].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 12), busyPct: rest.observedMs > 0 && rest.spans.length > 0 ? Math.round((rest.busyMs / rest.observedMs) * 100) : null }))
+}
+
+export type SortId = 'busy' | 'calls' | 'name' | 'recent'
+export const SORTS: readonly SortId[] = ['busy', 'calls', 'name', 'recent']
+
+export function sortLanes(lanes: readonly LaneView[], sort: SortId): LaneView[] {
+ const by: Record<SortId, (a: LaneView, b: LaneView) => number> = {
+ busy: (a, b) => (b.busyPct ?? -1) - (a.busyPct ?? -1) || b.calls - a.calls,
+ calls: (a, b) => b.calls - a.calls || (b.busyPct ?? -1) - (a.busyPct ?? -1),
+ name: (a, b) => (a.label < b.label ? -1 : a.label > b.label ? 1 : 0),
+ recent: (a, b) => b.lastAtMs - a.lastAtMs,
+ }
+
+ return [...lanes].sort((a, b) => by[sort](a, b) || (a.lane < b.lane ? -1 : 1))
+}
+
+/** Which of `n` cells of the window a lane was busy (2), idle (1), called a tool in (3), or unobserved (0). */
+export function cellsOf(lane: LaneView, win: Span, cellsN: number, _store?: LaneStore): Uint8Array {
+ const out = new Uint8Array(cellsN)
+ const step = (win.toMs - win.fromMs) / cellsN
+
+ for (const span of lane.spans) {
+ const a = Math.max(0, Math.floor((Math.max(span.fromMs, win.fromMs) - win.fromMs) / step))
+ const b = Math.min(cellsN - 1, Math.floor((Math.min(span.toMs, win.toMs) - win.fromMs - 1) / step))
+
+ for (let i = a; i <= b; i++) out[i] = Math.max(out[i] as number, span.busy ? 2 : 1)
+ }
+
+ for (const m of lane.tickMins) {
+ const i = Math.floor((m * 60_000 + 30_000 - win.fromMs) / step)
+
+ if (i >= 0 && i < cellsN) out[i] = 3
+ }
+
+ return out
+}
+
+export type Concurrency = { counts: number[]; stepMs: number; peak: number; mean: number; peakAtMs: number | null }
+
+/** How many lanes were busy in each bar (a busy span, or a tool call, in it): a parallelism strip with its peak and mean over the bars with anyone busy. */
+export function concurrency(lanes: readonly LaneView[], win: Span, store: LaneStore, bars: number): Concurrency {
+ const stepMs = (win.toMs - win.fromMs) / bars
+ const counts = new Array<number>(bars).fill(0)
+
+ for (const lane of lanes) {
+ const cells = cellsOf(lane, win, bars, store)
+
+ for (let i = 0; i < bars; i++) if ((cells[i] as number) >= 2) counts[i]!++
+ }
+
+ const peak = Math.max(0, ...counts)
+ const active = counts.filter(n => n > 0)
+
+ return { counts, stepMs, peak, mean: active.length === 0 ? 0 : Math.round((active.reduce((a, b) => a + b, 0) / active.length) * 10) / 10, peakAtMs: peak === 0 ? null : win.fromMs + counts.indexOf(peak) * stepMs }
+}
+
+export type IdleGap = { lane: string; label: string; fromMs: number; toMs: number }
+
+/** A lane idle for `minMs` or more while another lane was busy: the stretches, longest first (at most `max`). */
+export function idleGaps(lanes: readonly LaneView[], win: Span, store: LaneStore, minMs = 5 * 60_000, max = 8): IdleGap[] {
+ const bars = Math.max(1, Math.min(240, Math.round((win.toMs - win.fromMs) / 60_000)))
+ const step = (win.toMs - win.fromMs) / bars
+ const grids = lanes.map(lane => cellsOf(lane, win, bars, store))
+ const busyAt = (i: number, skip: number): boolean => grids.some((g, k) => k !== skip && (g[i] as number) >= 2)
+ const out: IdleGap[] = []
+
+ grids.forEach((grid, k) => {
+ let from = -1
+
+ const close = (to: number) => {
+ if (from >= 0 && (to - from) * step >= minMs) out.push({ lane: (lanes[k] as LaneView).lane, label: (lanes[k] as LaneView).label, fromMs: win.fromMs + from * step, toMs: win.fromMs + to * step })
+
+ from = -1
+ }
+
+ for (let i = 0; i < bars; i++) {
+ const idle = (grid[i] as number) === 1 && busyAt(i, k)
+
+ if (idle && from < 0) from = i
+ else if (!idle) close(i)
+ }
+
+ close(bars)
+ })
+
+ return out.sort((a, b) => b.toMs - b.fromMs - (a.toMs - a.fromMs)).slice(0, max)
+}
+
+/** The minute with the most tool calls across all lanes in the window, or null. */
+export function busiestMinute(store: LaneStore, win: Span): { atMs: number; n: number } | null {
+ const per = new Map<number, number>()
+
+ for (const tick of store.ticks.values()) if (tick.min * 60_000 >= win.fromMs - 60_000 && tick.min * 60_000 < win.toMs) per.set(tick.min, (per.get(tick.min) ?? 0) + tick.n)
+
+ let best: { atMs: number; n: number } | null = null
+
+ for (const [min, n] of per) if (best === null || n > best.n || (n === best.n && min * 60_000 > best.atMs)) best = { atMs: min * 60_000, n }
+
+ return best
+}
+
+// ---------------------------------------------------------------------------------------------------------------- events on lanes
+
+/** Lookup tables from a ref to a lane, built once per list of lanes: `agent:<id>` is `ruflo:<id>`, `run:<id>` is any workflow lane of that run. */
+function laneIndex(lanes: readonly LaneView[]): { exact: Map<string, string>; runs: Map<string, string> } {
+ const exact = new Map<string, string>()
+ const runs = new Map<string, string>()
+
+ for (const lane of lanes) {
+ exact.set(lane.lane, lane.lane)
+
+ if (lane.lane.startsWith('workflow:')) {
+ const run = lane.lane.slice(9).split('/')[0] as string
+
+ if (!runs.has(run)) runs.set(run, lane.lane)
+ }
+ }
+
+ return { exact, runs }
+}
+
+const laneFor = (ref: string | undefined, index: ReturnType<typeof laneIndex>): string | null => {
+ if (ref === undefined) return null
+
+ const at = ref.indexOf(':')
+ const kind = ref.slice(0, at)
+ const id = ref.slice(at + 1)
+
+ return index.exact.get(`${kind === 'agent' ? 'ruflo' : kind}:${id}`) ?? index.exact.get(ref) ?? (kind === 'run' ? (index.runs.get(id) ?? null) : null)
+}
+
+/** The worst warn or bad level in each of `bars` cells of the window, for every lane that has one ('' is the top events lane): one pass over the events. */
+export function markerIndex(events: readonly ConsoleEvent[], lanes: readonly LaneView[], win: Span, bars: number): Map<string, (Level | null)[]> {
+ const out = new Map<string, (Level | null)[]>()
+ const index = laneIndex(lanes)
+ const step = (win.toMs - win.fromMs) / bars
+
+ for (const event of events) {
+ if (event.atMs < win.fromMs || event.atMs >= win.toMs) continue
+
+ const level = levelOfEvent(event)
+
+ if (rankOf(level) < 2) continue
+
+ const key = laneFor(refOf(event), index) ?? ''
+ let cells = out.get(key)
+
+ if (cells === undefined) {
+ cells = new Array<Level | null>(bars).fill(null)
+ out.set(key, cells)
+ }
+
+ const i = Math.min(bars - 1, Math.floor((event.atMs - win.fromMs) / step))
+
+ if (cells[i] === null || rankOf(level) > rankOf(cells[i] as Level)) cells[i] = level
+ }
+
+ return out
+}
+
+/** The newest warn or bad event strictly before `beforeMs`, or null: where "jump to the last problem" goes. */
+export function lastProblem(events: readonly ConsoleEvent[], beforeMs: number): ConsoleEvent | null {
+ for (let i = events.length - 1; i >= 0; i--) {
+ const event = events[i] as ConsoleEvent
+
+ if (event.atMs < beforeMs && rankOf(levelOfEvent(event)) >= 2) return event
+ }
+
+ return null
+}
+
+const pad2 = (n: number): string => String(n).padStart(2, '0')
+
+/** Local `HH:MM` (or `D HH:MM` past a day) of a time. */
+export function clockOf(ms: number, withDay = false): string {
+ const at = new Date(ms)
+
+ return `${withDay ? `${pad2(at.getMonth() + 1)}-${pad2(at.getDate())} ` : ''}${pad2(at.getHours())}:${pad2(at.getMinutes())}`
+}
+
+/** The axis: local time labels at even spacing across `cellsN` cells, never overlapping. */
+export function axisLine(win: Span, cellsN: number): string {
+ const long = win.toMs - win.fromMs > 86_400_000
+ const label = long ? 11 : 5
+ const marks = Math.max(1, Math.floor(cellsN / (label + 2)))
+ const chars = new Array<string>(cellsN).fill(' ')
+
+ for (let k = 0; k < marks; k++) {
+ const at = marks === 1 ? 0 : Math.round((k / (marks - 1)) * (cellsN - label))
+ const text = clockOf(win.fromMs + ((win.toMs - win.fromMs) * (at + label / 2)) / cellsN, long)
+
+ for (let i = 0; i < text.length && at + i < cellsN; i++) chars[at + i] = text[i] as string
+ }
+
+ return chars.join('')
+}
diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.ts
index 552aacfb3f..9daa845cda 100644
--- a/plugins/ruflo-console/hooks/dispatch.ts
+++ b/plugins/ruflo-console/hooks/dispatch.ts
@@ -18,6 +18,7 @@ import { barText } from './views/bar'
import { viewText } from './views/pane'
import { autopilotCommand } from './views/ap-panel'
import { hostOf } from './ap-live'
+import { watchCommand } from './watch-command'
import { bandReply, noticesReply, quietReply, median, p95 } from './notices'
/** The engine's words when a registered command reaches it with no hook answering (Claude Code 2.1.287). */
@@ -194,6 +195,9 @@ export async function dispatch(control: Controller, state: State, args: string,
}
case 'commands':
return { text: commandsText(await loadCatalog(control), intent.query) }
+ case 'events':
+ case 'timeline':
+ return watchCommand(control, state, intent)
case 'unknown':
return { text: `Unknown: "${plain(intent.word, 30)}". /ruflo help lists the views (${VIEWS.map(view => view.id).join(', ')}) and commands.` }
}
diff --git a/plugins/ruflo-console/hooks/events-args.ts b/plugins/ruflo-console/hooks/events-args.ts
new file mode 100644
index 0000000000..8bab10f72f
--- /dev/null
+++ b/plugins/ruflo-console/hooks/events-args.ts
@@ -0,0 +1,131 @@
+/**
+ * `/ruflo events <args>` (ADR-474): sets the Events page's filters and returns what to say. The export and forget verbs are for the
+ * caller (they need the host and the confirm card).
+ */
+import { eventsActions, eventsModel, eventsUi } from './events-ui'
+import { formatOf } from './data/event-export'
+import { maskLine } from './data/event-mask'
+import { EMPTY_QUERY, parseQuery } from './data/event-query'
+import { isLevel } from './data/event-severity'
+import { isWindowId } from './data/event-stats'
+import { EVENT_KINDS } from './data/events'
+import type { Host } from './host'
+import type { State } from './state'
+
+export function applyEventsArgs(state: State, args: readonly string[]): { text: string; export?: { format: 'md' | 'jsonl'; path: string }; forget?: boolean } {
+ const ui = eventsUi(state)
+ const [first = '', ...rest] = args
+ const word = first.toLowerCase()
+ const sync = (): void => {
+ ui.page = 0
+ ui.focus = 0
+ }
+
+ if (word === '') return { text: summary(state) }
+
+ if (word === 'clear') {
+ ui.query = ''
+ ui.parsed = EMPTY_QUERY
+ ui.level = 'all'
+ ui.followRef = null
+ ui.narrowed = null
+ state.eventFilter = 'all'
+ sync()
+
+ return { text: 'events: filters cleared' }
+ }
+
+ if (word === 'forget') return { text: 'asking before the history files are removed', forget: true }
+
+ if (word === 'export') {
+ const path = rest.join(' ').trim()
+
+ return { text: 'checking the path', export: { format: formatOf(path) === 'jsonl' ? 'jsonl' : 'md', path } }
+ }
+
+ if (word === 'follow') {
+ const ref = rest.join(' ').trim()
+
+ ui.followRef = ref === '' ? null : maskLine(ref, 80)
+ sync()
+
+ return { text: ref === '' ? 'events: follow off' : `events: following ${ui.followRef} and what happened within 30 s of it` }
+ }
+
+ if (word === 'window') {
+ const id = rest[0] ?? ''
+
+ if (!isWindowId(id)) return { text: 'window takes session, 15m, 1h, 24h or all' }
+ ui.window = id
+ ui.narrowed = null
+ sync()
+
+ return { text: `events: window ${id}` }
+ }
+
+ if (word === 'pin') {
+ const event = eventsModel(state, Date.now()).rows[ui.focus]?.event
+
+ if (event === undefined) return { text: 'nothing focused to pin' }
+ eventsActions(state, { fillPrompt: async () => false } as unknown as Host, () => undefined, () => undefined, () => undefined).pin(event)
+
+ return { text: ui.said ?? 'pinned' }
+ }
+
+ if (word === 'rule') {
+ eventsActions(state, {} as Host, () => undefined, () => undefined, () => undefined).addRule()
+
+ return { text: ui.said ?? '' }
+ }
+
+ // `level bad` and `kind swarm` as the help names them, besides the bare `bad` and `swarm`.
+ if ((word === 'level' || word === 'kind') && rest.length === 1) {
+ const value = (rest[0] ?? '').toLowerCase()
+
+ if (word === 'level' && (value === 'all' || isLevel(value))) {
+ ui.level = value
+ sync()
+
+ return { text: `events: level ${value}` }
+ }
+
+ if (word === 'kind' && ((EVENT_KINDS as readonly string[]).includes(value) || value === 'all')) {
+ state.eventFilter = value as State['eventFilter']
+ sync()
+
+ return { text: `events: ${value}` }
+ }
+
+ return { text: word === 'level' ? 'level takes all, bad, warn, ok or info' : `kind takes all, ${EVENT_KINDS.join(', ')}` }
+ }
+
+ if ((EVENT_KINDS as readonly string[]).includes(word) || word === 'all') {
+ state.eventFilter = word as State['eventFilter']
+ sync()
+
+ return { text: `events: ${word}` }
+ }
+
+ if (isLevel(word)) {
+ ui.level = word
+ sync()
+
+ return { text: `events: level ${word}` }
+ }
+
+ const joined = args.join(' ')
+
+ ui.query = maskLine(joined, 200)
+ ui.parsed = parseQuery(ui.query)
+ sync()
+
+ return { text: ui.parsed.errors.length > 0 ? `events: query set, but ${ui.parsed.errors[0]}` : `events: query ${ui.parsed.source}` }
+}
+
+function summary(state: State): string {
+ const ui = eventsUi(state)
+ const model = eventsModel(state, Date.now())
+
+ return `events: ${model.shown.length} of ${model.total} shown · kind ${state.eventFilter} · level ${ui.level} · window ${ui.narrowed === null ? ui.window : 'narrowed'}${ui.parsed.source === '' ? '' : ` · query ${ui.parsed.source}`}${ui.followRef === null ? '' : ` · following ${ui.followRef}`} · ${model.warnBad} warn/bad`
+}
+
diff --git a/plugins/ruflo-console/hooks/events-ui.ts b/plugins/ruflo-console/hooks/events-ui.ts
new file mode 100644
index 0000000000..5d07837469
--- /dev/null
+++ b/plugins/ruflo-console/hooks/events-ui.ts
@@ -0,0 +1,497 @@
+/**
+ * The Events page's own state, its filter pipeline and its actions (ADR-474). The pipeline is memoised by (log version, pause point,
+ * filters, query, window, follow, mutes, clock second): a ten-thousand-event log is filtered once per change, not once per frame, and
+ * only the visible page is turned into rows. State here is per console and never written, except the saved searches, pins and rules
+ * (data/activity-store.ts Prefs) which go through hooks/activity-live.ts.
+ */
+import { isoOf } from './data/safe'
+import { activityOf, clearMemory, markPrefsDirty, pathsOf, seqOf, takeRing } from './activity-live'
+import { MAX_PINS, MAX_RULES, MAX_SEARCHES, type Pin } from './data/activity-store'
+import { exportSpecFor, eventsText, formatOf } from './data/event-export'
+import { collapse, follow, idOf, templateOf, type Row } from './data/event-group'
+import { maskLine } from './data/event-mask'
+import { budgetOf, EMPTY_QUERY, matches, parseQuery, REGEX_BUDGET_MS, type Query } from './data/event-query'
+import { isLevel, levelOfEvent, LEVELS, rankOf, type Level } from './data/event-severity'
+import { bars as barsOf, isWindowId, levelKey, windowStart, type Bars, type WindowId } from './data/event-stats'
+import { EVENT_KINDS, type ConsoleEvent } from './data/events'
+import type { ActionSpec } from './actions'
+import type { Host } from './host'
+import type { State, ViewId } from './state'
+
+export const PAGE = 12
+export const EVENTS_HELP = 'events [kind|level|since:15m|"query"|window <session|15m|1h|24h|all>|clear|forget|export <path>|follow <ref>|pin|rule]'
+
+export type Narrow = { fromMs: number; toMs: number }
+
+export type EventsUi = {
+ query: string
+ parsed: Query
+ window: WindowId
+ narrowed: Narrow | null
+ level: Level | 'all'
+ followRef: string | null
+ mutedKinds: Set<string>
+ mutedTemplates: Set<string>
+ /** The sequence number of the log when the tail was paused, or null while it runs. */
+ pausedSeq: number | null
+ focus: number
+ expanded: Set<string>
+ isGrouped: boolean
+ chartBy: 'kind' | 'level'
+ seenSeq: number
+ said: string | null
+ page: number
+ open: string | null
+ memoKey: string
+ memo: Model | null
+}
+
+export type Model = {
+ shown: ConsoleEvent[]
+ rows: Row[]
+ kindCounts: Map<string, number>
+ levelCounts: Map<Level, number>
+ warnBad: number
+ unread: number
+ total: number
+ unreadBad: number
+ /** Events a regex term was not run on because its time budget was spent (the newest are searched first). */
+ skipped: number
+}
+
+const uis = new WeakMap<State, EventsUi>()
+
+export function eventsUi(state: State): EventsUi {
+ let found = uis.get(state)
+
+ if (found === undefined) {
+ found = { query: '', parsed: EMPTY_QUERY, window: 'all', narrowed: null, level: 'all', followRef: null, mutedKinds: new Set(), mutedTemplates: new Set(), pausedSeq: null, focus: 0, expanded: new Set(), isGrouped: true, chartBy: 'kind', seenSeq: 0, said: null, page: 0, open: null, memoKey: '', memo: null }
+ uis.set(state, found)
+ }
+
+ return found
+}
+
+/** The window the page shows, as times (null: unbounded). A narrowed span, set by pressing a bar, wins over the window id. */
+export function rangeOf(state: State, ui: EventsUi, nowMs: number): { fromMs: number | null; toMs: number | null } {
+ if (ui.narrowed !== null) return { fromMs: ui.narrowed.fromMs, toMs: ui.narrowed.toMs }
+
+ return { fromMs: windowStart(ui.window, nowMs, state.loadedAtMs), toMs: null }
+}
+
+/** The events the page shows now, their counts, and the rows of the page (collapsed bursts, newest first). Memoised. */
+export function eventsModel(state: State, nowMs: number): Model {
+ const act = activityOf(state)
+ const ui = eventsUi(state)
+
+ takeRing(state, act)
+
+ const key = [act.version, ui.pausedSeq, state.eventFilter, ui.level, ui.query, ui.window, ui.narrowed?.fromMs, ui.narrowed?.toMs, ui.followRef, [...ui.mutedKinds].join(), [...ui.mutedTemplates].join(), ui.isGrouped, Math.floor(nowMs / 5000)].join('|')
+
+ if (ui.memo !== null && ui.memoKey === key) return ui.memo
+
+ const upTo = ui.pausedSeq === null ? act.log.length : Math.max(0, Math.min(act.log.length, ui.pausedSeq - act.seqBase))
+ const range = rangeOf(state, ui, nowMs)
+ let pool: ConsoleEvent[] = []
+
+ for (let i = 0; i < upTo; i++) {
+ const event = act.log[i] as ConsoleEvent
+
+ if ((range.fromMs !== null && event.atMs < range.fromMs) || (range.toMs !== null && event.atMs >= range.toMs)) continue
+ if (ui.mutedKinds.has(event.kind) || (ui.mutedTemplates.size > 0 && ui.mutedTemplates.has(templateOf(event.text)))) continue
+ pool.push(event)
+ }
+
+ if (ui.followRef !== null) pool = follow(pool, ui.followRef).events
+
+ const kindCounts = new Map<string, number>()
+ const levelCounts = new Map<Level, number>()
+ const shown: ConsoleEvent[] = []
+
+ const budget = budgetOf(REGEX_BUDGET_MS)
+
+ // Newest first, so that when a slow pattern spends its budget it is the oldest events that are not searched.
+ for (let i = pool.length - 1; i >= 0; i--) {
+ const event = pool[i] as ConsoleEvent
+
+ if (!matches(event, ui.parsed, nowMs, budget)) continue
+
+ const level = levelOfEvent(event)
+
+ kindCounts.set(event.kind, (kindCounts.get(event.kind) ?? 0) + 1)
+ if (state.eventFilter !== 'all' && event.kind !== state.eventFilter) continue
+ levelCounts.set(level, (levelCounts.get(level) ?? 0) + 1)
+ if (ui.level !== 'all' && level !== ui.level) continue
+ shown.push(event)
+ }
+
+ shown.reverse()
+
+ const rows = (ui.isGrouped ? collapse(shown) : shown.map(event => ({ event, members: [event], id: idOf(event) }))).reverse()
+ const taken = new Map<string, number>()
+
+ // Two events can share a millisecond, a kind and a text (a diff makes several at once): a row id must still be its own.
+ for (const entry of rows) {
+ const seen = taken.get(entry.id) ?? 0
+
+ taken.set(entry.id, seen + 1)
+ if (seen > 0) entry.id = `${entry.id}~${seen}`
+ }
+
+ const unread = ui.pausedSeq === null ? 0 : seqOf(act) - ui.pausedSeq
+ const sinceSeen = Math.max(0, Math.min(act.log.length, seqOf(act) - ui.seenSeq))
+ let unreadBad = 0
+
+ for (let i = act.log.length - sinceSeen; i < act.log.length; i++) if (rankOf(levelOfEvent(act.log[i] as ConsoleEvent)) >= 2) unreadBad++
+
+ const model: Model = { shown, rows, kindCounts, levelCounts, warnBad: (levelCounts.get('bad') ?? 0) + (levelCounts.get('warn') ?? 0), unread, total: upTo, unreadBad, skipped: budget.skipped }
+
+ ui.memo = model
+ ui.memoKey = key
+
+ return model
+}
+
+/** Where an event's ref lives: the current state of that thing, in words, and the page that shows it. */
+export function entityOf(state: State, ref: string | undefined): { text: string; go: ViewId } | null {
+ if (ref === undefined) return null
+
+ const [kind, ...rest] = ref.split(':')
+ const id = rest.join(':')
+ const snap = state.snapshot
+
+ switch (kind) {
+ case 'agent': {
+ const agent = snap?.agents.find(item => item.id === id)
+
+ return { text: agent === undefined ? 'agent: not in the store now' : `agent ${agent.name ?? agent.type}: ${agent.status}`, go: 'swarm' }
+ }
+ case 'claim': {
+ const claim = snap?.claims.find(item => item.issueId === id)
+
+ return { text: claim === undefined ? 'claim: released or not on the board now' : `claim ${id}: ${claim.status}${claim.progress === undefined ? '' : ` (${claim.progress}%)`}`, go: 'claims' }
+ }
+ case 'task': {
+ const task = snap?.tasks.find(item => item.id === id)
+
+ return { text: task === undefined ? 'task: not in the store now' : `task ${id}: ${task.status}`, go: 'claims' }
+ }
+ case 'run': {
+ const run = state.wf.read?.runs.find(item => item.id === id)
+
+ return { text: run === undefined ? 'run: not in the last read' : `run ${run.name}: ${run.state}, ${run.done} of ${run.total} agents done`, go: 'workflows' }
+ }
+ case 'mission': {
+ const mission = snap?.missions?.missions.find(item => item.id === id)
+
+ return { text: mission === undefined ? 'mission: not in the last read' : `mission ${id}: ${mission.state}`, go: 'missions' }
+ }
+ case 'step':
+ return { text: 'autopilot step: see the Automation page', go: 'automate' }
+ case 'rule':
+ return { text: `Anatole rule ${id}`, go: 'secure' }
+ default:
+ return null
+ }
+}
+
+/** The one cross-link both pages use: the Events page pre-filtered to follow `ref`, over `win` (a span the Timeline shows) when given. */
+export function openEventsFor(state: State, ref: string, win: Narrow | null = null): void {
+ const ui = eventsUi(state)
+
+ ui.followRef = maskLine(ref, 80)
+ ui.narrowed = win
+ ui.page = 0
+ ui.focus = 0
+ ui.open = null
+ state.eventFilter = 'all'
+ ui.level = 'all'
+}
+
+const nextOf = <T>(order: readonly T[], at: T): T => order[(order.indexOf(at) + 1) % order.length] as T
+
+export type EventsActions = {
+ query: (text: string) => void
+ clearFilters: () => void
+ window: (id: WindowId) => void
+ narrow: (fromMs: number, toMs: number) => void
+ level: (level: Level | 'all') => void
+ cycleLevel: () => void
+ follow: (ref: string | null) => void
+ muteKind: (kind: string) => void
+ muteTemplate: (text: string) => void
+ unmute: () => void
+ pause: () => void
+ move: (by: number) => void
+ focusId: (id: string) => void
+ open: (id: string) => void
+ toggleBurst: (id: string) => void
+ toggleGroup: () => void
+ chartBy: () => void
+ pin: (event: ConsoleEvent) => void
+ unpin: (atMs: number, text: string) => void
+ saveSearch: () => void
+ runSearch: (name: string) => void
+ deleteSearch: (name: string) => void
+ addRule: () => void
+ removeRule: (name: string) => void
+ copy: (event: ConsoleEvent | null) => void
+ exportTo: (format: 'md' | 'jsonl', target: string) => Promise<void>
+ forget: () => void
+ ask: (event: ConsoleEvent) => void
+ page: (by: number) => void
+}
+
+const say = (ui: EventsUi, text: string): void => {
+ ui.said = text
+}
+
+export function eventsActions(state: State, host: Host, invalidate: () => void, askSpec: (spec: ActionSpec | null, why?: string) => void, askClaude: (question: string) => void): EventsActions {
+ const ui = eventsUi(state)
+ const act = activityOf(state)
+ const touch = (): void => {
+ ui.page = 0
+ ui.focus = 0
+ invalidate()
+ }
+ const current = (): ConsoleEvent | null => {
+ const rows = eventsModel(state, Date.now()).rows
+
+ return (rows[ui.focus]?.event ?? null) as ConsoleEvent | null
+ }
+ /** A line under the toolbar, and a redraw: every press says what it did, even when nothing else changed. */
+ const note = (text: string): void => {
+ say(ui, text)
+ invalidate()
+ }
+ const nameOf = (): string => maskLine(ui.parsed.source, 24).replace(/\s+/g, ' ') || 'all'
+
+ return {
+ query: text => {
+ ui.query = maskLine(text, 200)
+ ui.parsed = parseQuery(ui.query)
+ say(ui, ui.parsed.errors[0] ?? '')
+ touch()
+ },
+ clearFilters: () => {
+ ui.query = ''
+ ui.parsed = EMPTY_QUERY
+ ui.level = 'all'
+ ui.followRef = null
+ ui.narrowed = null
+ state.eventFilter = 'all'
+ say(ui, 'filters cleared')
+ touch()
+ },
+ window: id => {
+ if (isWindowId(id)) ui.window = id
+ ui.narrowed = null
+ touch()
+ },
+ narrow: (fromMs, toMs) => {
+ ui.narrowed = { fromMs, toMs }
+ touch()
+ },
+ level: level => {
+ ui.level = level === 'all' || isLevel(level) ? level : 'all'
+ say(ui, ui.level === 'all' ? 'every level shown' : `only ${ui.level} events shown`)
+ touch()
+ },
+ cycleLevel: () => {
+ ui.level = nextOf(['all', ...LEVELS] as const, ui.level)
+ touch()
+ },
+ follow: ref => {
+ ui.followRef = ref === null ? null : maskLine(ref, 80)
+ touch()
+ },
+ muteKind: kind => {
+ ui.mutedKinds.add(kind)
+ say(ui, `muted kind ${kind} for this session`)
+ touch()
+ },
+ muteTemplate: text => {
+ ui.mutedTemplates.add(templateOf(text))
+ say(ui, 'muted lines like that for this session')
+ touch()
+ },
+ unmute: () => {
+ ui.mutedKinds.clear()
+ ui.mutedTemplates.clear()
+ say(ui, 'unmuted')
+ touch()
+ },
+ pause: () => {
+ ui.pausedSeq = ui.pausedSeq === null ? seqOf(act) : null
+ ui.page = 0
+ invalidate()
+ },
+ move: by => {
+ const model = eventsModel(state, Date.now())
+
+ if (model.rows.length === 0) return note(by < 0 ? 'no events above' : 'no events below')
+
+ const next = Math.max(0, Math.min(Math.max(0, model.rows.length - 1), ui.focus + by))
+
+ if (next === ui.focus) return note(by < 0 ? 'already on the newest event' : 'already on the oldest event')
+
+ ui.focus = next
+ ui.page = Math.floor(ui.focus / PAGE)
+ invalidate()
+ },
+ focusId: id => {
+ const at = eventsModel(state, Date.now()).rows.findIndex(row => row.id === id)
+
+ if (at >= 0) ui.focus = at
+ invalidate()
+ },
+ open: id => {
+ ui.open = ui.open === id ? null : id
+ invalidate()
+ },
+ toggleBurst: id => {
+ if (ui.expanded.has(id)) ui.expanded.delete(id)
+ else ui.expanded.add(id)
+ invalidate()
+ },
+ toggleGroup: () => {
+ ui.isGrouped = !ui.isGrouped
+ touch()
+ },
+ chartBy: () => {
+ ui.chartBy = ui.chartBy === 'kind' ? 'level' : 'kind'
+ invalidate()
+ },
+ pin: event => {
+ if (act.isPrefsForeign) return note('the saved file is from a newer console: not changed')
+ if (act.prefs.pins.some(pin => pin.atMs === event.atMs && pin.text === event.text)) return note('already pinned')
+ if (act.prefs.pins.length >= MAX_PINS) return note(`${MAX_PINS} pins is the limit: unpin one first`)
+ act.prefs.pins.push({ atMs: event.atMs, kind: event.kind, text: maskLine(event.text, 240), level: levelOfEvent(event) } satisfies Pin)
+ markPrefsDirty(state)
+ say(ui, 'pinned')
+ invalidate()
+ },
+ unpin: (atMs, text) => {
+ act.prefs.pins = act.prefs.pins.filter(pin => !(pin.atMs === atMs && pin.text === text))
+ markPrefsDirty(state)
+ invalidate()
+ },
+ saveSearch: () => {
+ if (ui.parsed.source === '') return note('type a query first')
+ if (act.isPrefsForeign) return note('the saved file is from a newer console: not changed')
+
+ const name = nameOf()
+
+ act.prefs.searches = [...act.prefs.searches.filter(item => item.name !== name), { name, q: ui.parsed.source }].slice(-MAX_SEARCHES)
+ markPrefsDirty(state)
+ say(ui, `saved search "${name}" (${act.prefs.searches.length} of ${MAX_SEARCHES})`)
+ invalidate()
+ },
+ runSearch: name => {
+ const found = act.prefs.searches.find(item => item.name === name)
+
+ if (found === undefined) return
+ ui.query = found.q
+ ui.parsed = parseQuery(found.q)
+ say(ui, ui.parsed.errors[0] ?? '')
+ touch()
+ },
+ deleteSearch: name => {
+ act.prefs.searches = act.prefs.searches.filter(item => item.name !== name)
+ markPrefsDirty(state)
+ invalidate()
+ },
+ addRule: () => {
+ if (ui.parsed.terms.length === 0 || ui.parsed.errors.length > 0) return note('a rule needs a valid query with at least one term')
+ if (act.isPrefsForeign) return note('the saved file is from a newer console: not changed')
+ if (act.prefs.rules.length >= MAX_RULES && !act.prefs.rules.some(rule => rule.name === nameOf())) return note(`${MAX_RULES} rules is the limit: remove one first`)
+
+ const name = nameOf()
+
+ act.prefs.rules = [...act.prefs.rules.filter(rule => rule.name !== name), { name, q: ui.parsed.source }]
+ markPrefsDirty(state)
+ say(ui, `alert rule "${name}": a band notice when a NEW event matches (history is never scanned)`)
+ invalidate()
+ },
+ removeRule: name => {
+ act.prefs.rules = act.prefs.rules.filter(rule => rule.name !== name)
+ markPrefsDirty(state)
+ invalidate()
+ },
+ copy: event => {
+ const target = event ?? current()
+
+ if (target === null) return note('nothing focused to copy')
+
+ const text = `${isoOf(target.atMs)} ${levelOfEvent(target)} ${target.kind} ${maskLine(target.text, 240)}`
+
+ void host.fillPrompt(text).then(
+ ok => {
+ say(ui, ok ? 'put the masked line in the prompt box' : 'no prompt box here: the line is not copied')
+ invalidate()
+ },
+ () => say(ui, 'the prompt box refused it'),
+ )
+ },
+ exportTo: async (format, target) => {
+ const model = eventsModel(state, Date.now())
+ const title = ui.parsed.source === '' ? `${model.shown.length} shown` : ui.parsed.source
+ const checked = formatOf(target) === null ? `${target}.${format}` : target
+ const made = await exportSpecFor(host.fs, state.cwd, checked, eventsText(model.shown, formatOf(checked) === 'jsonl' ? 'jsonl' : 'md', title, Date.now()), `${model.shown.length} events`, ['md', 'jsonl'])
+
+ if (!made.ok) {
+ say(ui, made.why)
+ invalidate()
+
+ return
+ }
+
+ askSpec(made.spec, 'that export cannot run here')
+ },
+ forget: () => {
+ const paths = pathsOf(state.cwd)
+
+ askSpec(
+ {
+ label: 'forget the Events and Timeline history',
+ args: [],
+ argv: ['rm', '-f', '--', paths.events, paths.lanes],
+ expect: 'events.jsonl and lanes.jsonl removed',
+ declared: 'delete',
+ shows: `rm -f -- ${paths.events} ${paths.lanes}`,
+ note: 'deletes only the console\'s own history files for this project; saved searches, pins and rules stay',
+ timeoutMs: 10_000,
+ onOutput: () => {
+ clearMemory(state)
+ say(ui, 'history forgotten')
+ },
+ verifyLocal: async h => (await h.fs.stat(paths.events).catch(() => undefined)) === undefined,
+ },
+ 'that cannot run here',
+ )
+ },
+ ask: event => askClaude(`This event appeared in my ruflo console: "${maskLine(event.text, 200)}" (kind ${event.kind}, level ${levelOfEvent(event)}). What does it mean, and should I do anything?`),
+ page: by => {
+ const model = eventsModel(state, Date.now())
+ const last = Math.max(0, Math.ceil(model.rows.length / PAGE) - 1)
+
+ ui.page = Math.max(0, Math.min(last, ui.page + by))
+ ui.focus = ui.page * PAGE
+ invalidate()
+ },
+ }
+}
+
+/** The colours of the chart's keys: kinds and levels each have one. */
+export const KIND_RGB = [0x2fa4c9, 0xe0a526, 0x2bb673, 0x8b7cf6, 0x6ec1e4, 0xe5534b, 0xb48ead, 0x56b6c2, 0xd19a66, 0xe5c07b, 0x98c379, 0x6b7280]
+export const LEVEL_RGB_LIST = [0xe5534b, 0xe0a526, 0x2bb673, 0x2fa4c9]
+
+/** The activity chart's bars for the page: by kind or level, over the window shown (a window with no start spans the shown events, at least 15 min). */
+export function chartOf(state: State, model: Model, nowMs: number, columns: number): { data: Bars; colors: number[] } {
+ const ui = eventsUi(state)
+ const range = rangeOf(state, ui, nowMs)
+ const span = range.fromMs === null ? Math.max(15 * 60_000, nowMs - (model.shown[0]?.atMs ?? nowMs)) : (range.toMs ?? nowMs) - range.fromMs
+ const keys: string[] = ui.chartBy === 'kind' ? [...EVENT_KINDS] : [...LEVELS]
+
+ return { data: barsOf(model.shown, keys, ui.chartBy === 'kind' ? event => event.kind : levelKey, Math.max(60_000, span), range.toMs ?? nowMs, Math.max(12, Math.min(48, columns - 12))), colors: ui.chartBy === 'kind' ? KIND_RGB : LEVEL_RGB_LIST }
+}
diff --git a/plugins/ruflo-console/hooks/gfx/ev-charts.ts b/plugins/ruflo-console/hooks/gfx/ev-charts.ts
new file mode 100644
index 0000000000..7a116f1ecb
--- /dev/null
+++ b/plugins/ruflo-console/hooks/gfx/ev-charts.ts
@@ -0,0 +1,53 @@
+/**
+ * Pictures of the Events and Timeline pages (ADR-474): a stacked activity chart and the Timeline's lanes. Pure functions of data that
+ * return a Grid; both have a text twin built from the same data (views/events-parts.ts, views/timeline.ts).
+ */
+import type { Line, Tone } from '../data/timeline-lines'
+import type { Bars } from '../data/event-stats'
+import { COLOR, Grid, mix } from './raster'
+
+const TONE: Record<Tone, number> = { busy: COLOR.warn, idle: mix(COLOR.info, 0x000000, 0.3), tool: 0xffffff, none: COLOR.line, warn: COLOR.warn, bad: COLOR.bad, dim: COLOR.dim, plain: 0xd0d0d0 }
+
+/** Bars stacked by key: each column is one bucket, filled from the bottom in the keys' colours, scaled to the tallest bucket. */
+export function stackedPicture(data: Bars, colors: readonly number[], columns: number, rows: number): Grid {
+ const grid = new Grid(columns, rows)
+ const totals = data.stacks.map(stack => stack.reduce((a, b) => a + b, 0))
+ const top = Math.max(1, ...totals)
+ const width = Math.max(1, Math.min(3, Math.floor((columns - 6) / Math.max(1, data.stacks.length))))
+
+ grid.text(0, 0, String(top).padStart(4), COLOR.dim)
+ grid.text(0, rows - 1, ' 0', COLOR.dim)
+
+ data.stacks.forEach((stack, i) => {
+ const high = totals[i] === 0 ? 0 : Math.max(1, Math.round(((totals[i] as number) / top) * rows))
+ let drawn = 0
+ let acc = 0
+
+ stack.forEach((n, k) => {
+ acc += n
+
+ const upTo = totals[i] === 0 ? 0 : Math.round((acc / (totals[i] as number)) * high)
+
+ for (; drawn < upTo; drawn++) for (let w = 0; w < width; w++) grid.set(5 + i * width + w, rows - 1 - drawn, '█', colors[k] ?? COLOR.info)
+ })
+
+ if (high === 0) grid.set(5 + i * width, rows - 1, '·', COLOR.line)
+ })
+
+ return grid
+}
+
+/** The lines of data/timeline-lines.ts, one grid row each. */
+export function linesPicture(lines: readonly Line[], columns: number): Grid {
+ const grid = new Grid(columns, Math.max(1, lines.length))
+
+ lines.forEach((line, y) => {
+ grid.text(0, y, line.label, line.isCursor === true ? 0xffffff : line.kind === 'group' ? COLOR.accent : 0xd0d0d0)
+
+ const x0 = line.label.length + 1
+
+ line.cells.forEach((cell, x) => grid.set(x0 + x, y, cell.ch, TONE[cell.tone]))
+ })
+
+ return grid
+}
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index 82a8e76fda..97b64b0f49 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -114,6 +114,8 @@ export type Options = GuardOptions & ConvoOptions & {
look: 'bbs' | 'plain'
/** With the bbs look, a short dial-up boot screen when the cockpit opens. */
boot: boolean
+ /** ADR-474: keep the Events and Timeline history in `.claude-flow/console/` (events.jsonl, lanes.jsonl). On by default; masked text only. */
+ eventsPersist: boolean
}
const num = (value: unknown, fallback: number, lo: number, hi: number): number => {
@@ -135,6 +137,7 @@ export function optionsOf(raw: PluginOptions | undefined): Options {
federationNetwork: value.federationNetwork === true,
look: value.look === 'plain' ? 'plain' : 'bbs',
boot: value.boot !== false,
+ eventsPersist: value.eventsPersist !== false && value.eventsPersist !== 'false',
...guardOptionsOf(raw),
...convoOptionsOf(raw),
}
diff --git a/plugins/ruflo-console/hooks/timeline-ui.ts b/plugins/ruflo-console/hooks/timeline-ui.ts
new file mode 100644
index 0000000000..bd82976a63
--- /dev/null
+++ b/plugins/ruflo-console/hooks/timeline-ui.ts
@@ -0,0 +1,294 @@
+/**
+ * The Timeline page's own state, model and actions (ADR-474): the window and how far back it is panned, lane groups that fold, a sort,
+ * a cursor over the visible lanes, one lane opened for detail, and the cross-links to the Events page. The model is memoised by the
+ * lane store's version, the window, the sort and the clock second, and the page draws only the lanes of one page.
+ */
+import { activityOf, pathsOf } from './activity-live'
+import { eventsUi, openEventsFor } from './events-ui'
+import { LANE_GROUPS, type LaneGroup } from './data/activity-store'
+import { exportSpecFor, lanesText, type LaneExport } from './data/event-export'
+import { maskLine } from './data/event-mask'
+import { rankOf } from './data/event-severity'
+import { levelOfEvent } from './data/event-severity'
+import type { ConsoleEvent } from './data/events'
+import { busiestMinute, clockOf, concurrency, idleGaps, isTlWindow, lanesIn, lastProblem, sortLanes, SORTS, windowOf, zoomed, type Concurrency, type IdleGap, type LaneView, type SortId, type TlWindowId } from './data/timeline-model'
+import { formatOf } from './data/event-export'
+import type { ActionSpec } from './actions'
+import type { Host } from './host'
+import type { State, ViewId } from './state'
+
+export const LANES_PAGE = 12
+export const BARS_MIN = 24
+
+export type Entry = { type: 'group'; group: LaneGroup; count: number; busy: number; isOpen: boolean } | { type: 'lane'; lane: LaneView }
+
+export type TimelineUi = {
+ window: TlWindowId
+ /** How far the window is panned back from now (0 is the live edge). */
+ offsetMs: number
+ sort: SortId
+ collapsed: Set<LaneGroup>
+ page: number
+ cursor: number
+ open: string | null
+ said: string | null
+ /** The time of the problem the last jump went to (null after any other move): the next jump looks before it. */
+ problemAt: number | null
+ memoKey: string
+ memo: TlModel | null
+}
+
+export type TlModel = {
+ win: { fromMs: number; toMs: number; spanMs: number }
+ lanes: LaneView[]
+ entries: Entry[]
+ concurrency: Concurrency
+ gaps: IdleGap[]
+ busiest: { atMs: number; n: number } | null
+ problems: ConsoleEvent[]
+ total: number
+}
+
+const uis = new WeakMap<State, TimelineUi>()
+
+export function timelineUi(state: State): TimelineUi {
+ let found = uis.get(state)
+
+ if (found === undefined) {
+ found = { window: '15m', offsetMs: 0, sort: 'busy', collapsed: new Set(), page: 0, cursor: 0, open: null, said: null, problemAt: null, memoKey: '', memo: null }
+ uis.set(state, found)
+ }
+
+ return found
+}
+
+export function timelineModel(state: State, nowMs: number, bars = 60): TlModel {
+ const act = activityOf(state)
+ const ui = timelineUi(state)
+ const key = [act.lanes.version, act.version, ui.window, ui.offsetMs, ui.sort, [...ui.collapsed].join(), Math.floor(nowMs / 2000), bars].join('|')
+
+ if (ui.memo !== null && ui.memoKey === key) return ui.memo
+
+ const win = windowOf(ui.window, ui.offsetMs, nowMs, state.loadedAtMs)
+ const lanes = lanesIn(act.lanes, win, nowMs)
+ const entries: Entry[] = []
+
+ for (const group of LANE_GROUPS) {
+ const inGroup = sortLanes(lanes.filter(lane => lane.group === group), ui.sort)
+
+ if (inGroup.length === 0) continue
+
+ const isOpen = !ui.collapsed.has(group)
+
+ entries.push({ type: 'group', group, count: inGroup.length, busy: inGroup.filter(lane => (lane.busyPct ?? 0) > 0 || lane.calls > 0).length, isOpen })
+ if (isOpen) for (const lane of inGroup) entries.push({ type: 'lane', lane })
+ }
+
+ const problems = act.log.filter(event => event.atMs >= win.fromMs && event.atMs < win.toMs && rankOf(levelOfEvent(event)) >= 2)
+ const model: TlModel = { win, lanes, entries, concurrency: concurrency(lanes, win, act.lanes, Math.max(BARS_MIN, bars)), gaps: idleGaps(lanes.filter(lane => lane.group === 'ruflo' || lane.group === 'workflow'), win, act.lanes), busiest: busiestMinute(act.lanes, win), problems, total: lanes.length }
+
+ ui.memo = model
+ ui.memoKey = key
+
+ return model
+}
+
+/** The page that shows a lane's thing, and the ref the Events page follows for it. */
+export function laneRef(lane: LaneView): { ref: string; go: ViewId } {
+ const id = lane.lane.slice(lane.lane.indexOf(':') + 1)
+
+ switch (lane.group) {
+ case 'ruflo':
+ return { ref: `agent:${id}`, go: 'swarm' }
+ case 'workflow':
+ return { ref: `run:${id.split('/')[0]}`, go: 'workflows' }
+ case 'mission':
+ return { ref: `task:${id}`, go: 'missions' }
+ case 'autopilot':
+ return { ref: `step:${id}`, go: 'automate' }
+ default:
+ return { ref: lane.lane, go: 'events' }
+ }
+}
+
+export type TimelineActions = {
+ window: (id: TlWindowId) => void
+ zoom: (by: 1 | -1) => void
+ pan: (by: number) => void
+ now: () => void
+ start: () => void
+ problem: () => void
+ move: (by: number) => void
+ open: (lane: string | null) => void
+ toggleGroup: (group: LaneGroup) => void
+ sort: () => void
+ page: (by: number) => void
+ events: (lane: LaneView) => void
+ go: (lane: LaneView) => void
+ ask: (lane: LaneView) => void
+ exportTo: (format: 'md' | 'csv', target: string) => Promise<void>
+}
+
+export function timelineActions(state: State, host: Host, invalidate: () => void, view: (id: ViewId) => void, askSpec: (spec: ActionSpec | null, why?: string) => void, askClaude: (question: string) => void): TimelineActions {
+ const ui = timelineUi(state)
+ const act = activityOf(state)
+ const model = (): TlModel => timelineModel(state, Date.now())
+ const lanesOnly = (): LaneView[] => model().entries.flatMap(entry => (entry.type === 'lane' ? [entry.lane] : []))
+ const keep = (): void => {
+ ui.problemAt = null
+ ui.offsetMs = Math.max(0, ui.offsetMs)
+ invalidate()
+ }
+
+ return {
+ window: id => {
+ if (isTlWindow(id)) ui.window = id
+ ui.page = 0
+ keep()
+ },
+ zoom: by => {
+ ui.window = zoomed(ui.window, by)
+ keep()
+ },
+ pan: by => {
+ const span = model().win.spanMs
+
+ ui.offsetMs = Math.max(0, ui.offsetMs - by * span * 0.5)
+ keep()
+ },
+ now: () => {
+ ui.said = ui.offsetMs === 0 ? 'already at the live edge' : 'back at the live edge'
+ ui.offsetMs = 0
+ keep()
+ },
+ start: () => {
+ const first = Math.min(...act.lanes.spans.map(span => span.fromMs), Number.POSITIVE_INFINITY)
+
+ if (Number.isFinite(first)) {
+ ui.offsetMs = Math.max(0, Date.now() - first - model().win.spanMs)
+ ui.said = `jumped to the start of what was observed (${clockOf(first, true)})`
+ } else ui.said = 'nothing has been observed yet'
+
+ keep()
+ },
+ problem: () => {
+ const m = model()
+ // Pressed again after a jump it goes one problem further back: the window is centred on the last one found, so look before that centre.
+ const found = lastProblem(act.log, ui.problemAt !== null && ui.offsetMs > 0 ? ui.problemAt : m.win.toMs)
+
+ if (found === null) {
+ ui.said = 'no warn or bad event before this window'
+ return invalidate()
+ }
+
+ ui.offsetMs = Math.max(0, Date.now() - found.atMs - m.win.spanMs / 2)
+ ui.said = `jumped to ${found.kind}: ${maskLine(found.text, 60)}`
+ keep()
+ ui.problemAt = found.atMs
+ },
+ move: by => {
+ const lanes = lanesOnly()
+ const next = Math.max(0, Math.min(Math.max(0, lanes.length - 1), ui.cursor + by))
+
+ // At either end the press still answers: a button that does nothing and says nothing looks broken.
+ ui.said = lanes.length === 0 ? 'no lanes in this window' : next === ui.cursor && ui.cursor === (by < 0 ? 0 : lanes.length - 1) && lanes.length > 0 ? (by < 0 ? 'already on the first lane' : 'already on the last lane') : ui.said
+ ui.cursor = next
+ ui.page = Math.floor(model().entries.findIndex(entry => entry.type === 'lane' && entry.lane === lanes[ui.cursor]) / LANES_PAGE)
+ ui.page = Math.max(0, ui.page)
+ invalidate()
+ },
+ open: lane => {
+ ui.open = ui.open === lane ? null : lane
+ invalidate()
+ },
+ toggleGroup: group => {
+ if (ui.collapsed.has(group)) ui.collapsed.delete(group)
+ else ui.collapsed.add(group)
+ ui.page = 0
+ invalidate()
+ },
+ sort: () => {
+ ui.sort = SORTS[(SORTS.indexOf(ui.sort) + 1) % SORTS.length] as SortId
+ invalidate()
+ },
+ page: by => {
+ const last = Math.max(0, Math.ceil(model().entries.length / LANES_PAGE) - 1)
+
+ ui.page = Math.max(0, Math.min(last, ui.page + by))
+ invalidate()
+ },
+ events: lane => {
+ const m = model()
+
+ openEventsFor(state, laneRef(lane).ref, { fromMs: m.win.fromMs, toMs: m.win.toMs })
+ eventsUi(state).said = `following ${laneRef(lane).ref} over the Timeline's window`
+ view('events')
+ },
+ go: lane => view(laneRef(lane).go),
+ ask: lane => askClaude(`In my ruflo console the lane "${maskLine(lane.label, 40)}" (${lane.group}) was busy ${lane.busyPct ?? 'n/a'}% of the observed time with ${lane.calls} tool calls in this window. Is that healthy, and what should I look at?`),
+ exportTo: async (format, target) => {
+ const m = model()
+ const data: LaneExport = { lanes: m.lanes, concurrency: m.concurrency, fromMs: m.win.fromMs, toMs: m.win.toMs, busiest: m.busiest }
+ const checked = formatOf(target) === null ? `${target}.${format}` : target
+ const made = await exportSpecFor(host.fs, state.cwd, checked, lanesText(data, formatOf(checked) === 'csv' ? 'csv' : 'md', Date.now()), `${m.lanes.length} lane summaries`, ['md', 'csv'])
+
+ if (!made.ok) {
+ ui.said = made.why
+ return invalidate()
+ }
+
+ askSpec(made.spec, 'that export cannot run here')
+ },
+ }
+}
+
+/** `/ruflo timeline <args>`: window, zoom, follow. `export` is for the caller. */
+export function applyTimelineArgs(state: State, args: readonly string[]): { text: string; export?: { format: 'md' | 'csv'; path: string }; follow?: string } {
+ const ui = timelineUi(state)
+ const [first = '', ...rest] = args
+ const word = first.toLowerCase()
+
+ if (isTlWindow(word)) {
+ ui.window = word
+ ui.offsetMs = 0
+ ui.page = 0
+
+ return { text: `timeline: ${word}` }
+ }
+
+ if (word === 'zoom') {
+ const dir = rest[0]
+
+ if (dir !== 'in' && dir !== 'out') return { text: 'zoom takes in or out' }
+ ui.window = zoomed(ui.window, dir === 'in' ? -1 : 1)
+
+ return { text: `timeline: ${ui.window}` }
+ }
+
+ if (word === 'follow') {
+ const ref = rest.join(' ').trim()
+
+ if (ref === '') return { text: 'follow takes a ref such as agent:<id> or run:<id>' }
+ const m = timelineModel(state, Date.now())
+
+ openEventsFor(state, ref, { fromMs: m.win.fromMs, toMs: m.win.toMs })
+
+ return { text: `timeline: following ${maskLine(ref, 80)} on the Events page`, follow: ref }
+ }
+
+ if (word === 'export') {
+ const path = rest.join(' ').trim()
+
+ return { text: 'checking the path', export: { format: formatOf(path) === 'csv' ? 'csv' : 'md', path } }
+ }
+
+ if (word === '') {
+ const m = timelineModel(state, Date.now())
+
+ return { text: `timeline: window ${ui.window}${ui.offsetMs > 0 ? ` panned ${Math.round(ui.offsetMs / 60000)} min back` : ''} · ${m.total} lanes · concurrency peak ${m.concurrency.peak}, mean ${m.concurrency.mean}` }
+ }
+
+ return { text: 'timeline [5m|15m|1h|6h|24h|session|zoom <in|out>|follow <ref>|export <path>]' }
+}
+
+export { pathsOf }
diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts
index 14f0182218..8428db9030 100644
--- a/plugins/ruflo-console/hooks/version.ts
+++ b/plugins/ruflo-console/hooks/version.ts
@@ -2,4 +2,4 @@
* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest
* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.
*/
-export const CONSOLE_VERSION = '0.35.0'
+export const CONSOLE_VERSION = '0.36.0'
diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts
index 6de79e9ac0..c5050de667 100644
--- a/plugins/ruflo-console/hooks/views/common.ts
+++ b/plugins/ruflo-console/hooks/views/common.ts
@@ -8,6 +8,8 @@ import type { OptimizerActions } from '../optimizer'
import { askedBy } from '../data/room'
import type { RoomActions } from '../room'
import type { WatchActions } from '../watch'
+import type { EventsActions } from '../events-ui'
+import type { TimelineActions } from '../timeline-ui'
import type { Attention } from './attention'
import { HEADS, mark as marked } from './marks'
import type { LoopActions } from '../loops'
@@ -91,6 +93,10 @@ export type Actions = {
optimizer: OptimizerActions
/** The Timeline and Events pages: look-back range, kind filter, search, pause, paging, an event's detail, and asking about one. */
watch: WatchActions
+ /** The Events page (ADR-474): query, level, window, follow, mutes, pins, saved searches, alert rules, export. */
+ events: EventsActions
+ /** The Timeline page (ADR-474): window, zoom, pan, lane groups, sort, lane detail, cross-links, export. */
+ timeline: TimelineActions
/** The Room (ADR-448): the draft, what to send through, the feed's source filter, search, pause and paging. */
room: RoomActions
/** Ask Claude about this section (a visible prompt or a /btw aside) or run the plugin command that fits it: each asks first. */
diff --git a/plugins/ruflo-console/hooks/views/events-parts.ts b/plugins/ruflo-console/hooks/views/events-parts.ts
new file mode 100644
index 0000000000..65a71a2712
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/events-parts.ts
@@ -0,0 +1,105 @@
+/**
+ * Pieces of the Events page (ADR-474): one event row with highlighted matches, the opened event's detail pane (its words, source,
+ * level, the current state of the thing it is about with buttons that go to its page, and five events either side), and the chips.
+ * Every row is measured to fit the pane: the text is clipped to what is left after the fixed cells, never wrapped.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { isoOf } from '../data/safe'
+import { highlights, type Query } from '../data/event-query'
+import { neighbours, type Row } from '../data/event-group'
+import { levelOfEvent, type Level } from '../data/event-severity'
+import { refOf, type ConsoleEvent } from '../data/events'
+import { entityOf, eventsUi } from '../events-ui'
+import { ago, button, clip, col, row, text, THEME, type Ctx } from './common'
+import { flow, safe, type Btn } from './wf-layout'
+
+export const LEVEL_COLOR: Record<Level, () => string> = { ok: () => THEME.ok, info: () => THEME.info, warn: () => THEME.warn, bad: () => THEME.bad }
+export const LEVEL_MARK: Record<Level, string> = { ok: '✓', info: 'ℹ', warn: '⚠', bad: '✖' }
+export const KIND_COLOR = (kind: string): string => ({ swarm: THEME.info, claims: THEME.warn, federation: THEME.ok, learning: THEME.head, tools: THEME.info, mods: THEME.bad, missions: THEME.head, workflows: THEME.ok, autopilot: THEME.warn, anatole: THEME.bad, notices: THEME.head })[kind] ?? THEME.info
+
+export const chip = (key: string, label: string, isOn: boolean, onPress: () => void): Btn => ({ key, label: ` ${isOn ? '●' : '○'} ${label} `, onPress, ...(isOn && { primary: true }) })
+
+/** The text of a row cut to `room` cells, as runs: the parts the query matched are bold and bright. */
+function runs(ctx: Ctx, value: string, query: Query, room: number): RenderElement[] {
+ const shown = clip(value, room)
+ const marks = highlights(shown, query)
+ const out: RenderElement[] = []
+ let at = 0
+
+ for (const [from, to] of marks) {
+ if (from > at) out.push(ctx.kit.Text({ children: shown.slice(at, from) }))
+ out.push(ctx.kit.Text({ bold: true, color: THEME.head, children: shown.slice(from, to) }))
+ at = to
+ }
+
+ if (at < shown.length || out.length === 0) out.push(ctx.kit.Text({ children: shown.slice(at) }))
+
+ return out
+}
+
+export function eventRow(ctx: Ctx, entry: Row, query: Query, isFocused: boolean, isOpen: boolean, nowMs: number): RenderElement {
+ const event = entry.event
+ const level = levelOfEvent(event)
+ const count = entry.members.length > 1 ? ` ×${entry.members.length}` : ''
+ // Fixed cells: age 9, mark 2, kind 11, open button 5, count text.
+ const room = Math.max(8, ctx.columns - 9 - 2 - 11 - 5 - count.length)
+ const id = entry.id
+
+ return row(
+ ctx,
+ [
+ ctx.kit.Text({ dimColor: true, children: `${ago(event.atMs, nowMs).padStart(8)} ` }),
+ ctx.kit.Text({ color: LEVEL_COLOR[level](), children: `${isFocused ? '▸' : LEVEL_MARK[level]} ` }),
+ ctx.kit.Text({ color: KIND_COLOR(event.kind), children: `${event.kind.slice(0, 10).padEnd(10)} ` }),
+ ...runs(ctx, event.text, query, room),
+ ...(count === '' ? [] : [ctx.kit.Text({ color: THEME.warn, children: count })]),
+ ctx.kit.Button({ key: `ev-open-${id}`, label: isOpen ? '▾' : '▸', plain: true, onPress: safe(() => ctx.act.events.open(id)) }),
+ ],
+ `ev-${id}`,
+ )
+}
+
+const line = (ctx: Ctx, value: string, props: { dimColor?: boolean; bold?: boolean; color?: string } = {}): RenderElement => text(ctx, ` ${value}`, props)
+
+/** The opened event: words, facts, the entity's state now, buttons, and the five events either side (from the unfiltered shown list so the neighbours are what really surrounded it). */
+export function detailRows(ctx: Ctx, entry: Row, around: readonly ConsoleEvent[], nowMs: number): RenderElement[] {
+ const event = entry.event
+ const ref = refOf(event)
+ const entity = entityOf(ctx.state, ref)
+ const act = ctx.act.events
+ const out: RenderElement[] = [line(ctx, event.text, { bold: true }), line(ctx, `${levelOfEvent(event)} · ${event.kind} · ${isoOf(event.atMs)} · source ${event.src ?? 'observed'}${event.agentId === undefined ? '' : ` · agent ${clip(event.agentId, 24)}`}${ref === undefined ? '' : ` · ref ${clip(ref, 30)}`}`, { dimColor: true })]
+
+ if (entity !== null) out.push(line(ctx, `now: ${entity.text}`, { color: THEME.info }))
+ else if (ref !== undefined) out.push(line(ctx, 'now: nothing in the last read for this ref', { dimColor: true }))
+
+ const buttons: Btn[] = [
+ { key: 'ev-ask', label: ' ✦ ask Claude ', onPress: () => act.ask(event) },
+ { key: 'ev-pin', label: ' 📌 pin ', onPress: () => act.pin(event) },
+ { key: 'ev-copy', label: ' ⧉ copy line ', onPress: () => act.copy(event) },
+ { key: 'ev-mute-kind', label: ` mute ${event.kind} `, onPress: () => act.muteKind(event.kind) },
+ { key: 'ev-mute-like', label: ' mute lines like this ', onPress: () => act.muteTemplate(event.text) },
+ ...(ref === undefined ? [] : [{ key: 'ev-follow', label: ' ⤳ follow ', onPress: () => act.follow(ref) }]),
+ ...(entity === null ? [] : [{ key: 'ev-go', label: ` open ${entity.go} `, onPress: () => ctx.act.view(entity.go) }]),
+ ...(entry.members.length > 1 ? [{ key: 'ev-burst', label: eventsUi(ctx.state).expanded.has(entry.id) ? ' fold the burst ' : ` show ${entry.members.length} in the burst `, onPress: () => act.toggleBurst(entry.id) }] : []),
+ ]
+
+ out.push(...flow(ctx, buttons, 'ev-detail'))
+
+ if (eventsUi(ctx.state).expanded.has(entry.id)) {
+ for (const member of entry.members.slice(-8).reverse()) out.push(line(ctx, `${ago(member.atMs, nowMs).padStart(8)} ${member.text}`, { dimColor: true }))
+ }
+
+ const at = around.indexOf(event)
+ const near = neighbours(around, at, 5)
+
+ if (near.before.length + near.after.length > 0) {
+ out.push(line(ctx, 'around it (5 before, 5 after):', { dimColor: true }))
+ for (const item of [...near.before, event, ...near.after]) out.push(line(ctx, `${item === event ? '▸' : ' '} ${isoOf(item.atMs).slice(11, 19)} ${item.kind.padEnd(9)} ${item.text}`, item === event ? { bold: true } : { dimColor: true }))
+ }
+
+ return out
+}
+
+export const stack = (ctx: Ctx, rows: readonly RenderElement[], key: string): RenderElement => col(ctx, rows, key)
+export { button }
diff --git a/plugins/ruflo-console/hooks/views/events.ts b/plugins/ruflo-console/hooks/views/events.ts
new file mode 100644
index 0000000000..6209e56a38
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/events.ts
@@ -0,0 +1,131 @@
+/**
+ * The Events page (ADR-474): history kept across restarts, every source the console observes, a level on every event, a small query
+ * language, bursts collapsed, a detail pane with the entity's state now, a stacked activity chart, pins, saved searches, alert rules
+ * and an export. Each row is measured to fit 56 to 125 columns; only the visible page is built.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { activityOf, storeNote } from '../activity-live'
+import { barsLine, bars as barsOf, dayHour, heatLine, WINDOWS } from '../data/event-stats'
+import { EVENT_KINDS } from '../data/events'
+import { LEVELS } from '../data/event-severity'
+import { MAX_PINS, MAX_RULES, MAX_SEARCHES } from '../data/activity-store'
+import { sparkline } from '../memory-lines'
+import { chartOf, eventsModel, eventsUi, PAGE, rangeOf } from '../events-ui'
+import { ago, clip, col, picture, row, rule, text, THEME, type Ctx } from './common'
+import { chip, detailRows, eventRow, KIND_COLOR, LEVEL_COLOR, LEVEL_MARK } from './events-parts'
+import { flow, safe, type Btn } from './wf-layout'
+
+/** The words a long note is wrapped into, each line at most `width` cells, by the ` · ` joints. */
+export function notelines(note: string, width: number): string[] {
+ const out: string[] = []
+ let current = ''
+
+ for (const part of note.split(' · ')) {
+ if (current !== '' && current.length + part.length + 3 > width) {
+ out.push(current)
+ current = part
+ } else current = current === '' ? part : `${current} · ${part}`
+ }
+
+ if (current !== '') out.push(current)
+
+ return out.map(item => clip(item, width))
+}
+
+export function eventsView(ctx: Ctx): RenderElement {
+ const { state, nowMs } = ctx
+ const ui = eventsUi(state)
+ const act = activityOf(state)
+ const a = ctx.act.events
+ const model = eventsModel(state, nowMs)
+ const pages = Math.max(1, Math.ceil(model.rows.length / PAGE))
+ const page = Math.min(ui.page, pages - 1)
+ const visible = model.rows.slice(page * PAGE, page * PAGE + PAGE)
+ const range = rangeOf(state, ui, nowMs)
+ const filter = state.eventFilter
+ const windowLabel = ui.narrowed !== null ? 'narrowed' : (WINDOWS.find(item => item.id === ui.window)?.label ?? ui.window)
+ const rows: RenderElement[] = [rule(ctx, 'Events', `${model.shown.length} of ${model.total} · ${windowLabel}${model.warnBad > 0 ? ` · ${model.warnBad} warn/bad` : ''}${ui.pausedSeq === null ? ' · live' : ` · paused (${model.unread} new)`}${ui.followRef === null ? '' : ` · following ${clip(ui.followRef, 24)}`}`)]
+
+ rows.push(...flow(ctx, [chip('ev-kind-all', `all ${model.total}`, filter === 'all', () => ctx.act.watch.kind('all')), ...EVENT_KINDS.filter(kind => (model.kindCounts.get(kind) ?? 0) > 0 || filter === kind).map(kind => chip(`ev-kind-${kind}`, `${kind} ${model.kindCounts.get(kind) ?? 0}`, filter === kind, () => ctx.act.watch.kind(kind)))], 'ev-kinds', 'kind '))
+ rows.push(...flow(ctx, [chip('ev-level-all', 'any', ui.level === 'all', () => a.level('all')), ...LEVELS.map(level => chip(`ev-level-${level}`, `${LEVEL_MARK[level]} ${level} ${model.levelCounts.get(level) ?? 0}`, ui.level === level, () => a.level(level)))], 'ev-levels', 'level '))
+ rows.push(...flow(ctx, WINDOWS.map(item => chip(`ev-win-${item.id}`, item.label, ui.narrowed === null && ui.window === item.id, () => a.window(item.id))), 'ev-windows', 'window '))
+
+ const Input = ctx.kit.Input
+
+ if (Input !== undefined) rows.push(ctx.kit.Box({ key: 'ev-query-box', borderStyle: 'round', borderColor: THEME.info, paddingX: 1, children: [Input({ key: 'ev-query', label: '🔎', placeholder: 'words "phrase" -not kind:swarm level:bad agent:x since:1h a|b /re/', submitLabel: 'find', onSubmit: (value: string) => a.query(value) })] }))
+ if (ui.parsed.errors.length > 0) rows.push(text(ctx, `⚠ ${ui.parsed.errors[0]}`, { color: THEME.warn }))
+ else if (ui.said !== null && ui.said !== '') rows.push(text(ctx, ui.said, { dimColor: true }))
+
+ if (model.skipped > 0) rows.push(text(ctx, `⚠ that /regex/ is slow: ${model.skipped} older events were not searched. Narrow the window or simplify it.`, { color: THEME.warn }))
+
+ const tools: Btn[] = [
+ { key: 'ev-pause', label: ui.pausedSeq === null ? ' ⏸ pause ' : ` ▶ resume (${model.unread} new) `, onPress: a.pause, hotkey: 't', ...(ui.pausedSeq !== null && { primary: true }) },
+ { key: 'ev-level-cycle', label: ' level ', onPress: a.cycleLevel, hotkey: 'l' },
+ { key: 'ev-clear', label: ' ✕ clear filters ', onPress: a.clearFilters, hotkey: 'c' },
+ { key: 'ev-group', label: ui.isGrouped ? ' bursts: folded ' : ' bursts: all ', onPress: a.toggleGroup },
+ { key: 'ev-chart-by', label: ` chart by ${ui.chartBy} `, onPress: a.chartBy },
+ { key: 'ev-copy-focused', label: ' ⧉ copy focused ', onPress: () => a.copy(null), hotkey: 'v' },
+ ]
+
+ rows.push(...flow(ctx, tools, 'ev-tools'))
+
+ const { data } = chartOf(state, model, nowMs, ctx.columns)
+
+ rows.push(picture(ctx, 'ev-chart', ' '))
+ rows.push(text(ctx, ` ${windowLabel} ${barsLine(data)} now · bars of ${Math.round(data.stepMs / 60_000)} min, by ${ui.chartBy}`, { color: THEME.info }))
+ rows.push(text(ctx, ` last 15 min ${sparkline(barsOf(model.shown, ['x'], () => 'x', 15 * 60_000, nowMs, 15).stacks.map(stack => stack[0] ?? 0))}`, { dimColor: true }))
+
+ if (data.stacks.length > 1) {
+ const peak = data.stacks.map(stack => stack.reduce((x, y) => x + y, 0))
+ const at = peak.indexOf(Math.max(...peak))
+
+ if ((peak[at] ?? 0) > 0) rows.push(...flow(ctx, [{ key: 'ev-zoom-peak', label: ` ⌖ zoom to the busiest bar (${peak[at]}) `, onPress: () => a.narrow(data.fromMs + at * data.stepMs, data.fromMs + (at + 1) * data.stepMs) }, ...(ui.narrowed === null ? [] : [{ key: 'ev-zoom-reset', label: ' ⤢ back out ', onPress: () => a.window(ui.window) }])], 'ev-zoom'))
+ }
+
+ if (ui.window === 'all' || ui.window === '24h') {
+ const grid = dayHour(model.shown, nowMs)
+
+ if (grid.some(day => day.some(n => n > 0))) {
+ rows.push(text(ctx, ' day × hour (local, 0h to 23h)', { dimColor: true }))
+ grid.forEach((day, i) => rows.push(text(ctx, ` ${new Date(nowMs - (6 - i) * 86_400_000).toISOString().slice(5, 10)} ${heatLine(day)}`, { color: THEME.info })))
+ }
+ }
+
+ if (ui.mutedKinds.size + ui.mutedTemplates.size > 0) rows.push(...flow(ctx, [...[...ui.mutedKinds].map(kind => ({ key: `ev-unmute-${kind}`, label: ` ✕ muted ${kind} `, onPress: a.unmute })), ...(ui.mutedTemplates.size > 0 ? [{ key: 'ev-unmute-like', label: ` ✕ ${ui.mutedTemplates.size} muted line${ui.mutedTemplates.size === 1 ? '' : 's'} `, onPress: a.unmute }] : [])], 'ev-muted'))
+
+ const saved: Btn[] = [{ key: 'ev-save', label: ` ★ save search (${act.prefs.searches.length}/${MAX_SEARCHES}) `, onPress: a.saveSearch }, { key: 'ev-rule', label: ` 🔔 alert on this (${act.prefs.rules.length}/${MAX_RULES}) `, onPress: a.addRule }, ...act.prefs.searches.map((item, i) => ({ key: `ev-search-${i}`, label: ` ${clip(item.name, 16)} `, onPress: () => a.runSearch(item.name) }))]
+
+ rows.push(...flow(ctx, saved, 'ev-saved'))
+ if (act.prefs.rules.length > 0) rows.push(...flow(ctx, act.prefs.rules.map((item, i) => ({ key: `ev-rule-${i}`, label: ` ✕ 🔔 ${clip(item.name, 16)} `, onPress: () => a.removeRule(item.name) })), 'ev-rules', 'rules '))
+ if (act.prefs.searches.length > 0) rows.push(...flow(ctx, act.prefs.searches.map((item, i) => ({ key: `ev-del-${i}`, label: ` ✕ ${clip(item.name, 12)} `, onPress: () => a.deleteSearch(item.name) })), 'ev-dels', 'forget '))
+
+ if (act.prefs.pins.length > 0) {
+ rows.push(text(ctx, ` 📌 pinned (${act.prefs.pins.length}/${MAX_PINS})`, { bold: true }))
+
+ for (const [i, pin] of act.prefs.pins.slice(-3).reverse().entries()) {
+ rows.push(row(ctx, [ctx.kit.Text({ color: LEVEL_COLOR[pin.level](), children: ` ${LEVEL_MARK[pin.level]} ${ago(pin.atMs, nowMs).padStart(8)} ` }), ctx.kit.Text({ children: clip(pin.text, Math.max(8, ctx.columns - 26)) }), ctx.kit.Button({ key: `ev-unpin-${i}`, label: '✕', plain: true, onPress: safe(() => a.unpin(pin.atMs, pin.text)) })], `ev-pin-${i}`))
+ }
+ }
+
+ if (model.rows.length === 0) {
+ rows.push(text(ctx, state.events.length === 0 && act.log.length === 0 ? 'Nothing has changed since the console loaded, and no history is kept for this project yet. Events are what changed between reads, and what this session did.' : 'no event matches this filter, window and search', { dimColor: true }))
+ }
+
+ for (const entry of visible) {
+ const isOpen = ui.open === entry.id
+
+ rows.push(eventRow(ctx, entry, ui.parsed, model.rows[ui.focus]?.id === entry.id, isOpen, nowMs))
+ if (isOpen) rows.push(...detailRows(ctx, entry, model.shown, nowMs))
+ }
+
+ if (pages > 1) rows.push(...flow(ctx, [...(page < pages - 1 ? [{ key: 'ev-older', label: 'older ▸', onPress: () => a.page(1) }] : []), ...(page > 0 ? [{ key: 'ev-newer', label: '◂ newer', onPress: () => a.page(-1) }] : []), { key: 'ev-move-down', label: ' j ', onPress: () => a.move(1), hotkey: 'j' }, { key: 'ev-move-up', label: ' k ', onPress: () => a.move(-1), hotkey: 'k' }], 'ev-pages', ` page ${page + 1}/${pages} `))
+ else rows.push(...flow(ctx, [{ key: 'ev-move-down', label: ' j ', onPress: () => a.move(1), hotkey: 'j' }, { key: 'ev-move-up', label: ' k ', onPress: () => a.move(-1), hotkey: 'k' }], 'ev-pages'))
+
+ rows.push(...flow(ctx, [{ key: 'ev-export-md', label: ' ⇩ export .md ', onPress: () => void a.exportTo('md', `events-${new Date(nowMs).toISOString().slice(0, 16).replace(/[:T]/g, '-')}.md`) }, { key: 'ev-export-jsonl', label: ' ⇩ export .jsonl ', onPress: () => void a.exportTo('jsonl', `events-${new Date(nowMs).toISOString().slice(0, 16).replace(/[:T]/g, '-')}.jsonl`) }, { key: 'ev-forget', label: ' 🗑 forget history ', onPress: a.forget }, { key: 'filter', label: ` kind: ${filter} (cycle) `, onPress: ctx.act.filter, hotkey: 'f' }], 'ev-foot'))
+
+ for (const [i, note] of notelines(storeNote(state), Math.max(20, ctx.columns - 2)).entries()) rows.push(text(ctx, ` ${note}`, { dimColor: true, ...(i === 0 ? {} : {}) }))
+
+ return col(ctx, rows, 'events')
+}
+
diff --git a/plugins/ruflo-console/hooks/views/frames.ts b/plugins/ruflo-console/hooks/views/frames.ts
index 7a3c7613e8..52602696e7 100644
--- a/plugins/ruflo-console/hooks/views/frames.ts
+++ b/plugins/ruflo-console/hooks/views/frames.ts
@@ -16,7 +16,7 @@ import type { Channels, Peers, Roster } from '../data/cli'
import { pipelinePicture, radarPicture, samplesPicture, trendPicture, gaugePicture, type Stage } from '../gfx/charts'
import { loopPicture, loopStagesOf } from '../gfx/evolve'
import { flowModelOf, flowPicture, flowRows } from '../gfx/flow'
-import { federationPicture, ganttPicture, heatmapPicture, type FedNode, type HealthRow, type Lane } from '../gfx/maps'
+import { federationPicture, heatmapPicture, type FedNode, type HealthRow, type Lane } from '../gfx/maps'
import { activityPicture, bannerPicture, bootPicture, titlePicture, curvePicture, headerPicture, palettePicture, PULSE_MS, topologyPicture, type TopoModel } from '../gfx/pictures'
import type { Grid } from '../gfx/raster'
import { PROBES, severityOf } from '../data/cli'
@@ -31,6 +31,10 @@ import { openTasks } from './select'
export const MAX_NODES = 100
export const HEALTH_CHECKS = ['installed', 'enabled', 'clone', 'mod'] as const
+import { chartOf, eventsModel } from '../events-ui'
+import { linesPicture, stackedPicture } from '../gfx/ev-charts'
+import { timelineModel } from '../timeline-ui'
+import { linesFor } from './timeline-lines'
import { watchOf } from '../watch'
/** The radar's axis words: the score's own dimension names, shortened to fit at a spoke's end. */
const AXIS: Record<string, string> = { harnessFit: 'fit', compileConfidence: 'compile', taskCoverage: 'coverage', toolSafety: 'safety', memoryUsefulness: 'memory' }
@@ -258,9 +262,16 @@ export function picturesOf(state: State, columns: number, nowMs: number, t: numb
pictures.set('evolve-loop', loopPicture(loopStagesOf(state.evolve), width, t))
break
case 'timeline': {
- const lanes = lanesOf(state, nowMs)
+ const model = timelineModel(state, nowMs, Math.max(8, width - 10))
- if (lanes.length > 0) pictures.set('gantt', ganttPicture(lanes, width, nowMs - watchOf(state).rangeMs, nowMs))
+ if (model.lanes.length > 0) pictures.set('tl-picture', linesPicture(linesFor(state, model, width), width))
+ break
+ }
+ case 'events': {
+ const events = eventsModel(state, nowMs)
+ const { data, colors } = chartOf(state, events, nowMs, width)
+
+ if (events.shown.length > 0) pictures.set('ev-chart', stackedPicture(data, colors, width, 5))
break
}
default:
diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts
index b9ef475c90..f3b4182a79 100644
--- a/plugins/ruflo-console/hooks/views/pane.ts
+++ b/plugins/ruflo-console/hooks/views/pane.ts
@@ -31,7 +31,9 @@ import { sandboxView } from './sandbox'
import { federationView } from './federation'
import { hiveView } from './hive'
import { learningView } from './learning'
-import { approvalsView, eventsView, timelineView } from './manage'
+import { eventsView } from './events'
+import { approvalsView } from './manage'
+import { timelineView } from './timeline'
import { roomView } from './room'
import { memoryView } from './memory'
import { menuView } from './menu'
diff --git a/plugins/ruflo-console/hooks/views/timeline-lines.ts b/plugins/ruflo-console/hooks/views/timeline-lines.ts
new file mode 100644
index 0000000000..a887108fa7
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/timeline-lines.ts
@@ -0,0 +1,18 @@
+/**
+ * The Timeline's page of lines (ADR-474): the lanes of one page, as cells, for a given width. The picture (views/frames.ts) and the text
+ * (views/timeline.ts) both call this, so they are the same lines.
+ */
+import { activityOf } from '../activity-live'
+import { buildLines, type Line } from '../data/timeline-lines'
+import { LANES_PAGE, timelineUi, type TlModel } from '../timeline-ui'
+import type { State } from '../state'
+
+export function linesFor(state: State, model: TlModel, columns: number): Line[] {
+ const ui = timelineUi(state)
+ const act = activityOf(state)
+ const page = Math.min(ui.page, Math.max(0, Math.ceil(model.entries.length / LANES_PAGE) - 1))
+ const entries = model.entries.slice(page * LANES_PAGE, page * LANES_PAGE + LANES_PAGE)
+ const lanes = model.entries.flatMap(entry => (entry.type === 'lane' ? [entry.lane] : []))
+
+ return buildLines(entries, act.lanes, model.problems, model.lanes, model.win, model.concurrency, columns, lanes[ui.cursor]?.lane ?? null)
+}
diff --git a/plugins/ruflo-console/hooks/views/timeline.ts b/plugins/ruflo-console/hooks/views/timeline.ts
new file mode 100644
index 0000000000..9b022c5e3d
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/timeline.ts
@@ -0,0 +1,132 @@
+/**
+ * The Timeline page (ADR-474): lanes in groups over a window you can zoom and pan, with the Events log's warn and bad events laid on
+ * them, a parallelism strip, idle gaps, a lane detail, an export and cross-links to the Events page. The picture and the text lines
+ * are built from the same list (data/timeline-lines.ts), so the text carries everything the picture does. Only one page of lanes is built.
+ */
+import type { RenderElement } from 'claude-code'
+
+import { activityOf, storeNote } from '../activity-live'
+import { LEGEND, runsOf, type Line, type Tone } from '../data/timeline-lines'
+import { clockOf, SORTS, TL_WINDOWS, type LaneView } from '../data/timeline-model'
+import { refOf } from '../data/events'
+import { levelOfEvent } from '../data/event-severity'
+import { laneRef, LANES_PAGE, timelineModel, timelineUi, type TlModel } from '../timeline-ui'
+import { linesFor } from './timeline-lines'
+import { clip, col, picture, row, rule, text, THEME, type Ctx } from './common'
+import { LEVEL_COLOR, LEVEL_MARK, chip } from './events-parts'
+import { notelines } from './events'
+import { flow, type Btn } from './wf-layout'
+
+const TONE = (tone: Tone): { color?: string; dimColor?: boolean } => (tone === 'busy' ? { color: THEME.warn } : tone === 'idle' ? { color: THEME.info, dimColor: true } : tone === 'tool' ? { color: THEME.head } : tone === 'bad' ? { color: THEME.bad } : tone === 'warn' ? { color: THEME.warn } : { dimColor: true })
+
+const dur = (ms: number): string => (ms < 60_000 ? `${Math.round(ms / 1000)}s` : ms < 3_600_000 ? `${Math.round(ms / 60_000)}m` : `${(ms / 3_600_000).toFixed(1)}h`)
+
+function textLines(ctx: Ctx, lines: readonly Line[]): RenderElement[] {
+ return lines.map((line, i) =>
+ row(
+ ctx,
+ line.kind === 'group'
+ ? [ctx.kit.Text({ bold: true, color: THEME.head, children: clip(line.label, ctx.columns) })]
+ : [ctx.kit.Text({ ...(line.isCursor === true ? { bold: true, color: THEME.head } : { dimColor: line.kind === 'axis' }), children: `${line.label} ` }), ...runsOf(line.cells).map(run => ctx.kit.Text({ ...TONE(run.tone), children: run.text }))],
+ `tl-line-${i}`,
+ ),
+ )
+}
+
+function laneDetail(ctx: Ctx, lane: LaneView, model: TlModel, nowMs: number): RenderElement[] {
+ const { ref, go } = laneRef(lane)
+ const a = ctx.act.timeline
+ const act = activityOf(ctx.state)
+ const spans = lane.spans.slice(-8)
+ const out: RenderElement[] = [text(ctx, ` ${lane.group} · ${lane.label}`, { bold: true }), text(ctx, ` busy ${lane.busyPct === null ? 'n/a' : `${lane.busyPct}%`} of ${dur(lane.observedMs)} observed · longest busy stretch ${dur(lane.longestMs)} · ${lane.calls} tool call${lane.calls === 1 ? '' : 's'}`, { dimColor: true })]
+
+ if (spans.length === 0) out.push(text(ctx, ' no busy or idle stretch was observed in this window', { dimColor: true }))
+
+ spans.forEach((span, i) => {
+ const next = spans[i + 1]
+ const gap = next === undefined ? '' : next.fromMs - span.toMs > 1000 ? ` · gap ${dur(next.fromMs - span.toMs)}` : ''
+
+ out.push(text(ctx, ` ${clockOf(span.fromMs)} ${span.busy ? '█ busy' : '▁ idle'} ${dur(span.toMs - span.fromMs)}${gap}`, { color: span.busy ? THEME.warn : THEME.info }))
+ })
+
+ if (lane.byTool.length > 0) out.push(text(ctx, ` tools: ${lane.byTool.slice(0, 6).map(([tool, n]) => `${tool} ${n}`).join(' · ')}`, { dimColor: true }))
+
+ const events = act.log.filter(event => refOf(event) === ref).slice(-10).reverse()
+
+ if (events.length > 0) out.push(text(ctx, ` last ${events.length} events:`, { dimColor: true }))
+ for (const event of events) out.push(text(ctx, ` ${LEVEL_MARK[levelOfEvent(event)]} ${clockOf(event.atMs)} ${event.text}`, { color: LEVEL_COLOR[levelOfEvent(event)]() }))
+ void nowMs
+ void model
+
+ out.push(...flow(ctx, [{ key: 'tl-lane-events', label: ' ⤳ follow on Events ', onPress: () => a.events(lane) }, { key: 'tl-lane-go', label: ` open ${go} `, onPress: () => a.go(lane) }, { key: 'tl-lane-ask', label: ' ✦ ask Claude ', onPress: () => a.ask(lane) }, { key: 'tl-lane-close', label: ' close ', onPress: () => a.open(null) }], 'tl-lane-btns'))
+
+ return out
+}
+
+export function timelineView(ctx: Ctx): RenderElement {
+ const { state, nowMs } = ctx
+ const ui = timelineUi(state)
+ const a = ctx.act.timeline
+ const act = activityOf(state)
+ const model = timelineModel(state, nowMs, Math.max(8, ctx.columns - 10))
+ const label = TL_WINDOWS.find(item => item.id === ui.window)?.label ?? ui.window
+ const rows: RenderElement[] = [rule(ctx, 'Timeline', `${label}${ui.offsetMs > 0 ? ` · ${dur(ui.offsetMs)} back` : ' · live'} · ${clockOf(model.win.fromMs, model.win.spanMs > 86_400_000)} to ${clockOf(model.win.toMs, model.win.spanMs > 86_400_000)} · ${model.total} lanes`)]
+
+ rows.push(...flow(ctx, TL_WINDOWS.map(item => chip(`tl-win-${item.id}`, item.label, ui.window === item.id, () => a.window(item.id))), 'tl-windows', 'window '))
+ rows.push(
+ ...flow(
+ ctx,
+ [
+ { key: 'tl-back', label: ' ◂ earlier ', onPress: () => a.pan(-1), hotkey: 'b' },
+ { key: 'tl-fwd', label: ' later ▸ ', onPress: () => a.pan(1), hotkey: 'n' },
+ { key: 'tl-zin', label: ' + zoom in ', onPress: () => a.zoom(-1) },
+ { key: 'tl-zout', label: ' - zoom out ', onPress: () => a.zoom(1) },
+ { key: 'tl-now', label: ' ⏺ now ', onPress: a.now },
+ { key: 'tl-start', label: ' ⏮ start ', onPress: a.start },
+ { key: 'tl-problem', label: ' ⚠ last problem ', onPress: a.problem },
+ { key: 'tl-sort', label: ` sort: ${ui.sort} `, onPress: a.sort, hotkey: 's' },
+ ],
+ 'tl-controls',
+ ),
+ )
+
+ if (model.lanes.length === 0) {
+ rows.push(text(ctx, state.snapshot === null ? 'Reading ruflo state…' : 'No lane was observed in this window. Lanes appear when a ruflo agent reports a status, Claude Code calls a tool, a workflow agent or a mission task runs, or the autopilot hands over a step.', { dimColor: true }))
+ } else {
+ const lines = linesFor(state, model, ctx.columns)
+
+ rows.push(...flow(ctx, model.entries.flatMap(entry => (entry.type === 'group' ? [{ key: `tl-group-${entry.group}`, label: ` ${entry.isOpen ? '▾' : '▸'} ${entry.group} (${entry.count}) `, onPress: () => a.toggleGroup(entry.group) }] : [])), 'tl-groups', 'groups '))
+ rows.push(ctx.pictures.has('tl-picture') ? picture(ctx, 'tl-picture', ' ') : col(ctx, textLines(ctx, lines), 'tl-text'))
+
+ const pages = Math.max(1, Math.ceil(model.entries.length / LANES_PAGE))
+ const page = Math.min(ui.page, pages - 1)
+ const cursor = model.entries.flatMap(entry => (entry.type === 'lane' ? [entry.lane] : []))[ui.cursor]
+ const nav: Btn[] = [{ key: 'tl-down', label: ' j ', onPress: () => a.move(1), hotkey: 'j' }, { key: 'tl-up', label: ' k ', onPress: () => a.move(-1), hotkey: 'k' }, ...(cursor === undefined ? [] : [{ key: 'tl-open', label: ` ▸ open ${clip(cursor.label, 18)} `, onPress: () => a.open(cursor.lane), hotkey: 'o' }]), ...(pages > 1 ? [...(page < pages - 1 ? [{ key: 'tl-next', label: 'more lanes ▸', onPress: () => a.page(1) }] : []), ...(page > 0 ? [{ key: 'tl-prev', label: '◂ back', onPress: () => a.page(-1) }] : [])] : [])]
+
+ rows.push(...flow(ctx, nav, 'tl-nav', pages > 1 ? ` page ${page + 1}/${pages} ` : ''))
+ rows.push(text(ctx, ` ${LEGEND}`, { dimColor: true }))
+
+ const conc = model.concurrency
+
+ rows.push(text(ctx, ` parallel: peak ${conc.peak}, mean ${conc.mean} lanes busy at once${conc.peakAtMs === null ? '' : ` (peak ${clockOf(conc.peakAtMs)})`}${model.busiest === null ? '' : ` · busiest minute ${clockOf(model.busiest.atMs)}: ${model.busiest.n} tool calls`}${model.problems.length === 0 ? '' : ` · ${model.problems.length} warn/bad events`}`, { color: THEME.info }))
+
+ for (const gap of model.gaps.slice(0, 3)) rows.push(text(ctx, ` idle ${dur(gap.toMs - gap.fromMs)}: ${gap.label} ${clockOf(gap.fromMs)} to ${clockOf(gap.toMs)} while others were busy`, { color: THEME.warn }))
+
+ const open = ui.open === null ? undefined : model.lanes.find(lane => lane.lane === ui.open)
+
+ if (open !== undefined) rows.push(...laneDetail(ctx, open, model, nowMs))
+ }
+
+ if (ui.said !== null) rows.push(text(ctx, ` ${ui.said}`, { dimColor: true }))
+
+ const stamp = new Date(nowMs).toISOString().slice(0, 16).replace(/[:T]/g, '-')
+
+ rows.push(...flow(ctx, [{ key: 'tl-export-md', label: ' ⇩ export .md ', onPress: () => void a.exportTo('md', `timeline-${stamp}.md`) }, { key: 'tl-export-csv', label: ' ⇩ export .csv ', onPress: () => void a.exportTo('csv', `timeline-${stamp}.csv`) }, { key: 'tl-ask', label: ' ✦ ask Claude about this window ', onPress: () => ctx.act.watch.ask(`In my ruflo console's timeline (${label}) ${model.total} lanes ran with peak parallelism ${model.concurrency.peak} and ${model.problems.length} warn/bad events. Anything worth looking at?`) }], 'tl-foot'))
+ rows.push(text(ctx, 'ruflo agents\' own tool calls are not visible to Claude Code: their lanes show status only', { dimColor: true }))
+
+ for (const note of notelines(`lanes observed since the console loaded, plus ${act.loaded.lanesBytes > 0 ? `${Math.round(act.loaded.lanesBytes / 1000)} kB of history` : 'no history yet'} · ${storeNote(state)}`, Math.max(20, ctx.columns - 2))) rows.push(text(ctx, ` ${note}`, { dimColor: true }))
+
+ return col(ctx, rows, 'timeline')
+}
+
+export { SORTS }
diff --git a/plugins/ruflo-console/hooks/watch-command.ts b/plugins/ruflo-console/hooks/watch-command.ts
new file mode 100644
index 0000000000..dcbeb6a275
--- /dev/null
+++ b/plugins/ruflo-console/hooks/watch-command.ts
@@ -0,0 +1,39 @@
+/**
+ * `/ruflo events <args>` and `/ruflo timeline <args>` (ADR-474), carried out: the filters are set (pure, in events-ui.ts and
+ * timeline-ui.ts), the export and forget verbs ask through the confirm card like every other write, and the page is brought up.
+ */
+import type { Controller } from './controller'
+import type { Intent } from './commands'
+import { applyEventsArgs } from './events-args'
+import { applyTimelineArgs } from './timeline-ui'
+import { eventsUi } from './events-ui'
+import { timelineUi } from './timeline-ui'
+import type { State } from './state'
+
+const pendingText = (state: State): string | null => (state.pending === null ? null : `Asked: ${state.pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.${state.pending.shows === undefined ? '' : `\nruns: ${state.pending.shows}`}`)
+
+export async function watchCommand(control: Controller, state: State, intent: Extract<Intent, { kind: 'events' | 'timeline' }>): Promise<{ text: string }> {
+ const isEvents = intent.kind === 'events'
+ const done = isEvents ? applyEventsArgs(state, intent.args) : applyTimelineArgs(state, intent.args)
+ const actions = control.actions
+
+ control.setView(isEvents || 'follow' in done && done.follow !== undefined ? 'events' : 'timeline')
+
+ if (isEvents && 'forget' in done && done.forget === true) actions.events.forget()
+ else if (done.export !== undefined) {
+ const target = done.export
+
+ if (isEvents) await actions.events.exportTo(target.format === 'csv' ? 'md' : target.format, target.path)
+ else await actions.timeline.exportTo(target.format === 'jsonl' ? 'md' : target.format, target.path)
+ }
+
+ control.host.invalidate()
+
+ const opened = await control.open()
+ const asked = pendingText(state)
+ const why = opened.isPlaced ? '' : ` (the pane could not be shown: ${opened.reason})`
+
+ const said = done.export === undefined ? done.text : (isEvents ? eventsUi(state).said : timelineUi(state).said) ?? done.text
+
+ return { text: `${asked ?? said}${why}` }
+}
diff --git a/plugins/ruflo-console/scripts/bench-events.mjs b/plugins/ruflo-console/scripts/bench-events.mjs
new file mode 100644
index 0000000000..73fa0b0490
--- /dev/null
+++ b/plugins/ruflo-console/scripts/bench-events.mjs
@@ -0,0 +1,177 @@
+// @ts-check
+/**
+ * ADR-474 benchmark: the Events and Timeline pages under load. Plain node, no fixtures on disk: a 2 MiB events log and a 200-lane by
+ * 24 h lane store are generated here, and every page is drawn through the REAL view into a recording kit (the engine's own layout is not
+ * in it). Median and p99 per case; `--check` exits 1 when a case misses its budget.
+ * npx -y tsx plugins/ruflo-console/scripts/bench-events.mjs [--check]
+ * Cases: load the tail of a 2 MiB log and parse it; four query shapes over a 10 000-event log (cold pipeline, then memoised); the old
+ * `eventsShown` substring filter over the same log (the BEFORE); render one Events page; render one Timeline page over 200 lanes x 24 h of
+ * spans; append 100 events (encode, queue, one batched write); append 100 lane samples.
+ */
+import { activityOf, append } from '../hooks/activity-live.ts'
+import { BATCH_MAX, flush, queueLine, resetIo } from '../hooks/activity-io.ts'
+import { decodeEvents, encodeEvent, EVENTS_CAP } from '../hooks/data/activity-store.ts'
+import { loadRows, observe } from '../hooks/data/timeline-model.ts'
+import { eventsModel, eventsUi } from '../hooks/events-ui.ts'
+import { parseQuery } from '../hooks/data/event-query.ts'
+import { newState } from '../hooks/state.ts'
+import { timelineModel } from '../hooks/timeline-ui.ts'
+import { eventsView } from '../hooks/views/events.ts'
+import { timelineView } from '../hooks/views/timeline.ts'
+import { eventsShown } from '../hooks/watch.ts'
+
+const CHECK = process.argv.includes('--check')
+const NOW = Date.now()
+const BUDGET_MS = { 'parse 2 MiB tail': 250, 'query word (cold)': 25, 'query field+negation (cold)': 25, 'query regex (cold)': 40, 'query since+phrase (cold)': 25, 'events page frame': 20, 'timeline model rebuild (200 lanes x 24h)': 60, 'timeline page frame (200 lanes x 24h)': 20, 'append 100 events (queue+write)': 20, 'append 100 lane samples': 5 }
+
+const el = (kind) => (props) => ({ kind, props })
+const kit = { Box: el('Box'), Text: el('Text'), Button: el('Button'), Input: el('Input') }
+const ctxOf = (state, columns = 100) => ({ kit, state, nowMs: NOW, columns, pictures: new Map(), act: new Proxy({}, { get: () => new Proxy(() => undefined, { get: () => () => undefined }) }) })
+
+const KINDS = ['swarm', 'claims', 'workflows', 'autopilot', 'anatole', 'tools', 'learning']
+const LINES = ['agent coder-12 spawned (coder)', 'run wf_alpha_build finished: 3 of 3 agents done', 'step s7 failed: tests red', 'Anatole blocked Bash: rule r-exfil (high)', 'ISSUE-1234 progress 40%', '+2 patterns learned']
+const mkEvents = (n) => Array.from({ length: n }, (_, i) => ({ atMs: NOW - (n - i) * 8_000, kind: KINDS[i % KINDS.length], text: `${LINES[i % LINES.length]} #${i}`, ...(i % 5 === 0 && { agentId: `agent-${i % 40}` }) }))
+
+const stats = (samples) => {
+ const sorted = [...samples].sort((a, b) => a - b)
+
+ return { median: sorted[Math.floor(sorted.length / 2)], p99: sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.99))] }
+}
+
+const results = []
+
+async function time(name, run, runs = 25) {
+ const samples = []
+
+ for (let i = 0; i < 3; i++) await run(i)
+
+ for (let i = 0; i < runs; i++) {
+ const started = performance.now()
+
+ await run(i)
+ samples.push(performance.now() - started)
+ }
+
+ const { median, p99 } = stats(samples)
+ const budget = BUDGET_MS[name]
+
+ results.push({ name, median, p99, budget })
+ console.log(`${name.padEnd(44)} median ${median.toFixed(2).padStart(8)} ms p99 ${p99.toFixed(2).padStart(8)} ms${budget === undefined ? '' : ` budget ${budget} ms ${median <= budget ? 'ok' : 'OVER'}`}`)
+}
+
+// -- a 2 MiB log
+const events = mkEvents(10_000)
+const text = events.map(e => encodeEvent(e, 's1')).join('')
+const log = text.slice(Math.max(0, text.length - 2 * 1024 * 1024))
+
+console.log(`log: ${(log.length / 1048576).toFixed(2)} MiB, ${events.length} events, cap ${EVENTS_CAP} bytes`)
+await time('parse 2 MiB tail', () => decodeEvents(log), 10)
+
+// -- queries over a 10 000 event log
+const state = newState({})
+
+state.cwd = '/work/proj'
+state.loadedAtMs = NOW - 86_400_000
+const act = activityOf(state)
+
+append(act, events)
+act.loaded.isLoaded = true
+
+const ui = eventsUi(state)
+const shapes = { 'query word (cold)': 'failed', 'query field+negation (cold)': 'kind:swarm -spawned level:bad', 'query regex (cold)': '/step s\\d+ failed/', 'query since+phrase (cold)': 'since:1h "tests red"' }
+
+for (const [name, q] of Object.entries(shapes)) {
+ await time(name, i => {
+ ui.query = q
+ ui.parsed = parseQuery(q)
+ act.version++ // a cold pipeline: the memo key changes
+ eventsModel(state, NOW + i)
+ })
+}
+
+ui.query = 'failed'
+ui.parsed = parseQuery('failed')
+const warm = []
+
+for (let i = 0; i < 25; i++) {
+ const t = performance.now()
+
+ eventsModel(state, NOW)
+ warm.push(performance.now() - t)
+}
+console.log(`${'query word (memoised)'.padEnd(44)} median ${stats(warm).median.toFixed(3).padStart(8)} ms`)
+
+// -- BEFORE: the old substring filter
+const old = newState({})
+
+old.events = events
+const lowered = 'failed'
+const before = []
+
+for (let i = 0; i < 25; i++) {
+ const t = performance.now()
+
+ eventsShown(old)
+ before.push(performance.now() - t)
+ void lowered
+}
+console.log(`${'BEFORE: old eventsShown, no query (10k)'.padEnd(44)} median ${stats(before).median.toFixed(3).padStart(8)} ms (no level, no regex, no window, no follow; capped at 300 events in the app)`)
+
+// -- one page
+ui.query = ''
+ui.parsed = parseQuery('')
+await time('events page frame', i => {
+ act.version += i === 0 ? 0 : 0
+ eventsView(ctxOf(state))
+})
+
+// -- timeline: 200 lanes x 24 h
+const tstate = newState({})
+
+tstate.cwd = '/work/proj'
+tstate.loadedAtMs = NOW - 86_400_000
+const tact = activityOf(tstate)
+const rows = []
+
+for (let lane = 0; lane < 200; lane++) {
+ for (let s = 0; s < 144; s++) rows.push({ k: 'span', lane: `ruflo:l${lane}`, group: ['ruflo', 'workflow', 'mission', 'autopilot'][lane % 4], label: `lane ${lane}`, fromMs: NOW - 86_400_000 + s * 600_000, toMs: NOW - 86_400_000 + s * 600_000 + 300_000, busy: s % 2 === 0 })
+}
+
+loadRows(tact.lanes, rows)
+append(tact, events)
+tact.loaded.isLoaded = true
+tstate.snapshot = /** @type {never} */ ({})
+const tui = (await import('../hooks/timeline-ui.ts')).timelineUi(tstate)
+
+tui.window = '24h'
+console.log(`lanes: 200, spans: ${tact.lanes.spans.length} (store cap 20000)`)
+// A changed store (a live read, at most one per 1.5 s tick): the model is rebuilt once, then every frame reuses it.
+await time('timeline model rebuild (200 lanes x 24h)', () => {
+ tact.lanes.version += 1
+ timelineModel(tstate, NOW, 60)
+}, 15)
+await time('timeline page frame (200 lanes x 24h)', () => timelineView(ctxOf(tstate, 70)), 25)
+
+// -- appends
+const memory = new Map()
+const host = { fs: { stat: async () => undefined, read: async () => '', list: async () => [] }, run: async (argv, _t, stdin = '') => (argv.includes('oflag=append') && memory.set(argv[1], (memory.get(argv[1]) ?? '') + stdin), { exitCode: 0, stdout: '', stderr: '' }) }
+
+await time('append 100 events (queue+write)', async i => {
+ resetIo()
+ for (let k = 0; k < 100; k++) queueLine('/work/proj/e.jsonl', EVENTS_CAP, encodeEvent({ atMs: NOW + k, kind: 'swarm', text: `agent a${k} failed ${i}` }))
+ await flush(host, '/work/proj', '/work/proj/e.jsonl', NOW + i * 60_000)
+})
+void BATCH_MAX
+
+const store = tact.lanes
+
+await time('append 100 lane samples', i => {
+ for (let k = 0; k < 100; k++) observe(store, 'ruflo', [{ lane: `ruflo:l${k}`, group: 'ruflo', label: `lane ${k}`, busy: (i + k) % 2 === 0 }], NOW + (i + 1) * 60_000)
+})
+
+const over = results.filter(r => r.budget !== undefined && r.median > r.budget)
+
+if (CHECK && over.length > 0) {
+ console.error(`over budget: ${over.map(r => r.name).join(', ')}`)
+ process.exit(1)
+}
diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh
index a6b0dd84ac..1ff06c98ed 100755
--- a/plugins/ruflo-console/scripts/smoke.sh
+++ b/plugins/ruflo-console/scripts/smoke.sh
@@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares ruflo-console 0.35.0"
+step "1. plugin.json declares ruflo-console 0.36.0"
grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \
- && grep -q '"version": "0.35.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
+ && grep -q '"version": "0.36.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
step "2. hooks.json names exactly one module and no classic hook commands"
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
diff --git a/plugins/ruflo-console/tests/ap-core.spec.ts b/plugins/ruflo-console/tests/ap-core.spec.ts
index 87a555cecd..6ff3ccf7f8 100644
--- a/plugins/ruflo-console/tests/ap-core.spec.ts
+++ b/plugins/ruflo-console/tests/ap-core.spec.ts
@@ -3,6 +3,11 @@
* crash-resume properties, run over a seeded random walk), the adaptation gate and the guards. Pure and fast. Run with
* npx vitest run plugins/ruflo-console/tests/ap-core.spec.ts --testTimeout=30000
*/
+import { spawnSync } from 'node:child_process'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
import { describe, expect, it } from 'vitest'
import { applyChange, clampToEnvelope, DEFAULTS, evaluate, lastHash, outcomesOf, promote, propose, reviewTrials, tunablesFrom, verifyReceipts, type Tunables } from '../hooks/data/ap-adapt'
@@ -118,7 +123,33 @@ describe('journal', () => {
})
it('appends with a fixed argv, the path as one element', () => {
- expect(appendArgv('/p/j; rm -rf /.jsonl')).toEqual(['dd', 'of=/p/j; rm -rf /.jsonl', 'oflag=append', 'conv=notrunc', 'status=none'])
+ expect(appendArgv('/p/j; rm -rf /.jsonl')).toEqual(['dd', 'of=/p/j; rm -rf /.jsonl', 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])
+ })
+
+ it.skipIf(process.platform !== 'linux')('with the real GNU dd, eight writers of whole journal batches never tear a line (ADR-466)', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ap-dd-'))
+
+ try {
+ const batch = (c: string): string => Array.from({ length: 60 }, (_, i) => `{"w":"${c}","n":${i},"pad":"${c.repeat(900)}"}\n`).join('')
+ const file = join(dir, 'journal.jsonl')
+ const argv = (appendArgv(file) as string[]).map(arg => `'${arg}'`).join(' ')
+ const script = Array.from({ length: 8 }, (_, w) => {
+ const src = join(dir, `b${w}.txt`)
+
+ writeFileSync(src, batch(w % 2 === 0 ? 'A' : 'B'))
+
+ return `( for k in 1 2 3 4 5; do cat '${src}' | ${argv}; done ) &`
+ }).join('\n')
+
+ expect(spawnSync('bash', ['-c', `${script}\nwait`]).status).toBe(0)
+
+ const lines = readFileSync(file, 'utf8').split('\n').filter(Boolean)
+
+ expect(lines).toHaveLength(8 * 5 * 60)
+ expect(lines.filter(line => !/^\{"w":"(A+|B+)","n":\d+,"pad":"(A+|B+)"\}$/.test(line) || line.length < 900)).toHaveLength(0)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
})
})
diff --git a/plugins/ruflo-console/tests/ap-live.spec.ts b/plugins/ruflo-console/tests/ap-live.spec.ts
index 51b2cdf7ce..da11a7a1d3 100644
--- a/plugins/ruflo-console/tests/ap-live.spec.ts
+++ b/plugins/ruflo-console/tests/ap-live.spec.ts
@@ -290,7 +290,7 @@ describe('writes', () => {
const dd = r.runs.find(a => a[0] === 'dd')
- expect(dd).toEqual(['dd', `of=${J}`, 'oflag=append', 'conv=notrunc', 'status=none'])
+ expect(dd).toEqual(['dd', `of=${J}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])
const linked = rig()
diff --git a/plugins/ruflo-console/tests/events-commands.spec.ts b/plugins/ruflo-console/tests/events-commands.spec.ts
new file mode 100644
index 0000000000..9481e6adca
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-commands.spec.ts
@@ -0,0 +1,76 @@
+/**
+ * `/ruflo events` and `/ruflo timeline` (ADR-474): the parse, the help text, and that the verbs set the filters and do not collide
+ * with the older commands.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { HELP, parseRuflo } from '../hooks/commands'
+import { applyEventsArgs } from '../hooks/events-args'
+import { eventsUi } from '../hooks/events-ui'
+import { applyTimelineArgs, timelineUi } from '../hooks/timeline-ui'
+import { newState } from '../hooks/state'
+
+describe('parse', () => {
+ it('bare events and timeline open their page; with words they carry them', () => {
+ expect(parseRuflo('events')).toEqual({ kind: 'open', view: 'events' })
+ expect(parseRuflo('timeline')).toEqual({ kind: 'open', view: 'timeline' })
+ expect(parseRuflo('events level bad')).toEqual({ kind: 'events', args: ['level', 'bad'] })
+ expect(parseRuflo('timeline zoom in')).toEqual({ kind: 'timeline', args: ['zoom', 'in'] })
+ expect(parseRuflo('filter swarm')).toEqual({ kind: 'filter', filter: 'swarm' })
+ expect(parseRuflo('filter workflows')).toEqual({ kind: 'filter', filter: 'workflows' })
+ })
+
+ it('every verb is in the help, and none of them is an older command word', () => {
+ for (const verb of ['events [kind|level|since:15m|', 'timeline [5m|15m|1h|6h|24h|session|zoom', 'forget', 'export <path>', 'follow <ref>']) expect(HELP).toContain(verb)
+ for (const old of ['filter', 'notices', 'quiet', 'band', 'autopilot', 'mission', 'palette']) expect(parseRuflo(old).kind).not.toBe('events')
+ })
+})
+
+describe('events args', () => {
+ it('kind, level, a query, a window, follow, clear', () => {
+ const state = newState({})
+ const ui = eventsUi(state)
+
+ expect(applyEventsArgs(state, ['swarm']).text).toBe('events: swarm')
+ expect(state.eventFilter).toBe('swarm')
+ expect(applyEventsArgs(state, ['bad']).text).toBe('events: level bad')
+ expect(ui.level).toBe('bad')
+ expect(applyEventsArgs(state, ['since:15m', 'kind:claims']).text).toContain('query since:15m kind:claims')
+ expect(ui.parsed.sinceMs).toBe(15 * 60_000)
+ expect(applyEventsArgs(state, ['since:soon']).text).toContain('but since:')
+ expect(applyEventsArgs(state, ['window', '1h']).text).toBe('events: window 1h')
+ expect(applyEventsArgs(state, ['window', 'never']).text).toContain('window takes')
+ expect(applyEventsArgs(state, ['follow', 'agent:x']).text).toContain('following agent:x')
+ expect(ui.followRef).toBe('agent:x')
+ expect(applyEventsArgs(state, ['clear']).text).toBe('events: filters cleared')
+ expect([state.eventFilter, ui.level, ui.followRef, ui.query]).toEqual(['all', 'all', null, ''])
+ })
+
+ it('export and forget are handed to the caller; a quoted query is one query', () => {
+ const state = newState({})
+
+ expect(applyEventsArgs(state, ['export', 'run.jsonl']).export).toEqual({ format: 'jsonl', path: 'run.jsonl' })
+ expect(applyEventsArgs(state, ['export', 'run.md']).export).toEqual({ format: 'md', path: 'run.md' })
+ expect(applyEventsArgs(state, ['forget']).forget).toBe(true)
+ expect(applyEventsArgs(state, ['"agent', 'coder"']).text).toContain('"agent coder"')
+ expect(eventsUi(state).parsed.terms).toHaveLength(1)
+ })
+})
+
+describe('timeline args', () => {
+ it('windows, zoom, follow, export, and a hint for anything else', () => {
+ const state = newState({})
+ const ui = timelineUi(state)
+
+ expect(applyTimelineArgs(state, ['6h']).text).toBe('timeline: 6h')
+ expect(ui.window).toBe('6h')
+ expect(applyTimelineArgs(state, ['zoom', 'in']).text).toBe('timeline: 1h')
+ expect(applyTimelineArgs(state, ['zoom', 'out']).text).toBe('timeline: 6h')
+ expect(applyTimelineArgs(state, ['zoom']).text).toContain('in or out')
+ expect(applyTimelineArgs(state, ['follow']).text).toContain('takes a ref')
+ expect(applyTimelineArgs(state, ['follow', 'run:wf_1']).follow).toBe('run:wf_1')
+ expect(eventsUi(state).followRef).toBe('run:wf_1')
+ expect(applyTimelineArgs(state, ['export', 'x.csv']).export).toEqual({ format: 'csv', path: 'x.csv' })
+ expect(applyTimelineArgs(state, ['nonsense']).text).toContain('timeline [5m')
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-export.spec.ts b/plugins/ruflo-console/tests/events-export.spec.ts
new file mode 100644
index 0000000000..4cf9d9a4db
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-export.spec.ts
@@ -0,0 +1,111 @@
+/**
+ * Exports (ADR-474): events as markdown or JSONL, lane summaries as markdown or CSV. The path is checked (traversal, a link on the way,
+ * an existing file, a bad extension), the text is masked, the size is capped, a CSV cell cannot be a formula, and the write is
+ * one fixed argv behind the confirm card.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { eventsText, exportSpecFor, lanesText, MAX_EXPORT_BYTES, resolveTarget } from '../hooks/data/event-export'
+import type { ConsoleEvent } from '../hooks/data/events'
+import { newLaneStore, lanesIn, concurrency, loadRows } from '../hooks/data/timeline-model'
+import { hostOn, newDisk } from './fixtures/activity-fs'
+
+const T = Date.UTC(2026, 9, 7, 12)
+const CWD = '/work/proj'
+const ev = (text: string, atS = 0): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000 })
+
+describe('the target path', () => {
+ it('a bare name goes under the exports folder; a relative path under the project', () => {
+ expect(resolveTarget('run.md', CWD, ['md'])).toEqual({ ok: true, path: `${CWD}/.claude-flow/console/exports/run.md` })
+ expect(resolveTarget('docs/run.jsonl', CWD, ['md', 'jsonl'])).toEqual({ ok: true, path: `${CWD}/docs/run.jsonl` })
+ })
+
+ it.each([
+ ['../escape.md', 'with ..'],
+ ['/etc/passwd.md', 'outside'],
+ ['/work/other/x.md', 'outside'],
+ ['~/x.md', 'expanded'],
+ ['a\\b.md', 'backslash'],
+ ['x.txt', 'end in'],
+ ['x.csv', 'can be'],
+ ['', 'give a file'],
+ ['bad\nname.md', 'control'],
+ ['a'.repeat(400) + '.md', '300'],
+ ])('refuses %j', (input, why) => {
+ const out = resolveTarget(input, CWD, ['md', 'jsonl'])
+
+ expect(out.ok).toBe(false)
+ expect(out.ok ? '' : out.why).toContain(why)
+ })
+
+ it('refuses an existing file, and a link in the way, before asking', async () => {
+ const disk = newDisk({ [`${CWD}/taken.md`]: 'x' })
+
+ expect(await exportSpecFor(hostOn(disk).fs, CWD, 'taken.md', 'x', 'x', ['md'])).toMatchObject({ ok: true })
+
+ const placed = await exportSpecFor(hostOn(disk).fs, CWD, `${CWD}/taken.md`, 'x', 'x', ['md'])
+
+ expect(placed.ok).toBe(false)
+ expect(placed.ok ? '' : placed.why).toContain('already exists')
+
+ disk.dirs.add(`${CWD}/.claude-flow`)
+ disk.links.add(`${CWD}/.claude-flow`)
+
+ const linked = await exportSpecFor(hostOn(disk).fs, CWD, 'new.md', 'x', 'x', ['md'])
+
+ expect(linked.ok).toBe(false)
+ expect(linked.ok ? '' : linked.why).toContain('link')
+ })
+
+ it('the spec is a fixed argv that fails rather than overwrite, with the text on stdin', async () => {
+ const made = await exportSpecFor(hostOn(newDisk()).fs, CWD, 'out.md', 'hello', '3 events', ['md'])
+
+ expect(made.ok).toBe(true)
+ if (made.ok) {
+ expect(made.spec.argv?.[0]).toBe('install')
+ expect(made.spec.stdin).toBe('hello')
+ expect(made.spec.declared).toBe('write')
+ }
+
+ const withDir = newDisk()
+
+ withDir.dirs.add(`${CWD}/.claude-flow/console/exports`)
+
+ const direct = await exportSpecFor(hostOn(withDir).fs, CWD, 'out.md', 'hello', 'x', ['md'])
+
+ if (direct.ok) expect(direct.spec.argv).toContain('conv=excl')
+ })
+})
+
+describe('the text', () => {
+ it('masks secrets and paths in markdown and JSONL, and keeps the newest 2000', () => {
+ const md = eventsText([ev('token=abcdef123456 at /home/bob/x')], 'md', 'q', T)
+ const jsonl = eventsText([ev('Bearer abcdefghijklmnopqrstu failed')], 'jsonl', 'q', T)
+
+ expect(md).not.toContain('abcdef123456')
+ expect(md).not.toContain('bob')
+ expect(jsonl).not.toContain('abcdefghijklmnopqrstu')
+ expect(JSON.parse(jsonl.trim())).toMatchObject({ v: 1, level: 'bad' })
+ expect(eventsText(Array.from({ length: 2500 }, (_, i) => ev(`e${i}`, i)), 'jsonl', 'q', T).trim().split('\n')).toHaveLength(2000)
+ })
+
+ it('a pipe in an event cannot break the markdown table, and the size is capped', () => {
+ expect(eventsText([ev('a | b')], 'md', 'q', T)).toContain('a / b')
+ expect(new TextEncoder().encode(eventsText(Array.from({ length: 2000 }, (_, i) => ev('x '.repeat(100) + i, i)), 'md', 'q', T)).length).toBeLessThanOrEqual(MAX_EXPORT_BYTES)
+ })
+
+ it('lane summaries: markdown with the concurrency figures, CSV with formulas defused', () => {
+ const store = newLaneStore()
+
+ loadRows(store, [{ k: 'span', lane: 'ruflo:1', group: 'ruflo', label: '=HYPERLINK("x")', fromMs: T, toMs: T + 60_000, busy: true }])
+
+ const win = { fromMs: T - 60_000, toMs: T + 120_000 }
+ const lanes = lanesIn(store, win, T + 120_000)
+ const data = { lanes, concurrency: concurrency(lanes, win, store, 12), fromMs: win.fromMs, toMs: win.toMs, busiest: null }
+ const csv = lanesText(data, 'csv', T)
+
+ expect(csv.split('\n')[0]).toContain('busy_pct')
+ expect(csv).toContain("'=HYPERLINK")
+ expect(lanesText(data, 'md', T)).toContain('peak 1')
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-group.spec.ts b/plugins/ruflo-console/tests/events-group.spec.ts
new file mode 100644
index 0000000000..142ab65089
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-group.spec.ts
@@ -0,0 +1,96 @@
+/**
+ * Grouping and correlation (ADR-474): bursts collapse by kind and template inside a gap, follow keeps a ref and what happened within
+ * 30 s of it, neighbours are five either side, and the chart numbers (windows, bars, heat strip) are exact.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { collapse, follow, neighbours, templateOf } from '../hooks/data/event-group'
+import { bars, barsLine, bucketMs, dayHour, heatLine, levelKey, narrow, windowStart } from '../hooks/data/event-stats'
+import { refOf, type ConsoleEvent } from '../hooks/data/events'
+
+const T = Date.UTC(2026, 9, 7, 12)
+const ev = (text: string, atS: number, extra: Partial<ConsoleEvent> = {}): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000, ...extra })
+
+describe('collapse', () => {
+ it('folds a burst of one template into one row with every member, newest shown', () => {
+ const rows = collapse([ev('agent a1 progress 10%', 0), ev('agent a1 progress 20%', 5), ev('agent a1 progress 30%', 9), ev('swarm paused', 10)])
+
+ expect(rows).toHaveLength(2)
+ expect(rows[0]?.members).toHaveLength(3)
+ expect(rows[0]?.event.text).toBe('agent a1 progress 30%')
+ })
+
+ it('does not fold across a gap longer than the burst gap, across kinds, or across agents', () => {
+ expect(collapse([ev('x 1', 0), ev('x 2', 31)])).toHaveLength(2)
+ expect(collapse([ev('x 1', 0), { ...ev('x 2', 1), kind: 'claims' }])).toHaveLength(2)
+ expect(collapse([ev('x 1', 0, { agentId: 'a' }), ev('x 2', 1, { agentId: 'b' })])).toHaveLength(2)
+ expect(collapse([ev('x 1', 0), ev('x 2', 30)])).toHaveLength(1)
+ })
+
+ it('templates drop numbers, hex ids and quoted names', () => {
+ expect(templateOf('run "alpha" 3 of 10 abcdef12')).toBe(templateOf('run "beta" 4 of 99 12345678'))
+ })
+})
+
+describe('follow and neighbours', () => {
+ const events = [ev('a', 0, { agentId: 't1' }), ev('b', 10), ev('c', 100), ev('d', 125, { agentId: 't1' }), ev('e', 140), ev('f', 400)]
+
+ it('keeps the ref events and everything within 30 s of them, nothing else', () => {
+ const out = follow(events, 'agent:t1')
+
+ expect(out.own).toBe(2)
+ expect(out.events.map(e => e.text)).toEqual(['a', 'b', 'c', 'd', 'e'])
+ expect(follow(events, 'agent:nobody')).toEqual({ own: 0, events: [] })
+ })
+
+ it('derives a ref from the agent, or from the first id of a claims or missions line', () => {
+ expect(refOf(ev('x', 0, { agentId: 'z' }))).toBe('agent:z')
+ expect(refOf({ ...ev('ISSUE-7 claimed by coder', 0), kind: 'claims' })).toBe('claim:ISSUE-7')
+ expect(refOf({ ...ev('task t-9 created: x', 0), kind: 'claims' })).toBe('task:t-9')
+ expect(refOf({ ...ev('mission m-3 (active): go', 0), kind: 'missions' })).toBe('mission:m-3')
+ expect(refOf(ev('plain', 0))).toBeUndefined()
+ })
+
+ it('five before and five after, clipped at the ends', () => {
+ const many = Array.from({ length: 20 }, (_, i) => ev(`e${i}`, i))
+
+ expect(neighbours(many, 10).before.map(e => e.text)).toEqual(['e5', 'e6', 'e7', 'e8', 'e9'])
+ expect(neighbours(many, 10).after.map(e => e.text)).toEqual(['e11', 'e12', 'e13', 'e14', 'e15'])
+ expect(neighbours(many, 0).before).toEqual([])
+ expect(neighbours(many, 99)).toEqual({ before: [], after: [] })
+ })
+})
+
+describe('chart numbers', () => {
+ it('picks a bar size by span, and a window start by id', () => {
+ expect(bucketMs(15 * 60_000)).toBe(60_000)
+ expect(bucketMs(3 * 3_600_000)).toBe(600_000)
+ expect(bucketMs(3 * 86_400_000)).toBe(3_600_000)
+ expect(windowStart('1h', T, T - 5)).toBe(T - 3_600_000)
+ expect(windowStart('session', T, T - 5)).toBe(T - 5)
+ expect(windowStart('all', T, T - 5)).toBeNull()
+ })
+
+ it('stacks by kind and by level, and counts only what is inside the span', () => {
+ const list = [ev('x failed', -30), { ...ev('ok done', -30), kind: 'claims' as const }, ev('old', -3000)]
+ const byKind = bars(list, ['swarm', 'claims'], e => e.kind, 15 * 60_000, T + 1000)
+ const byLevel = bars(list, ['bad', 'ok'], levelKey, 15 * 60_000, T + 1000)
+
+ expect(byKind.stacks.reduce((n, s) => n + s.reduce((a, b) => a + b, 0), 0)).toBe(2)
+ expect(byLevel.stacks.flat().reduce((a, b) => a + b, 0)).toBe(2)
+ expect(barsLine(byKind)).toHaveLength(byKind.stacks.length)
+ expect(narrow(100, 10, 3)).toEqual({ fromMs: 130, toMs: 140 })
+ })
+
+ it('a day by hour strip puts an event in its local day and hour', () => {
+ const at = new Date(T)
+
+ at.setHours(9, 30, 0, 0)
+
+ const grid = dayHour([{ kind: 'swarm', text: 'x', atMs: at.getTime() }], T)
+
+ expect(grid).toHaveLength(7)
+ expect(grid[6]?.[9]).toBe(1)
+ expect(heatLine([0, 1, 4])).toHaveLength(3)
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-mutants.spec.ts b/plugins/ruflo-console/tests/events-mutants.spec.ts
new file mode 100644
index 0000000000..749b9bf293
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-mutants.spec.ts
@@ -0,0 +1,182 @@
+/**
+ * Boundaries the first mutation pass of the ADR-474 review found unguarded: each test below fails when the number or comparison it
+ * names is changed. (`secret` in the KEYED mask is covered twice, by maskSecrets as well, so that one mutation is equivalent.)
+ */
+import { describe, expect, it } from 'vitest'
+
+import { activityOf, tick } from '../hooks/activity-live'
+import { resetIo } from '../hooks/activity-io'
+import { keepNewestHalf } from '../hooks/data/activity-store'
+import { lanesText } from '../hooks/data/event-export'
+import { maskLine } from '../hooks/data/event-mask'
+import { durationOf, matches, parseQuery } from '../hooks/data/event-query'
+import { evaluateRules } from '../hooks/data/event-rules'
+import { bars } from '../hooks/data/event-stats'
+import type { ConsoleEvent } from '../hooks/data/events'
+import { cellsOf, idleGaps, newLaneStore, zoomed, type LaneView } from '../hooks/data/timeline-model'
+import { eventsModel, eventsUi } from '../hooks/events-ui'
+import type { Host } from '../hooks/host'
+import { newState } from '../hooks/state'
+import { hostOn, newDisk } from './fixtures/activity-fs'
+import { rig } from './fixtures/ev-rig'
+
+const T = Date.UTC(2026, 9, 7, 12)
+const ev = (text: string, atS = 0): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000 })
+const lane = (id: string, spans: { fromMs: number; toMs: number; busy: boolean }[], tickMins: number[] = []): LaneView => ({ lane: id, group: 'ruflo', label: id, calls: 0, byTool: [], busyMs: 0, observedMs: 0, busyPct: null, longestMs: 0, lastAtMs: 0, tickMins, spans: spans.map(span => ({ lane: id, group: 'ruflo' as const, label: id, ...span })) })
+
+describe('query', () => {
+ it('a regex sees only the first 200 characters of a line; since: reaches 30 days and no further', () => {
+ expect(matches(ev(`${'a'.repeat(150)}x`), parseQuery('/x/'), T)).toBe(true)
+ expect(matches(ev(`${'a'.repeat(300)}x`), parseQuery('/x/'), T)).toBe(false)
+ expect(durationOf('30d')).toBe(30 * 86_400_000)
+ expect(durationOf('31d')).toBeNull()
+ })
+
+ it('a rule whose query has a problem never fires, even when it also has a term', () => {
+ expect(evaluateRules([{ name: 'r', q: 'failed since:soon' }], [ev('step failed')], T)).toEqual([])
+ expect(evaluateRules([{ name: 'r', q: 'failed' }], [ev('step failed')], T)).toHaveLength(1)
+ })
+})
+
+describe('timeline arithmetic', () => {
+ it('an idle stretch of 5 minutes next to a busy lane is a gap, 4 minutes is not', () => {
+ const win = { fromMs: 0, toMs: 20 * 60_000 }
+ const busy = lane('busy', [{ fromMs: 0, toMs: 20 * 60_000, busy: true }])
+ const idle = lane('idle', [{ fromMs: 0, toMs: 4 * 60_000, busy: false }, { fromMs: 4 * 60_000, toMs: 6 * 60_000, busy: true }, { fromMs: 6 * 60_000, toMs: 11 * 60_000, busy: false }, { fromMs: 11 * 60_000, toMs: 20 * 60_000, busy: true }])
+ const gaps = idleGaps([busy, idle], win, newLaneStore())
+
+ expect(gaps).toHaveLength(1)
+ expect(gaps[0]).toMatchObject({ lane: 'idle', fromMs: 6 * 60_000, toMs: 11 * 60_000 })
+ })
+
+ it('a minute of tool calls marks the bar that holds the middle of the minute', () => {
+ const win = { fromMs: 0, toMs: 400_000 }
+ const cells = cellsOf(lane('c', [], [1]), win, 10)
+
+ expect(cells[2]).toBe(3)
+ expect(cells[1]).toBe(0)
+ })
+
+ it('zoom steps one window out or in, from a session too', () => {
+ expect(zoomed('15m', 1)).toBe('1h')
+ expect(zoomed('15m', -1)).toBe('5m')
+ expect(zoomed('session', 1)).toBe('1h')
+ expect(zoomed('session', -1)).toBe('5m')
+ expect(zoomed('24h', 1)).toBe('24h')
+ expect(zoomed('5m', -1)).toBe('5m')
+ })
+
+ it('chart bars are a minute wide up to an hour', () => {
+ expect(bars([], ['k'], () => 'k', 3_300_000, T, 100).stepMs).toBe(60_000)
+ expect(bars([], ['k'], () => 'k', 3_700_000, T, 100).stepMs).toBe(600_000)
+ })
+})
+
+describe('events window', () => {
+ it('a narrowed span is half open: its start is in, its end is out', () => {
+ const w = rig(100, { events: 0 })
+
+ w.act.log.length = 0
+ activityOf(w.state).log.push({ atMs: T, kind: 'swarm', text: 'at start' }, { atMs: T + 60_000, kind: 'swarm', text: 'at end' })
+ activityOf(w.state).version++
+ eventsUi(w.state).narrowed = { fromMs: T, toMs: T + 60_000 }
+ expect(eventsModel(w.state, T + 120_000).shown.map(item => item.text)).toEqual(['at start'])
+ })
+})
+
+describe('writing', () => {
+ it('two changes of the saved searches less than 2 s apart are one write; the third waits its turn', async () => {
+ resetIo()
+
+ const disk = newDisk()
+ const state = newState({})
+
+ state.cwd = '/work/proj'
+
+ const host = { ...hostOn(disk), every: () => ({ cancel: () => undefined }), invalidate: () => undefined } as unknown as Host
+ const file = '/work/proj/.claude-flow/console/events-prefs.json'
+ const act = activityOf(state)
+ const change = (name: string): void => {
+ act.prefs.searches.push({ name, q: 'failed' })
+ act.isPrefsDirty = true
+ }
+
+ await tick(state, host, T)
+ change('one')
+ await tick(state, host, T + 5000)
+ expect(disk.files.get(file)).toContain('one')
+ change('two')
+ await tick(state, host, T + 6000)
+ expect(disk.files.get(file)).not.toContain('two')
+ await tick(state, host, T + 7100)
+ expect(disk.files.get(file)).toContain('two')
+ })
+
+ it('past its cap a log keeps its newest half, from a line start', () => {
+ const text = Array.from({ length: 30 }, () => `${'x'.repeat(9)}\n`).join('')
+
+ expect(keepNewestHalf(text, 100).split('\n').filter(Boolean)).toHaveLength(4)
+ expect(keepNewestHalf('short\n', 100)).toBe('short\n')
+ })
+})
+
+describe('washing and export', () => {
+ it('a /Users path loses its user name like /home does', () => {
+ expect(maskLine('/Users/bob/projects/x')).toBe('~/projects/x')
+ expect(maskLine('/home/bob/projects/x')).toBe('~/projects/x')
+ })
+
+ it('a lane name that starts with = + - or @ is defused in the CSV', () => {
+ const base = { lanes: ['=SUM(A1)', '+1', '-2', '@x'].map(label => ({ ...lane(label, []), label })), concurrency: { counts: [], stepMs: 0, peak: 0, mean: 0, peakAtMs: null }, fromMs: 0, toMs: 1, busiest: null }
+ const csv = lanesText(base, 'csv', T)
+
+ for (const bad of ["'=SUM", "'+1", "'-2", "'@x"]) expect(csv).toContain(bad)
+ })
+})
+
+describe('found by the review of what the pages promise', () => {
+ it('permission denies keep arriving after the console has dropped its oldest (it keeps only 20): 25 denies in a row are 25 events', async () => {
+ const { denyEvents, newMemo } = await import('../hooks/data/event-sources')
+ const memo = newMemo()
+ const kept: { tool: string; reason: string; atMs: number }[] = []
+ let seen = 0
+
+ denyEvents(memo, kept)
+
+ for (let i = 0; i < 25; i++) {
+ kept.push({ tool: `Tool${i}`, reason: 'policy', atMs: T + i * 1000 })
+ if (kept.length > 20) kept.shift()
+ seen += denyEvents(memo, kept).length
+ }
+
+ expect(seen).toBe(25)
+ })
+
+ it('at either end of the lanes the j and k buttons say so', async () => {
+ const { timelineUi } = await import('../hooks/timeline-ui')
+ const w = rig(100)
+
+ w.actions.timeline.move(-1)
+ expect(timelineUi(w.state).said).toBe('already on the first lane')
+ for (let i = 0; i < 40; i++) w.actions.timeline.move(1)
+ w.actions.timeline.move(1)
+ expect(timelineUi(w.state).said).toBe('already on the last lane')
+ })
+
+ it('a slow regex says how many events were not searched, on the page', async () => {
+ const { vi } = await import('vitest')
+ const { eventsView } = await import('../hooks/views/events')
+ const { words } = await import('./fixtures/wf-drill-world')
+ const w = rig(100, { events: 400 })
+ let clock = 0
+ const spy = vi.spyOn(performance, 'now').mockImplementation(() => (clock += 1000))
+
+ try {
+ eventsUi(w.state).parsed = parseQuery('/agent.*run/')
+ expect(eventsModel(w.state, T).skipped).toBeGreaterThan(300)
+ expect(words(eventsView(w.ctx))).toContain('is slow')
+ } finally {
+ spy.mockRestore()
+ }
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-persist.spec.ts b/plugins/ruflo-console/tests/events-persist.spec.ts
new file mode 100644
index 0000000000..fb072af22a
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-persist.spec.ts
@@ -0,0 +1,226 @@
+/**
+ * Persistence and the live pass (ADR-474): batching, the append path, rotation, a missing folder, a failing disk, a link in the way,
+ * two consoles on one file, history loaded on open (corrupt lines, a cut line, schema skew), and the option that turns writing off.
+ */
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { activityOf, loadActivity, pathsOf, tick } from '../hooks/activity-live'
+import { BATCH_MAX, flush, pendingOf, queueLine, resetIo, PENDING_MAX } from '../hooks/activity-io'
+import { encodeEvent, EVENTS_CAP, EVENTS_FILE } from '../hooks/data/activity-store'
+import type { ConsoleEvent } from '../hooks/data/events'
+import type { Host } from '../hooks/host'
+import { newState } from '../hooks/state'
+import { hostOn, newDisk, type Disk } from './fixtures/activity-fs'
+
+const T = Date.UTC(2026, 9, 7, 12)
+const CWD = '/work/proj'
+const FILE = `${CWD}/${EVENTS_FILE}`
+const ev = (text: string, atS = 0, extra: Partial<ConsoleEvent> = {}): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000, ...extra })
+
+function consoleOn(disk: Disk, options: Record<string, string | number | boolean> = {}) {
+ const state = newState(options)
+
+ state.cwd = CWD
+
+ const host = { ...hostOn(disk), every: () => ({ cancel: () => undefined }), invalidate: () => undefined } as unknown as Host
+
+ return { state, host }
+}
+
+beforeEach(() => resetIo())
+
+describe('the write path', () => {
+ it('batches: a hundred queued lines are one append, not a hundred', async () => {
+ const disk = newDisk()
+ const host = hostOn(disk)
+
+ for (let i = 0; i < 100; i++) queueLine(FILE, EVENTS_CAP, encodeEvent(ev(`e${i}`, i)))
+ await flush(host, CWD, FILE, T)
+
+ expect(disk.runs.filter(argv => argv.includes('oflag=append'))).toHaveLength(1)
+ expect(disk.files.get(FILE)?.split('\n').filter(Boolean)).toHaveLength(100)
+ expect(pendingOf(FILE)).toBe(0)
+ })
+
+ it('makes the missing folder once, and appends through the journal fixed dd argv', async () => {
+ const disk = newDisk()
+ const host = hostOn(disk)
+
+ queueLine(FILE, EVENTS_CAP, encodeEvent(ev('a')))
+ await flush(host, CWD, FILE, T)
+ queueLine(FILE, EVENTS_CAP, encodeEvent(ev('b')))
+ await flush(host, CWD, FILE, T + 1)
+
+ expect(disk.runs.filter(argv => argv[0] === 'mkdir')).toHaveLength(1)
+ expect(disk.runs.find(argv => argv.includes('oflag=append'))).toEqual(['dd', `of=${FILE}`, 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])
+ })
+
+ it('writes a batch no bigger than the batch cap and the rest on the next pass', async () => {
+ const disk = newDisk()
+ const line = encodeEvent(ev('x'.repeat(100)))
+ const n = Math.ceil((BATCH_MAX * 2) / line.length)
+
+ for (let i = 0; i < n; i++) queueLine(FILE, EVENTS_CAP, line)
+ await flush(hostOn(disk), CWD, FILE, T)
+
+ expect(disk.files.get(FILE)!.length).toBeLessThanOrEqual(BATCH_MAX)
+ expect(pendingOf(FILE)).toBeGreaterThan(0)
+ })
+
+ it('a failing disk is remembered, not thrown: the lines stay queued and are retried after the wait', async () => {
+ const disk = newDisk()
+
+ disk.failAppend = true
+ queueLine(FILE, EVENTS_CAP, encodeEvent(ev('a')))
+ await expect(flush(hostOn(disk), CWD, FILE, T)).resolves.toBeUndefined()
+ expect(pendingOf(FILE)).toBe(1)
+
+ await flush(hostOn(disk), CWD, FILE, T + 1000)
+ expect(disk.runs.filter(argv => argv.includes('oflag=append'))).toHaveLength(1)
+
+ disk.failAppend = false
+ await flush(hostOn(disk), CWD, FILE, T + 60_000)
+ expect(pendingOf(FILE)).toBe(0)
+ expect(disk.files.get(FILE)).toContain('"text":"a"')
+ })
+
+ it('never writes through a link, and the queue is bounded', async () => {
+ const disk = newDisk({ [FILE]: '' })
+
+ disk.dirs.add(`${CWD}/.claude-flow`).add(`${CWD}/.claude-flow/console`)
+ disk.links.add(FILE)
+ queueLine(FILE, EVENTS_CAP, encodeEvent(ev('a')))
+ await flush(hostOn(disk), CWD, FILE, T)
+ expect(disk.runs.some(argv => argv.includes('oflag=append'))).toBe(false)
+
+ for (let i = 0; i < PENDING_MAX + 50; i++) queueLine(FILE, EVENTS_CAP, 'x\n')
+ expect(pendingOf(FILE)).toBe(PENDING_MAX)
+ })
+
+ it('past its cap the file is cut to its newest half and still holds whole lines', async () => {
+ const disk = newDisk()
+ const cap = 4000
+
+ for (let i = 0; i < 200; i++) queueLine(FILE, cap, encodeEvent(ev(`event ${i}`, i)))
+
+ for (let pass = 0; pass < 30 && pendingOf(FILE) > 0; pass++) await flush(hostOn(disk), CWD, FILE, T + pass)
+
+ const text = disk.files.get(FILE) as string
+
+ expect(text.length).toBeLessThan(cap)
+ expect(text.split('\n').filter(Boolean).every(line => line.startsWith('{') && line.endsWith('}'))).toBe(true)
+ expect(text).toContain('event 199')
+ expect(text).not.toContain('"event 0"')
+ })
+
+ it('two consoles appending to one file never cut a batch in two', async () => {
+ const disk = newDisk()
+ const a = hostOn(disk)
+
+ for (let i = 0; i < 20; i++) {
+ queueLine(FILE, EVENTS_CAP, encodeEvent(ev(`from a ${i}`, i), 'a'))
+ await flush(a, CWD, FILE, T + i * 10_000)
+ disk.files.set(FILE, (disk.files.get(FILE) ?? '') + encodeEvent(ev(`from b ${i}`, i), 'b'))
+ }
+
+ const lines = (disk.files.get(FILE) as string).split('\n').filter(Boolean)
+
+ expect(lines).toHaveLength(40)
+ expect(lines.every(line => JSON.parse(line).v === 1)).toBe(true)
+ })
+})
+
+describe('the live pass', () => {
+ it('loads history on open: the tail, with corrupt lines counted and a cut line dropped', async () => {
+ const good = encodeEvent(ev('before restart', -3600))
+ const disk = newDisk({ [FILE]: `${good.slice(10)}${good}garbage\n${encodeEvent(ev('second', -60))}{"v":1,"t":5` })
+ const { state, host } = consoleOn(disk)
+
+ await loadActivity(state, host)
+
+ const act = activityOf(state)
+
+ expect(act.log.map(e => e.text)).toEqual(['before restart', 'second'])
+ expect(act.loaded).toMatchObject({ isLoaded: true, events: 2 })
+ expect(act.loaded.bad).toBeGreaterThanOrEqual(2)
+ })
+
+ it('a missing folder is an empty history, not an error', async () => {
+ const { state, host } = consoleOn(newDisk())
+
+ await loadActivity(state, host)
+ expect(activityOf(state).loaded).toMatchObject({ isLoaded: true, events: 0, problem: null })
+ })
+
+ it('takes in new events once, writes them masked, and skips the write when eventsPersist is off', async () => {
+ const disk = newDisk()
+ const on = consoleOn(disk)
+ const off = consoleOn(newDisk(), { eventsPersist: false })
+
+ for (const { state, host } of [on, off]) {
+ await tick(state, host, T)
+ state.events.push(ev('agent x failed with token=abcdef123456', 5))
+ await tick(state, host, T + 10_000)
+ await tick(state, host, T + 20_000)
+ }
+
+ expect(activityOf(on.state).log).toHaveLength(1)
+ expect(disk.files.get(FILE)).toContain('"level":"bad"')
+ expect(disk.files.get(FILE)).not.toContain('abcdef123456')
+ expect(disk.files.get(FILE)?.split('\n').filter(Boolean)).toHaveLength(1)
+ expect(activityOf(off.state).log).toHaveLength(1)
+ expect(pathsOf(CWD).events).toBe(FILE)
+ })
+
+ it('history from a previous run is on the page but never re-announced to alert rules', async () => {
+ const disk = newDisk({ [FILE]: encodeEvent(ev('old failure failed', -100)) })
+ const { state, host } = consoleOn(disk)
+
+ await tick(state, host, T)
+ activityOf(state).prefs.rules = [{ name: 'fails', q: 'failed' }]
+ await tick(state, host, T + 2000)
+ expect(state.notices).toHaveLength(0)
+
+ state.events.push(ev('new failure failed', 5))
+ await tick(state, host, T + 5000)
+ expect(state.notices.map(n => n.key)).toEqual(['events-rule:fails'])
+ })
+})
+
+describe('lanes from the state the console holds', () => {
+ it('samples ruflo agents, aggregates tool calls per minute, and takes workflow agents and mission tasks as intervals once; lanes persist', async () => {
+ const disk = newDisk()
+ const { state, host } = consoleOn(disk)
+
+ state.snapshot = { agents: [{ id: 'a1', type: 'coder', status: 'busy' }, { id: 'a2', type: 'tester', status: 'idle' }], tasks: [{ id: 't1', description: 'build it', status: 'completed', assignedTo: [], type: 'x', startedAtMs: T - 120_000, completedAtMs: T - 60_000 }], claims: [] } as never
+ state.toolsByAgent.set('main', [{ atMs: T - 90_000, tool: 'Bash' }, { atMs: T - 80_000, tool: 'Bash' }, { atMs: T - 70_000, tool: 'Read' }])
+ state.wf.read = { runs: [{ id: 'wf_1', name: 'build', kind: 'workflow', state: 'completed', total: 1, done: 1, failed: 0, running: 0, idle: 0, hasRecord: true, totalTokens: null, isTokensPartial: false, phases: [{ title: 'p', done: 1, total: 1, running: 0, failed: 0, agents: [{ id: 'ag1', label: 'writer', phase: 'p', state: 'done', hasWorktree: false, startedMs: T - 300_000, elapsedMs: 120_000 }] }] }], root: '/x', capBytes: 1, skipped: 0, more: 0 } as never
+
+ await tick(state, host, T)
+ await tick(state, host, T + 2000)
+
+ const lanes = activityOf(state).lanes
+
+ expect(lanes.open.get('ruflo:a1')?.busy).toBe(true)
+ expect(lanes.open.get('ruflo:a2')?.busy).toBe(false)
+ expect(lanes.spans.map(span => span.lane).sort()).toEqual(['mission:t1', 'workflow:wf_1/ag1'])
+ expect([...lanes.ticks.values()].reduce((n, tick) => n + tick.n, 0)).toBe(3)
+
+ // A second pass shows the same things and adds nothing.
+ await tick(state, host, T + 4000)
+ expect(lanes.spans).toHaveLength(2)
+
+ // An agent that changes status closes its span, and the closed spans and finished minutes are written masked to lanes.jsonl.
+ ;(state.snapshot as unknown as { agents: { status: string }[] }).agents[0]!.status = 'idle'
+ await tick(state, host, T + 6000)
+ await tick(state, host, T + 12_000)
+
+ const written = disk.files.get(`${CWD}/.claude-flow/console/lanes.jsonl`) ?? ''
+
+ expect(written.split('\n').filter(Boolean).every(line => JSON.parse(line).v === 1)).toBe(true)
+ expect(written.split('\n').filter(Boolean).length).toBeGreaterThanOrEqual(4)
+ expect(written).toContain('"l":"ruflo:a1"')
+ expect(written).toContain('"l":"workflow:wf_1/ag1"')
+ expect(written).toContain('"tools":{"Bash":2')
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-query.spec.ts b/plugins/ruflo-console/tests/events-query.spec.ts
new file mode 100644
index 0000000000..166aec7e74
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-query.spec.ts
@@ -0,0 +1,136 @@
+/**
+ * The Events query language (ADR-474): the parser, the evaluator, highlights, and the safety of /regex/ terms (size cap, no nested
+ * quantifiers, no back-references, bounded text), plus a property test that no query text ever throws.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { durationOf, highlights, matches, parseQuery, regexProblem, REGEX_MAX } from '../hooks/data/event-query'
+import type { ConsoleEvent } from '../hooks/data/events'
+
+const NOW = Date.UTC(2026, 9, 7, 12)
+const ev = (kind: ConsoleEvent['kind'], text: string, extra: Partial<ConsoleEvent> = {}, agoMs = 0): ConsoleEvent => ({ kind, text, atMs: NOW - agoMs, ...extra })
+const run = (q: string, e: ConsoleEvent): boolean => matches(e, parseQuery(q), NOW)
+
+describe('parseQuery', () => {
+ it('free words are ANDed, a quoted phrase keeps its spaces, a leading minus negates', () => {
+ const e = ev('swarm', 'agent coder spawned (coder)')
+
+ expect(run('agent coder', e)).toBe(true)
+ expect(run('agent reviewer', e)).toBe(false)
+ expect(run('"agent coder"', e)).toBe(true)
+ expect(run('"coder agent"', e)).toBe(false)
+ expect(run('agent -spawned', e)).toBe(false)
+ expect(run('agent -failed', e)).toBe(true)
+ })
+
+ it('field filters: kind, level, agent, src, ref, with OR by a|b', () => {
+ const e = ev('workflows', 'run wf_1 failed (1 of 2 agents)', { src: 'workflows', ref: 'run:wf_1', agentId: 'tester-7' })
+
+ expect(run('kind:workflows', e)).toBe(true)
+ expect(run('kind:swarm|workflows', e)).toBe(true)
+ expect(run('kind:swarm|claims', e)).toBe(false)
+ expect(run('level:bad', e)).toBe(true)
+ expect(run('level:ok|info', e)).toBe(false)
+ expect(run('agent:tester', e)).toBe(true)
+ expect(run('src:autopilot', e)).toBe(false)
+ expect(run('ref:run:wf_1', e)).toBe(true)
+ expect(run('-kind:workflows', e)).toBe(false)
+ expect(run('failed|stuck', e)).toBe(true)
+ })
+
+ it('since: keeps only recent events and takes the smallest of several', () => {
+ expect(run('since:15m', ev('swarm', 'a', {}, 5 * 60_000))).toBe(true)
+ expect(run('since:15m', ev('swarm', 'a', {}, 20 * 60_000))).toBe(false)
+ expect(run('since:2d since:1h', ev('swarm', 'a', {}, 2 * 3_600_000))).toBe(false)
+ expect(durationOf('90s')).toBe(90_000)
+ expect(durationOf('1h')).toBe(3_600_000)
+ expect(durationOf('0m')).toBeNull()
+ expect(durationOf('999d')).toBeNull()
+ expect(durationOf('soon')).toBeNull()
+ })
+
+ it('reports problems inline and still applies the rest', () => {
+ const q = parseQuery('since:soon kind: swarm "unclosed')
+
+ expect(q.errors.some(error => error.startsWith('since:'))).toBe(true)
+ expect(q.errors.some(error => error.includes('quote'))).toBe(true)
+ expect(q.terms.length).toBeGreaterThan(0)
+ })
+
+ it('caps the query length and the number of terms', () => {
+ const q = parseQuery('word '.repeat(500))
+
+ expect(q.source.length).toBeLessThanOrEqual(200)
+ expect(q.terms.length).toBeLessThanOrEqual(12)
+ })
+})
+
+describe('regex terms', () => {
+ it('match case-sensitively, or with /i, against the event text', () => {
+ expect(run('/spawn(ed)?/', ev('swarm', 'agent spawned'))).toBe(true)
+ expect(run('/SPAWN/', ev('swarm', 'agent spawned'))).toBe(false)
+ expect(run('/SPAWN/i', ev('swarm', 'agent spawned'))).toBe(true)
+ expect(run('-/spawn/', ev('swarm', 'agent spawned'))).toBe(false)
+ })
+
+ it.each(['(a+)+$', '(a*)*b', '(a|aa)+c', '((a+))+', '(.*a){3}', '(x+x+)+y', '(a|b)*', '\\1(a)(b)\\2', '(?=a)a', '(?<!a)b'])('refuses the dangerous pattern %s', pattern => {
+ expect(regexProblem(pattern)).not.toBeNull()
+
+ const q = parseQuery(`/${pattern}/`)
+
+ expect(q.terms).toHaveLength(0)
+ expect(q.errors.length).toBeGreaterThan(0)
+ })
+
+ it('refuses a pattern over the size cap, and accepts ordinary ones', () => {
+ expect(regexProblem('a'.repeat(REGEX_MAX + 1))).not.toBeNull()
+ expect(regexProblem('step s[0-9]+ (done|failed)')).toBeNull()
+ expect(regexProblem('^agent \\w+$')).toBeNull()
+ })
+
+ it('cannot be made to run long: a hostile event text and a hostile pattern both finish at once', () => {
+ const text = `${'a'.repeat(50_000)}!`
+ const started = performance.now()
+
+ for (const pattern of ['a*a*a*a*b', '.*.*.*x', '(a+)+$']) expect(parseQuery(`/${pattern}/`).terms).toHaveLength(0)
+ for (const pattern of ['.*a.*b', 'a+a+b', '\\w+ \\w+x']) for (let i = 0; i < 40; i++) matches(ev('swarm', text), parseQuery(`/${pattern}/`), NOW)
+
+ expect(performance.now() - started).toBeLessThan(3000)
+ })
+
+ it('a regex that cannot compile is an error line, not a throw', () => {
+ expect(() => parseQuery('/[a-/')).not.toThrow()
+ expect(parseQuery('/[a-/').errors.length).toBeGreaterThan(0)
+ })
+})
+
+describe('highlights', () => {
+ it('ranges of words, phrases and regexes, merged, and none for a negation or a field', () => {
+ const q = parseQuery('coder "was busy" -zzz kind:swarm')
+
+ expect(highlights('agent coder was busy', q)).toEqual([[6, 11], [12, 20]])
+ expect(highlights('coder coder', parseQuery('coder'))).toEqual([[0, 5], [6, 11]])
+ expect(highlights('abc', parseQuery('/b/'))).toEqual([[1, 2]])
+ expect(highlights('abc', parseQuery('-b'))).toEqual([])
+ })
+})
+
+describe('a random query never throws', () => {
+ it('over 3000 random strings drawn from the language alphabet', () => {
+ let seed = 7
+ const rnd = (n: number): number => {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff
+
+ return seed % n
+ }
+ const alphabet = ['a', 'b', ' ', '"', '/', '-', ':', '|', '(', ')', '+', '*', '\\', '[', ']', '{', '}', 'kind', 'level:', 'since:', '1h', '.', '^', '$', '?', 'é', '\u0000', '‮']
+ const event = ev('swarm', 'agent coder spawned', { agentId: 'x' })
+
+ for (let i = 0; i < 3000; i++) {
+ const q = Array.from({ length: rnd(40) }, () => alphabet[rnd(alphabet.length)]).join('')
+
+ expect(() => highlights(event.text, parseQuery(q))).not.toThrow()
+ expect(() => matches(event, parseQuery(q), NOW)).not.toThrow()
+ }
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-review-core.spec.ts b/plugins/ruflo-console/tests/events-review-core.spec.ts
new file mode 100644
index 0000000000..4344ce6697
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-review-core.spec.ts
@@ -0,0 +1,231 @@
+/**
+ * The adversarial review of ADR-474 (Events and Timeline), part: the concurrency strip, the problem jump and the verbs through the real command path. Each block names the defect it pins.
+ */
+import { beforeEach, describe, expect, it } from 'vitest'
+import { append, tick } from '../hooks/activity-live'
+import { resetIo } from '../hooks/activity-io'
+import { EVENTS_FILE, LANES_FILE } from '../hooks/data/activity-store'
+import type { ConsoleEvent } from '../hooks/data/events'
+import { cellsOf, concurrency, lanesIn, newLaneStore, addTools, type LaneView } from '../hooks/data/timeline-model'
+import { applyEventsArgs } from '../hooks/events-args'
+import { eventsActions, eventsUi } from '../hooks/events-ui'
+import type { Host } from '../hooks/host'
+import { parseRuflo } from '../hooks/commands'
+import { newState } from '../hooks/state'
+import { timelineActions, timelineUi } from '../hooks/timeline-ui'
+import { watchCommand } from '../hooks/watch-command'
+import { rig } from './fixtures/ev-rig'
+import { hostOn, newDisk, type Disk } from './fixtures/activity-fs'
+
+
+const T = Date.UTC(2026, 9, 7, 12)
+const CWD = '/work/proj'
+const ev = (text: string, atS = 0, extra: Partial<ConsoleEvent> = {}): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000, ...extra })
+
+function consoleOn(disk: Disk, options: Record<string, string | number | boolean> = {}) {
+ const state = newState(options)
+
+ state.cwd = CWD
+
+ const host = { ...hostOn(disk), every: () => ({ cancel: () => undefined }), invalidate: () => undefined } as unknown as Host
+
+ return { state, host }
+}
+
+beforeEach(() => resetIo())
+
+describe('the concurrency strip against a brute force', () => {
+ it('counts, peak, peak time and mean agree on 300 random lanes of spans', () => {
+ let seed = 1234567
+ const rand = (n: number): number => {
+ seed = (Math.imul(seed, 1103515245) + 12345) & 0x7fffffff
+
+ return seed % n
+ }
+
+ for (let round = 0; round < 300; round++) {
+ const fromMs = rand(1000)
+ const spanMs = 100 + rand(2400)
+ const bars = 1 + rand(40)
+ const win = { fromMs, toMs: fromMs + spanMs }
+ const lanes: LaneView[] = Array.from({ length: rand(8) }, (_, k) => ({
+ lane: `l${k}`, group: 'ruflo', label: `l${k}`, calls: 0, byTool: [], busyMs: 0, observedMs: 0, busyPct: null, longestMs: 0, lastAtMs: 0, tickMins: [],
+ spans: Array.from({ length: rand(5) }, () => {
+ const a = fromMs - 200 + rand(spanMs + 400)
+
+ return { lane: `l${k}`, group: 'ruflo' as const, label: 'x', fromMs: a, toMs: a + 1 + rand(600), busy: rand(3) > 0 }
+ }),
+ }))
+ const got = concurrency(lanes, win, newLaneStore(), bars)
+ const step = spanMs / bars
+ const want = new Array<number>(bars).fill(0)
+
+ for (const lane of lanes) {
+ const busy = new Set<number>()
+
+ for (const span of lane.spans) {
+ if (!span.busy) continue
+
+ // The integer milliseconds the span covers, inside the window, each placed in the bar that holds it.
+ for (let m = Math.max(span.fromMs, win.fromMs); m <= Math.min(span.toMs, win.toMs) - 1; m++) busy.add(Math.floor((m - win.fromMs) / step))
+ }
+
+ for (const i of busy) want[i]!++
+ }
+
+ const peak = Math.max(0, ...want)
+ const active = want.filter(n => n > 0)
+
+ expect(got.counts, `round ${round}`).toEqual(want)
+ expect(got.peak).toBe(peak)
+ expect(got.mean).toBe(active.length === 0 ? 0 : Math.round((active.reduce((x, y) => x + y, 0) / active.length) * 10) / 10)
+ expect(got.peakAtMs).toBe(peak === 0 ? null : win.fromMs + want.indexOf(peak) * step)
+ }
+ })
+
+ it('an idle span never hides a busy one, a tool-call minute marks its bar, and lanes with no overlap with the window are absent', () => {
+ const lane = (spans: { fromMs: number; toMs: number; busy: boolean }[], tickMins: number[] = []): LaneView => ({ lane: 'a', group: 'ruflo', label: 'a', calls: 0, byTool: [], busyMs: 0, observedMs: 0, busyPct: null, longestMs: 0, lastAtMs: 0, tickMins, spans: spans.map(s => ({ lane: 'a', group: 'ruflo' as const, label: 'a', ...s })) })
+ const win = { fromMs: 0, toMs: 600_000 }
+
+ expect([...cellsOf(lane([{ fromMs: 0, toMs: 600_000, busy: false }, { fromMs: 0, toMs: 60_000, busy: true }]), win, 10)].slice(0, 3)).toEqual([2, 1, 1])
+ expect(cellsOf(lane([], [5]), win, 10)[5]).toBe(3)
+
+ const store = newLaneStore()
+
+ store.spans.push({ lane: 'z', group: 'ruflo', label: 'z', fromMs: 5_000_000, toMs: 5_000_100, busy: true })
+ expect(lanesIn(store, win, 600_000)).toEqual([])
+ })
+
+ it('tool names that are also object property names are counted, and a minute persists once', () => {
+ const store = newLaneStore()
+
+ addTools(store, 'claude:main', 'claude', 'main', [{ atMs: 61_000, tool: 'constructor' }, { atMs: 62_000, tool: '__proto__' }, { atMs: 63_000, tool: 'constructor' }, { atMs: 64_000, tool: 'toString' }], 61_000)
+
+ const tick = [...store.ticks.values()][0]!
+
+ expect(tick.n).toBe(4)
+ expect(tick.tools.constructor).toBe(2)
+ expect(tick.tools.toString).toBe(1)
+ expect(Object.getPrototypeOf(tick.tools)).toBeNull()
+ })
+})
+
+describe('jump to the last problem walks back', () => {
+ it('pressed again it goes to the next older problem and says so when there is none', () => {
+ const w = rig(100, { events: 0 })
+
+ w.act.log.length = 0
+ append(w.act, [{ atMs: T - 3 * 3_600_000, kind: 'swarm', text: 'step a failed' }, { atMs: T - 2 * 3_600_000, kind: 'swarm', text: 'step b failed' }, { atMs: T - 3_600_000 / 2, kind: 'swarm', text: 'step c failed' }])
+ w.state.loadedAtMs = T - 86_400_000
+
+ const ui = timelineUi(w.state)
+ const real = Date.now
+
+ Date.now = () => T
+
+ try {
+ w.actions.timeline.problem()
+ expect(ui.said).toContain('step c failed')
+ Date.now = () => T + 7
+ w.actions.timeline.problem()
+ expect(ui.said).toContain('step b failed')
+ w.actions.timeline.problem()
+ expect(ui.said).toContain('step a failed')
+ w.actions.timeline.problem()
+ expect(ui.said).toContain('no warn or bad event before')
+ } finally {
+ Date.now = real
+ }
+ })
+})
+
+// ------------------------------------------------------------------------------------------------------------------ reachability
+
+describe('every documented verb does what the help says, through the real parse and command path', () => {
+ async function run(words: string): Promise<{ text: string; state: ReturnType<typeof newState>; asked: { label: string; argv?: readonly string[]; stdin?: string }[]; views: string[] }> {
+ const w = rig(100)
+ const asked: { label: string; argv?: readonly string[]; stdin?: string }[] = []
+ const views: string[] = []
+ const control = {
+ actions: { events: eventsActions(w.state, { fs: hostOn(newDisk()).fs, fillPrompt: async () => true } as unknown as Host, () => undefined, spec => {
+ if (spec !== null) {
+ asked.push(spec as never)
+ w.state.pending = { label: spec.label, args: [], expect: '', askedAtMs: Date.now(), shows: spec.shows } as never
+ }
+ }, () => undefined), timeline: timelineActions(w.state, { fs: hostOn(newDisk()).fs } as unknown as Host, () => undefined, id => void views.push(id), spec => {
+ if (spec !== null) {
+ asked.push(spec as never)
+ w.state.pending = { label: spec.label, args: [], expect: '', askedAtMs: Date.now(), shows: spec.shows } as never
+ }
+ }, () => undefined) },
+ setView: (id: string) => void views.push(id),
+ open: async () => ({ isPlaced: true, reason: '' }),
+ host: { invalidate: () => undefined },
+ }
+ const intent = parseRuflo(words)
+
+ expect(intent.kind === 'events' || intent.kind === 'timeline' || intent.kind === 'open').toBe(true)
+
+ if (intent.kind === 'open') return { text: 'opened', state: w.state, asked, views: [intent.view as string] }
+
+ const out = await watchCommand(control as never, w.state, intent as never)
+
+ return { text: out.text, state: w.state, asked, views }
+ }
+
+ it('events: kind, level, since, a quoted query, window, clear, follow, pin, rule', async () => {
+ expect((await run('events swarm')).text).toBe('events: swarm')
+ expect((await run('events bad')).text).toBe('events: level bad')
+ expect((await run('events since:15m kind:claims')).text).toContain('query since:15m kind:claims')
+ expect((await run('events "agent coder"')).text).toContain('"agent coder"')
+ expect((await run('events window 1h')).text).toBe('events: window 1h')
+ expect((await run('events clear')).text).toBe('events: filters cleared')
+
+ const follow = await run('events follow agent:coder-12')
+
+ expect(follow.text).toContain('following agent:coder-12')
+ expect(eventsUi(follow.state).followRef).toBe('agent:coder-12')
+ expect(follow.views).toContain('events')
+ expect((await run('events pin')).text).toBe('pinned')
+ expect((await run('events level bad')).text).toBe('events: level bad')
+ expect((await run('events kind:swarm rule')).text).not.toBe('')
+ })
+
+ it('forget asks first with the exact rm of the two files; export asks with a new-file write; a bad path says why and asks nothing', async () => {
+ const forget = await run('events forget')
+
+ expect(forget.asked).toHaveLength(1)
+ expect(forget.asked[0]?.argv).toEqual(['rm', '-f', '--', `${'/work/proj'}/${EVENTS_FILE}`, `${'/work/proj'}/${LANES_FILE}`])
+ expect(forget.text).toContain('Asked: forget the Events and Timeline history')
+
+ const exported = await run('events export run.jsonl')
+
+ expect(['dd', 'install']).toContain(exported.asked[0]?.argv?.[0])
+ expect(exported.asked[0]?.argv?.some(arg => arg === 'conv=excl' || arg === '/dev/stdin')).toBe(true)
+ expect(exported.asked[0]?.stdin).toContain('"kind"')
+
+ const bad = await run('events export ../../etc/x.md')
+
+ expect(bad.asked).toHaveLength(0)
+ expect(bad.text).toContain('..')
+
+ const tl = await run('timeline export lanes.csv')
+
+ expect(tl.asked[0]?.stdin).toContain('group,lane,busy_pct')
+ expect((await run('timeline export ../x.csv')).asked).toHaveLength(0)
+ })
+
+ it('timeline: every window, zoom in and out, follow; bare opens the page', async () => {
+ for (const id of ['5m', '15m', '1h', '6h', '24h', 'session']) expect((await run(`timeline ${id}`)).text).toBe(`timeline: ${id}`)
+ expect((await run('timeline zoom in')).text).toMatch(/^timeline: /)
+ expect((await run('timeline zoom sideways')).text).toContain('zoom takes')
+
+ const follow = await run('timeline follow run:wf_1')
+
+ expect(follow.views).toContain('events')
+ expect(eventsUi(follow.state).followRef).toBe('run:wf_1')
+ expect((await run('timeline')).views).toEqual(['timeline'])
+ expect(applyEventsArgs(newState({}), []).text).toMatch(/^events: /)
+ })
+})
+
diff --git a/plugins/ruflo-console/tests/events-review-query.spec.ts b/plugins/ruflo-console/tests/events-review-query.spec.ts
new file mode 100644
index 0000000000..30d09bd5bc
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-review-query.spec.ts
@@ -0,0 +1,211 @@
+/**
+ * The adversarial review of ADR-474 (Events and Timeline), part: the query language, export targets, severity, ids and window edges. Each block names the defect it pins.
+ */
+import { beforeEach, describe, expect, it } from 'vitest'
+import { append } from '../hooks/activity-live'
+import { resetIo } from '../hooks/activity-io'
+import { eventsText, exportSpecFor, resolveTarget } from '../hooks/data/event-export'
+import { collapse, idOf } from '../hooks/data/event-group'
+import { budgetOf, matches, parseQuery, regexProblem } from '../hooks/data/event-query'
+import { evaluateRules } from '../hooks/data/event-rules'
+import { levelOf } from '../hooks/data/event-severity'
+import type { ConsoleEvent } from '../hooks/data/events'
+import { eventsModel, eventsUi } from '../hooks/events-ui'
+import type { Host } from '../hooks/host'
+import { newState } from '../hooks/state'
+import { eventsView } from '../hooks/views/events'
+import { flat } from './fixtures/wf-drill-world'
+import { rig } from './fixtures/ev-rig'
+import { hostOn, newDisk, type Disk } from './fixtures/activity-fs'
+
+
+const T = Date.UTC(2026, 9, 7, 12)
+const CWD = '/work/proj'
+const ev = (text: string, atS = 0, extra: Partial<ConsoleEvent> = {}): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000, ...extra })
+
+function consoleOn(disk: Disk, options: Record<string, string | number | boolean> = {}) {
+ const state = newState(options)
+
+ state.cwd = CWD
+
+ const host = { ...hostOn(disk), every: () => ({ cancel: () => undefined }), invalidate: () => undefined } as unknown as Host
+
+ return { state, host }
+}
+
+beforeEach(() => resetIo())
+
+// ------------------------------------------------------------------------------------------------------------------ the query language
+
+describe('query language: bounded time on hostile patterns', () => {
+ it('refuses a run of optional atoms (a?a?a?...a{n} took 18 ms a line at n=20), a quantified optional group and the rest of the known shapes', () => {
+ for (const pattern of ['a?'.repeat(20) + 'a{20}', '(a?)+b', '(a|aa)+$', '(a+)+$', '(.*a){3}', '(?:a?){24}a{24}', 'a?a?a?', '(a*)*', '\\1(a)', '(?<=a)b']) expect(regexProblem(pattern), pattern).not.toBeNull()
+ for (const pattern of ['colou?r', 'step s[0-9]+ (done|failed)', '^agent \\w+$', 'https?', 'a.*b', '(?:ed|ing)']) expect(regexProblem(pattern), pattern).toBeNull()
+ })
+
+ it('a slow pattern over ten thousand 200-character events stops at its budget, says how many were not searched, and keeps the newest', () => {
+ const w = rig(100, { events: 10 })
+
+ w.act.log.length = 0
+ append(w.act, Array.from({ length: 10_000 }, (_, i) => ({ atMs: T + i * 1000, kind: 'swarm' as const, text: `${'a'.repeat(199)}${i % 2 === 0 ? 'x' : '!'}` })))
+ w.state.loadedAtMs = 0
+
+ const ui = eventsUi(w.state)
+
+ ui.parsed = parseQuery('/.*.*x/')
+
+ const started = performance.now()
+ const model = eventsModel(w.state, T + 20_000_000)
+ const took = performance.now() - started
+
+ expect(took).toBeLessThan(2500)
+
+ // Either it was quick enough to search everything, or it stopped and said so; never a silent partial answer.
+ expect(model.skipped === 0 || model.shown.length > 0).toBe(true)
+
+ if (model.skipped > 0) expect(model.shown.at(-1)?.atMs).toBe(T + 9_998 * 1000)
+ expect(model.shown.length + model.skipped).toBeGreaterThanOrEqual(0)
+ })
+
+ it('a budget that is already spent skips every regex event and counts it; word terms are never skipped', () => {
+ const budget = budgetOf(0)
+
+ budget.spentMs = 1
+
+ const event = ev('step s1 failed')
+
+ expect(matches(event, parseQuery('/failed/'), T, budget)).toBe(false)
+ expect(budget.skipped).toBe(1)
+ expect(matches(event, parseQuery('failed'), T, budget)).toBe(true)
+ expect(budget.skipped).toBe(1)
+ })
+
+ it('alert rules share a small budget and cannot hold the pass', () => {
+ const fresh = Array.from({ length: 5000 }, (_, i) => ev(`${'a'.repeat(199)}!`, i))
+ const started = performance.now()
+
+ evaluateRules([{ name: 'slow', q: '/.*.*x/' }, { name: 'slow2', q: '/a.*a.*b/' }], fresh, T)
+ expect(performance.now() - started).toBeLessThan(1500)
+ })
+
+ it('a hostile query never throws and a huge one is cut', () => {
+ for (const q of ['"', '/', '//', '/(/', '-', '--"', 'kind:', 'since:', 'a|', '|||', '\u0000'.repeat(10), 'x'.repeat(100_000), '/a/i/i', '"a" "b" -"c" /d/ kind:swarm|claims level:bad|warn agent:x since:1h']) {
+ expect(() => matches(ev('text'), parseQuery(q), T)).not.toThrow()
+ }
+
+ expect(parseQuery('x'.repeat(100_000)).source.length).toBeLessThanOrEqual(200)
+ })
+})
+
+// ------------------------------------------------------------------------------------------------------------------ export
+
+describe('export targets', () => {
+ const refuse = (input: string): string | null => {
+ const found = resolveTarget(input, CWD, ['md', 'jsonl'])
+
+ return found.ok ? null : found.why
+ }
+
+ it('refuses traversal, outside paths, odd bytes, hidden folders (.git, .claude), long and badly named files', () => {
+ for (const input of ['../x.md', 'a/../../x.md', '/etc/x.md', '/work/proj-evil/x.md', '/work/x.md', 'x\u0000.md', 'x\n.md', 'a\\b.md', '~/x.md', '-x.md', '.hidden.md', `${'a'.repeat(400)}.md`, 'x.exe', 'x', '', '.claude/commands/evil.md', '.git/hooks/x.md', '.github/x.md', 'a/.ssh/x.md', 'x.csv']) expect(refuse(input), JSON.stringify(input)).not.toBeNull()
+ for (const input of ['events.md', 'a b.jsonl', 'reports/events.md', '.claude-flow/console/exports/x.md']) expect(refuse(input), input).toBeNull()
+ })
+
+ it('refuses a link on the way, an existing file and a link as the file; a new file in a real folder passes with the dd conv=excl argv', async () => {
+ const disk = newDisk({ [`${CWD}/taken.md`]: 'x' })
+ const fs = hostOn(disk).fs
+
+ disk.dirs.add(`${CWD}/real`)
+ disk.dirs.add(`${CWD}/jump`)
+ disk.links.add(`${CWD}/jump`)
+ disk.links.add(`${CWD}/flat.md`)
+
+ expect((await exportSpecFor(fs, CWD, 'jump/x.md', 'c', 'l', ['md'])).ok).toBe(false)
+ expect((await exportSpecFor(fs, CWD, './flat.md', 'c', 'l', ['md'])).ok).toBe(false)
+ expect((await exportSpecFor(fs, CWD, './taken.md', 'c', 'l', ['md'])).ok).toBe(false)
+
+ const made = await exportSpecFor(fs, CWD, 'real/new file.md', 'c', 'l', ['md'])
+
+ expect(made.ok && made.spec.argv).toEqual(['dd', `of=${CWD}/real/new file.md`, 'conv=excl', 'status=none'])
+ })
+
+ it('the exported text is masked, defused against spreadsheets and capped', () => {
+ const text = eventsText([ev(`token=hunter2hunter2 [email protected]`), ...Array.from({ length: 3000 }, (_, i) => ev(`line ${i}`, i))], 'md', 'q', T)
+
+ expect(text).not.toContain("hunter2hunter2")
+ expect(text).not.toContain('carol@')
+ expect(new TextEncoder().encode(text).length).toBeLessThanOrEqual(400_000)
+ })
+})
+
+// ------------------------------------------------------------------------------------------------------------------ correctness
+
+describe('severity', () => {
+ it('a tool event is info whatever the agent or tool is called; a deny is still bad; calm counts stay calm', () => {
+ for (const text of ['error-handler: Bash', 'deny-list-manager: Read', 'stuck-fixer: Edit', 'blocked-tasks: mcp__x__failed_tasks']) expect(levelOf('tools', text), text).toBe('info')
+ expect(levelOf('tools', 'permission denied: Bash (policy)')).toBe('bad')
+ expect(levelOf('tools', 'confirm for "x" came 40s after the ask and was not run')).toBe('info')
+ expect(levelOf('workflows', 'finished: 0 failed, 0 errors')).toBe('ok')
+ expect(levelOf('workflows', 'finished: failed: 0 errors: 0')).toBe('ok')
+ expect(levelOf('workflows', 'finished: 2 failed')).toBe('bad')
+ })
+})
+
+describe('ids and keys', () => {
+ it('two events of one millisecond and one length have different ids, and the page keys stay unique', () => {
+ const a = ev('agent a1 joined', 0, { agentId: 'a1' })
+ const b = ev('agent b2 joined', 0, { agentId: 'b2' })
+
+ expect(idOf(a)).not.toBe(idOf(b))
+
+ const w = rig(100, { events: 0 })
+
+ w.act.log.length = 0
+ append(w.act, [ev('agent a1 joined'), ev('agent b2 joined'), ev('agent b2 joined'), { ...ev('agent c3 joined'), kind: 'claims' as const }])
+ eventsUi(w.state).isGrouped = false
+ eventsUi(w.state).window = 'all'
+
+ const ids = eventsModel(w.state, T + 1000).rows.map(row => row.id)
+
+ expect(new Set(ids).size).toBe(ids.length)
+
+ const keys = flat(eventsView(w.ctx)).filter(node => node.kind === 'Button').map(node => String(node.props.key))
+
+ expect(new Set(keys).size).toBe(keys.length)
+
+ // Opening one row opens one row.
+ w.actions.events.open(ids[0] as string)
+ expect(flat(eventsView(w.ctx)).filter(node => node.kind === 'Button' && String(node.props.key) === 'ev-pin')).toHaveLength(1)
+ })
+
+ it('a burst of identical lines folds into one row with a count', () => {
+ const rows = collapse(Array.from({ length: 5 }, (_, i) => ev('agent a1 retry 3', i * 5)))
+
+ expect(rows).toHaveLength(1)
+ expect(rows[0]?.members).toHaveLength(5)
+ expect(collapse([ev('x 1', 0), ev('x 2', 31), ev('x 3', 62)])).toHaveLength(3)
+ })
+})
+
+describe('windows at their edges', () => {
+ it('15 minutes includes the event exactly 15 minutes old and excludes one millisecond older; since: agrees', () => {
+ const w = rig(100, { events: 0 })
+
+ w.act.log.length = 0
+ w.state.loadedAtMs = T - 86_400_000
+ append(w.act, [{ atMs: T - 900_000, kind: 'swarm', text: 'edge in' }, { atMs: T - 900_001, kind: 'swarm', text: 'edge out' }, { atMs: T + 86_400_000, kind: 'swarm', text: 'future' }])
+
+ const ui = eventsUi(w.state)
+
+ ui.window = '15m'
+ expect(eventsModel(w.state, T).shown.map(e => e.text)).toEqual(['edge in', 'future'])
+ ui.window = 'all'
+ ui.parsed = parseQuery('since:15m')
+ expect(eventsModel(w.state, T).shown.map(e => e.text)).toEqual(['edge in', 'future'])
+ ui.parsed = parseQuery('')
+ ui.window = 'session'
+ w.state.loadedAtMs = T - 900_001
+ expect(eventsModel(w.state, T).shown).toHaveLength(3)
+ })
+})
+
diff --git a/plugins/ruflo-console/tests/events-review.spec.ts b/plugins/ruflo-console/tests/events-review.spec.ts
new file mode 100644
index 0000000000..f4e107ec31
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-review.spec.ts
@@ -0,0 +1,294 @@
+/**
+ * The adversarial review of ADR-474 (Events and Timeline), part: what reaches the disk and the append (privacy, the write path). Each block names the defect it pins.
+ */
+import { spawnSync } from 'node:child_process'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { beforeEach, describe, expect, it } from 'vitest'
+import { activityOf, append, loadActivity, tick } from '../hooks/activity-live'
+import { appendArgv, BATCH_MAX, flush, queueLine, resetIo } from '../hooks/activity-io'
+import { decodeEvent, decodeEvents, decodeLane, decodeLanes, decodePrefs, EVENTS_CAP, EVENTS_FILE, LANES_FILE, PREFS_FILE } from '../hooks/data/activity-store'
+import { maskLine } from '../hooks/data/event-mask'
+import type { ConsoleEvent } from '../hooks/data/events'
+import { eventsActions, eventsUi } from '../hooks/events-ui'
+import type { Host } from '../hooks/host'
+import { newState } from '../hooks/state'
+import { hostOn, newDisk, type Disk } from './fixtures/activity-fs'
+
+
+const T = Date.UTC(2026, 9, 7, 12)
+const CWD = '/work/proj'
+const ev = (text: string, atS = 0, extra: Partial<ConsoleEvent> = {}): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000, ...extra })
+
+function consoleOn(disk: Disk, options: Record<string, string | number | boolean> = {}) {
+ const state = newState(options)
+
+ state.cwd = CWD
+
+ const host = { ...hostOn(disk), every: () => ({ cancel: () => undefined }), invalidate: () => undefined } as unknown as Host
+
+ return { state, host }
+}
+
+beforeEach(() => resetIo())
+
+// ------------------------------------------------------------------------------------------------------------------ privacy
+
+const SECRETS = [
+ 'sk-ant-api03-ZZZZ1234567890abcdefghij',
+ 'ghp_abcdefghijklmnopqrstuvwxyz0123456789',
+ 'AKIAIOSFODNN7EXAMPLE',
+ 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
+ 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U',
+ 'hunter2hunter2',
+ 'sessionvalue-ABC123',
+ 'tailsecretIJKLMNOP',
+]
+
+const HOSTILE: string[] = [
+ `agent failed: ANTHROPIC_API_KEY=${SECRETS[0]}`,
+ `used ${SECRETS[1]} to push`,
+ `export AWS_ACCESS_KEY_ID=${SECRETS[2]} AWS_SECRET_ACCESS_KEY=${SECRETS[3]}`,
+ `curl -H "Authorization: Bearer ${SECRETS[4]}" https://x.test`,
+ `.env line DB_PASS=${SECRETS[5]} and PASSWORD: ${SECRETS[5]}`,
+ `sk-\u001b[0mant-api03-${'A'.repeat(20)}ZZZZ1234567890`,
+ `sk-\u200bant-api03-ZZZZ1234567890abcdefghij`,
+ `sk-ant-api03-${'B'.repeat(12)}\u0001tailsecretIJKLMNOP`,
+ `\u001b]0;title ${SECRETS[0]}\u0007visible`,
+ `‮${SECRETS[1]}`,
+ `Cookie: session=${SECRETS[6]}; other=1`,
+ `mail ${SECRETS[8]} about it`,
+ `opened /home/ruvultra/projects/secret-client/notes.md and C:\\Users\\Carol\\Documents\\x.txt`,
+ `${'x'.repeat(60_000)} token=${SECRETS[5]}`,
+]
+
+const LEAKS = [...SECRETS, 'ruvultra', 'Carol']
+
+describe('what reaches the disk (privacy)', () => {
+ it('hostile text through the real write path leaves no credential, email, user name or control character in any file', async () => {
+ const disk = newDisk()
+ const { state, host } = consoleOn(disk)
+
+ await tick(state, host, T)
+ for (const [i, text] of HOSTILE.entries()) state.events.push(ev(text, i, { agentId: `agent-${SECRETS[0]}`, ref: `run:${SECRETS[1]}` }))
+ state.toolsByAgent.set('main', [{ atMs: T - 90_000, tool: SECRETS[0] as string }, { atMs: T - 80_000, tool: 'Bash' }])
+ state.snapshot = { agents: [{ id: `a-${SECRETS[1]}`, type: `coder ${SECRETS[3]}`, status: 'busy' }], tasks: [] } as never
+ await tick(state, host, T + 2000)
+ await tick(state, host, T + 6000)
+ ;(state.snapshot as unknown as { agents: { status: string }[] }).agents[0]!.status = 'idle'
+ await tick(state, host, T + 12_000)
+ await tick(state, host, T + 200_000)
+
+ const act = activityOf(state)
+
+ act.prefs.pins.push({ atMs: T, kind: 'swarm', text: maskLine(HOSTILE[0]), level: 'bad' })
+ eventsUi(state).query = ''
+ eventsActions(state, host, () => undefined, () => undefined, () => undefined).query(`failed token=${SECRETS[5]}`)
+ eventsActions(state, host, () => undefined, () => undefined, () => undefined).saveSearch()
+ eventsActions(state, host, () => undefined, () => undefined, () => undefined).addRule()
+ await tick(state, host, T + 210_000)
+ await tick(state, host, T + 215_000)
+
+ const files = [...disk.files].filter(([path]) => path.includes('/.claude-flow/console/'))
+
+ expect(files.map(([path]) => path.split('/').pop()).sort()).toEqual(expect.arrayContaining(['events.jsonl', 'events-prefs.json']))
+
+ for (const [path, body] of files) {
+ for (const leak of LEAKS) expect(body, `${path} holds ${leak}`).not.toContain(leak)
+ // eslint-disable-next-line no-control-regex
+ expect(body.replace(/\n/g, ''), path).not.toMatch(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]|[\u{e0000}-\u{e007f}]/u)
+ for (const line of body.split('\n').filter(Boolean)) expect(line.length, path).toBeLessThan(1_200)
+ }
+ })
+
+ it('every washing shape is masked on its own', () => {
+ for (const text of HOSTILE.slice(0, 13)) {
+ const out = maskLine(text)
+
+ for (const leak of LEAKS) expect(out, text.slice(0, 40)).not.toContain(leak)
+ }
+
+ // A control character in the middle of a credential joins it (a space would leave the tail readable on disk).
+ expect(maskLine('sk-ant-api03-BBBBBBBBBBBB\u0001tailsecretIJKLMNOP')).not.toContain('tailsecret')
+ expect(maskLine('write to [email protected] now')).toBe('write to ‹masked› now')
+ expect(maskLine('C:\\Users\\Carol\\x')).toBe('~\\x')
+ expect(maskLine('Set-Cookie: sid=abc; Path=/')).toBe('Set-Cookie: ‹masked›')
+ })
+
+ it('a 50 kB line and 10 000 long hostile lines are washed in bounded time', () => {
+ const started = performance.now()
+
+ maskLine('a'.repeat(50_000))
+ maskLine(`${'a.'.repeat(25_000)}@`)
+ maskLine(`${'@'.repeat(50_000)}`)
+ maskLine(`${'ab '.repeat(17_000)}`)
+ for (let i = 0; i < 2000; i++) maskLine(`${'q'.repeat(300)}${i}@${'w'.repeat(300)}`)
+
+ expect(performance.now() - started).toBeLessThan(4000)
+ })
+
+ it('eventsPersist off writes nothing at all: no event, lane, saved search, pin, rule, folder or ignore file', async () => {
+ const disk = newDisk()
+ const { state, host } = consoleOn(disk, { eventsPersist: false })
+
+ await tick(state, host, T)
+ state.events.push(ev(HOSTILE[0] as string, 5))
+ state.toolsByAgent.set('main', [{ atMs: T - 90_000, tool: 'Bash' }])
+ state.snapshot = { agents: [{ id: 'a1', type: 'coder', status: 'busy' }], tasks: [] } as never
+
+ const actions = eventsActions(state, host, () => undefined, () => undefined, () => undefined)
+
+ actions.query('level:bad')
+ actions.saveSearch()
+ actions.addRule()
+ actions.pin(ev('pinned secret token=hunter2hunter2'))
+
+ for (const s of [2000, 6000, 12_000, 70_000, 140_000]) await tick(state, host, T + s)
+
+ expect(disk.runs).toEqual([])
+ expect([...disk.files.keys()]).toEqual([])
+ expect(activityOf(state).prefs.searches).toHaveLength(1)
+ })
+
+ it('the folder carries its own .gitignore of *, because the one `ruflo init` writes does not list console/', async () => {
+ const disk = newDisk()
+ const { state, host } = consoleOn(disk)
+
+ await tick(state, host, T)
+ state.events.push(ev('something happened', 1))
+ await tick(state, host, T + 5000)
+ expect(disk.files.get(`${CWD}/.claude-flow/console/.gitignore`)).toMatch(/^\*$/m)
+
+ // Written once, and the pins file written first (the folder made by install -D) gets it too.
+ resetIo()
+
+ const second = newDisk()
+ const other = consoleOn(second)
+
+ await tick(other.state, other.host, T)
+ activityOf(other.state).prefs.pins.push({ atMs: T, kind: 'swarm', text: 'x', level: 'info' })
+ activityOf(other.state).isPrefsDirty = true
+ await tick(other.state, other.host, T + 5000)
+ expect(second.files.has(`${CWD}/.claude-flow/console/events-prefs.json`)).toBe(true)
+ expect(second.files.get(`${CWD}/.claude-flow/console/.gitignore`)).toMatch(/^\*$/m)
+ })
+
+ it('forget removes the events and lanes files, empties the page, and nothing old comes back; pins and searches stay (documented)', async () => {
+ const disk = newDisk()
+ const { state, host } = consoleOn(disk)
+ const asked: { argv?: readonly string[]; onOutput?: (out: string) => void }[] = []
+ const actions = eventsActions(state, host, () => undefined, spec => void asked.push(spec as never), () => undefined)
+
+ await tick(state, host, T)
+ state.events.push(ev('keep me out of the file after forget', 1))
+ state.toolsByAgent.set('main', [{ atMs: T - 90_000, tool: 'Bash' }])
+ await tick(state, host, T + 5000)
+ await tick(state, host, T + 200_000)
+ expect(disk.files.get(`${CWD}/${EVENTS_FILE}`)).toContain('keep me out')
+
+ actions.forget()
+
+ const spec = asked[0] as { argv: readonly string[]; onOutput: (out: string) => void }
+
+ expect(spec.argv).toEqual(['rm', '-f', '--', `${CWD}/${EVENTS_FILE}`, `${CWD}/${LANES_FILE}`])
+ await hostOn(disk).run(spec.argv, 1000)
+ spec.onOutput('')
+ expect(disk.files.has(`${CWD}/${EVENTS_FILE}`)).toBe(false)
+ expect(disk.files.has(`${CWD}/${LANES_FILE}`)).toBe(false)
+ expect(activityOf(state).log).toHaveLength(0)
+
+ await tick(state, host, T + 210_000)
+ await tick(state, host, T + 220_000)
+ expect(disk.files.get(`${CWD}/${EVENTS_FILE}`) ?? '').not.toContain('keep me out')
+ expect(activityOf(state).log).toHaveLength(0)
+ })
+
+ it('a hostile history file is masked when it is read, and a poisoned prefs file cannot pollute prototypes', async () => {
+ const line = `${JSON.stringify({ v: 1, t: T, kind: 'swarm', level: 'info', text: `leaked ${SECRETS[0]} [email protected]`, agent: SECRETS[1] })}\n`
+ const disk = newDisk({ [`${CWD}/${EVENTS_FILE}`]: line, [`${CWD}/${PREFS_FILE}`]: '{"v":1,"__proto__":{"polluted":1},"constructor":{"prototype":{"polluted":2}},"searches":[{"name":"__proto__","q":"x"},{"name":"constructor","q":"y"}],"pins":[{"__proto__":{"polluted":3},"atMs":1,"text":"t","kind":"__proto__"}]}' })
+ const { state, host } = consoleOn(disk)
+
+ await loadActivity(state, host)
+
+ const shown = activityOf(state).log[0] as ConsoleEvent
+
+ expect(shown.text).not.toContain('sk-ant')
+ expect(shown.text).not.toContain('carol@')
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined()
+ expect(decodePrefs('{"v":1,"searches":[{"name":"a","q":"b"}],"__proto__":{"polluted":1}}').prefs.searches).toHaveLength(1)
+ expect(activityOf(state).prefs.searches.map(item => item.name)).toEqual(['__proto__', 'constructor'])
+ expect(activityOf(state).prefs.pins[0]?.kind).toBe('other')
+ })
+
+ it('NaN, Infinity, negative and absurd times in an old log are skipped or harmless; a future time is kept and shown as now', () => {
+ for (const t of ['-5', '1e999', '"12"', 'null']) expect(decodeEvent(`{"v":1,"t":${t},"kind":"swarm","text":"x"}`)).toBeNull()
+ expect(decodeEvent(`{"v":1,"t":${T + 10 * 86_400_000},"kind":"swarm","text":"x"}`)).not.toBeNull()
+ expect(decodeLane('{"v":1,"t":"span","l":"a","g":"ruflo","n":"a","a":-1,"b":5,"y":1}')).toBeNull()
+ expect(decodeLane('{"v":1,"t":"span","l":"a","g":"ruflo","n":"a","a":9,"b":5,"y":1}')).toBeNull()
+ expect(decodeLane('{"v":1,"t":"span","l":"a","g":"ruflo","n":"a","a":1e999,"b":1e999,"y":1}')).toBeNull()
+
+ const tools = (decodeLane('{"v":1,"t":"tick","l":"a","g":"claude","n":"a","m":5,"c":2,"tools":{"__proto__":2,"constructor":1,"Bash":1}}') as { tools: Record<string, number> }).tools
+
+ expect(tools.constructor).toBe(1)
+ expect(Object.keys(tools).sort()).toEqual(['Bash', '__proto__', 'constructor'])
+ })
+
+ it('a 2 MiB log of tiny lines and a 1 MiB lane log load fast and keep the newest', () => {
+ const tiny = Array.from({ length: 200_000 }, (_, i) => `{"v":1,"t":${T + i},"kind":"swarm","text":"a${i}"}\n`).join('')
+ const lanes = Array.from({ length: 60_000 }, (_, i) => `{"v":1,"t":"span","l":"l${i % 50}","g":"ruflo","n":"n","a":${T + i * 10},"b":${T + i * 10 + 5},"y":1}\n`).join('')
+ const started = performance.now()
+ const events = decodeEvents(tiny)
+ const rows = decodeLanes(lanes)
+
+ expect(events.items.length).toBeLessThanOrEqual(10_000)
+ expect(events.items.at(-1)?.text).toBe('a199999')
+ expect(rows.items.length).toBeLessThanOrEqual(20_000)
+ expect(performance.now() - started).toBeLessThan(5000)
+ })
+})
+
+// ------------------------------------------------------------------------------------------------------------------ the append
+
+describe('the append path', () => {
+ it('uses one block per batch (bs and iflag=fullblock) and every path as a single argv element, never a shell', async () => {
+ const odd = "/work/it's a \"dir\" $(touch x); -rf\n"
+ const disk = newDisk()
+
+ disk.dirs.add(odd.replace(/\/+$/, ''))
+ queueLine(`${odd}f.jsonl`, EVENTS_CAP, '{"v":1}\n')
+ await flush(hostOn(disk), odd, `${odd}f.jsonl`, T)
+
+ expect(disk.runs.every(argv => !['sh', 'bash', 'zsh'].includes(argv[0] as string) && !argv.includes('-c'))).toBe(true)
+ expect(appendArgv('/p/a b')).toEqual(['dd', 'of=/p/a b', 'oflag=append', 'conv=notrunc', 'bs=1M', 'iflag=fullblock', 'status=none'])
+ expect(BATCH_MAX + 2000).toBeLessThan(1024 * 1024)
+ })
+
+ it.skipIf(process.platform !== 'linux')('with the real GNU dd, eight writers of batches that are 55 kB each never tear a line', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ev-dd-'))
+
+ try {
+ const batch = (c: string): string => Array.from({ length: 60 }, (_, i) => `{"w":"${c}","n":${i},"pad":"${c.repeat(900)}"}\n`).join('')
+ const file = join(dir, 'out.jsonl')
+ const [cmd, ...rest] = appendArgv(file) as string[]
+ const script = Array.from({ length: 8 }, (_, w) => {
+ const src = join(dir, `b${w}.txt`)
+
+ writeFileSync(src, batch(w % 2 === 0 ? 'A' : 'B'))
+
+ return `( for k in 1 2 3 4 5; do cat '${src}' | ${[cmd, ...rest].map(arg => `'${arg}'`).join(' ')}; done ) &`
+ }).join('\n')
+
+ expect(spawnSync('bash', ['-c', `${script}\nwait`]).status).toBe(0)
+
+ const lines = readFileSync(file, 'utf8').split('\n').filter(Boolean)
+
+ expect(lines).toHaveLength(8 * 5 * 60)
+ expect(lines.filter(line => !/^\{"w":"(A+|B+)","n":\d+,"pad":"(A+|B+)"\}$/.test(line) || line.length < 900)).toHaveLength(0)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
+
diff --git a/plugins/ruflo-console/tests/events-rules.spec.ts b/plugins/ruflo-console/tests/events-rules.spec.ts
new file mode 100644
index 0000000000..44779116ac
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-rules.spec.ts
@@ -0,0 +1,79 @@
+/**
+ * Alert rules and the derived sources (ADR-474): a rule fires only on NEW events, a bad rule never fires, the first read of every
+ * source is a baseline, and each source says what happened between two reads.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { evaluateRules } from '../hooks/data/event-rules'
+import { anatoleEvents, apEvents, denyEvents, modEvents, newMemo, noticeEvents, runEvents } from '../hooks/data/event-sources'
+import type { ConsoleEvent } from '../hooks/data/events'
+import type { WfRun } from '../hooks/data/workflows'
+
+const T = Date.UTC(2026, 9, 7, 12)
+const ev = (text: string, kind: ConsoleEvent['kind'] = 'swarm'): ConsoleEvent => ({ kind, text, atMs: T })
+
+describe('evaluateRules', () => {
+ const rules = [{ name: 'bad swarm', q: 'kind:swarm level:bad' }, { name: 'broken', q: 'kind:' }, { name: 'empty', q: '' }, { name: 'rx', q: '/step s\\d/' }]
+
+ it('fires per matching rule over the new events only, with the count and the newest', () => {
+ const hits = evaluateRules(rules, [ev('agent a failed'), ev('agent b failed'), ev('topology mesh'), ev('step s2 ran')], T)
+
+ expect(hits.map(hit => [hit.rule, hit.count])).toEqual([['bad swarm', 2], ['rx', 1]])
+ expect(hits[0]?.newest.text).toBe('agent b failed')
+ expect(hits[0]?.level).toBe('bad')
+ })
+
+ it('nothing new, nothing fired; a rule with errors or no terms never fires', () => {
+ expect(evaluateRules(rules, [], T)).toEqual([])
+ expect(evaluateRules([{ name: 'x', q: 'since:soon' }], [ev('failed')], T)).toEqual([])
+ })
+})
+
+const run = (id: string, state: WfRun['state'], extra: Partial<WfRun> = {}): WfRun => ({ id, name: id, kind: 'workflow', state, phases: [], running: 0, done: 0, failed: 0, idle: 0, total: 2, totalTokens: null, isTokensPartial: false, hasRecord: true, ...extra })
+
+describe('derived sources', () => {
+ it('workflow runs: the first read is a baseline, then started, failed, stuck, empty and finished are events with a run ref', () => {
+ const memo = newMemo()
+
+ expect(runEvents(memo, [run('a', 'running')], T)).toEqual([])
+
+ const out = runEvents(memo, [run('a', 'failed', { failed: 1 }), run('b', 'running'), run('c', 'stalled')], T + 1)
+
+ expect(out.map(e => e.text)).toEqual(['run a failed (1 of 2 agents)', 'run b started', 'run c seen stalled'])
+ expect(out.every(e => e.kind === 'workflows' && e.ref?.startsWith('run:'))).toBe(true)
+ expect(runEvents(memo, [run('a', 'failed'), run('b', 'completed', { done: 2 }), run('c', 'stalled')], T + 2).map(e => e.text)).toEqual(['run b finished: 2 of 2 agents done'])
+ expect(runEvents(memo, [run('b', 'completed', { total: 0 }), run('a', 'failed'), run('c', 'stalled')], T + 3).map(e => e.text)).toEqual(['run b finished empty: no agents'])
+ expect(runEvents(memo, [run('a', 'failed'), run('b', 'completed', { total: 0 }), run('c', 'stalled')], T + 4)).toEqual([])
+ })
+
+ it('autopilot: start, a step handed over, done, failed, parked, stop and the kill flag', () => {
+ const memo = newMemo()
+ const base = { phase: 'idle', steps: [], killed: false, parked: [], reason: null }
+ const step = (status: 'started' | 'done' | 'failed', extra = {}) => ({ id: 's1', task: 't1', cls: 'c', attempt: 1, startedAt: 1, deadline: 2, status, tier: 'low', ...extra })
+
+ expect(apEvents(memo, base, T)).toEqual([])
+ expect(apEvents(memo, { ...base, phase: 'running' }, T).map(e => e.text)).toEqual(['autopilot started'])
+ expect(apEvents(memo, { ...base, phase: 'running', steps: [step('started')] }, T).map(e => e.text)).toEqual(['step s1 handed over: t1'])
+ expect(apEvents(memo, { ...base, phase: 'running', steps: [step('done', { verified: true })] }, T).map(e => e.text)).toEqual(['step s1 done (verified)'])
+ expect(apEvents(memo, { ...base, phase: 'running', steps: [step('failed', { why: 'tests red' })], parked: [{ id: 'p1', question: 'which?' }], killed: true }, T).map(e => e.text)).toEqual(['step s1 failed: tests red', 'step p1 parked: which?', 'kill flag set: the autopilot is blocked'])
+ expect(apEvents(memo, { ...base, phase: 'stopped', reason: 'you', steps: [step('failed', { why: 'tests red' })], parked: [{ id: 'p1', question: 'which?' }], killed: true }, T).map(e => e.text)).toEqual(['autopilot stopped: you'])
+ })
+
+ it('anatole alerts, band notices, denies and mods: baseline first, then only what is new; a rule notice is not an event', () => {
+ const memo = newMemo()
+ const alert = (id: string) => ({ id, atMs: T, rule: 'r1', owasp: [], severity: 'high' as const, action: 'blocked' as const, tool: 'Bash', summary: 's', fp: null, state: 'open' as const })
+
+ expect(anatoleEvents(memo, [alert('a1')], T)).toEqual([])
+ expect(anatoleEvents(memo, [alert('a1'), alert('a2')], T).map(e => [e.kind, e.text, e.ref])).toEqual([['anatole', 'Anatole blocked Bash: rule r1 (high)', 'rule:r1']])
+
+ expect(noticeEvents(memo, [], 5)).toEqual([])
+ expect(noticeEvents(memo, [{ id: 6, level: 'warn', text: '2 new approvals waiting', key: 'approvals', atMs: T }, { id: 7, level: 'warn', text: 'rule hit', key: 'events-rule:x', atMs: T }], 7).map(e => e.text)).toEqual(['band: 2 new approvals waiting'])
+
+ expect(denyEvents(memo, [])).toEqual([])
+ expect(denyEvents(memo, [{ tool: 'Bash', reason: 'policy', atMs: T }]).map(e => e.text)).toEqual(['permission denied: Bash (policy)'])
+ expect(denyEvents(memo, [{ tool: 'Bash', reason: 'policy', atMs: T }])).toEqual([])
+
+ expect(modEvents(memo, [{ name: 'm1', isLoaded: true }], T)).toEqual([])
+ expect(modEvents(memo, [{ name: 'm1', isLoaded: false, reason: 'untrusted' }, { name: 'm2', isLoaded: true }], T).map(e => e.text)).toEqual(['mod m1 refused: untrusted', 'mod m2 loaded'])
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-severity.spec.ts b/plugins/ruflo-console/tests/events-severity.spec.ts
new file mode 100644
index 0000000000..ed55ccfe62
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-severity.spec.ts
@@ -0,0 +1,60 @@
+/**
+ * Event levels (ADR-474): the one pure rule that gives every event ok, info, warn or bad, and the mask that washes what is stored.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { maskLine } from '../hooks/data/event-mask'
+import { levelOf, levelOfEvent, rankOf } from '../hooks/data/event-severity'
+
+describe('levelOf', () => {
+ it.each([
+ ['swarm', 'agent coder: busy → failed', 'bad'],
+ ['workflows', 'run x is stuck: no progress', 'bad'],
+ ['tools', 'permission denied: Bash (policy)', 'bad'],
+ ['autopilot', 'step s1 parked: which branch?', 'warn'],
+ ['swarm', 'swarm paused (was running)', 'warn'],
+ ['claims', 'ISSUE-1 released', 'warn'],
+ ['autopilot', 'step s1 done (verified)', 'ok'],
+ ['learning', '+2 patterns learned', 'ok'],
+ ['swarm', 'topology mesh', 'info'],
+ ['anatole', 'Anatole blocked Bash: rule r1 (high)', 'bad'],
+ ['anatole', 'Anatole notified Read: rule r2 (low)', 'warn'],
+ ])('%s "%s" is %s', (kind, text, level) => expect(levelOf(kind, text)).toBe(level))
+
+ it('a bad word wins over a warn word, and "0 failed" is not a failure', () => {
+ expect(levelOf('swarm', 'paused after an error')).toBe('bad')
+ expect(levelOf('workflows', 'run finished: 0 failed')).toBe('ok')
+ expect(levelOf('workflows', 'run finished: no errors')).toBe('ok')
+ })
+
+ it('ranks bad over warn over info over ok, and remembers per event object', () => {
+ expect([rankOf('bad'), rankOf('warn'), rankOf('info'), rankOf('ok')]).toEqual([3, 2, 1, 0])
+
+ const event = { kind: 'swarm', text: 'x failed' }
+
+ expect(levelOfEvent(event)).toBe('bad')
+ event.text = 'fine'
+ expect(levelOfEvent(event)).toBe('bad')
+ })
+})
+
+describe('maskLine', () => {
+ it('masks credentials, keyed secrets, bearer strings and home paths', () => {
+ expect(maskLine('token=abcdef123456 used')).not.toContain('abcdef123456')
+ expect(maskLine('Authorization: Bearer abcdefghijklmnop')).not.toContain('abcdefghijklmnop')
+ expect(maskLine('key sk-ant-abcdefghijklmnopqrstuvwxyz0123 leaked')).not.toContain('abcdefghijklmnopqrstuvwxyz')
+ expect(maskLine('read /home/alice/secret/notes.txt')).toBe('read ~/secret/notes.txt')
+ expect(maskLine('password: hunter2')).not.toContain('hunter2')
+ })
+
+ it('strips escapes, control, bidi and tag characters, and caps the length with an ellipsis', () => {
+ const hostile = `a\u001b[31mred\u001b[0m‮evil\u0007${String.fromCodePoint(0xe0041)}​z`
+
+ expect(maskLine(hostile)).toBe('aredevilz')
+ expect(maskLine(hostile)).not.toMatch(/[\u001b‮\u0007​]/u)
+ expect(maskLine(hostile)).not.toContain(String.fromCodePoint(0xe0041))
+ expect(maskLine('word '.repeat(100), 20)).toHaveLength(20)
+ expect(maskLine('word '.repeat(100), 20).endsWith('…')).toBe(true)
+ expect(maskLine(42 as unknown as string)).toBe('')
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-store.spec.ts b/plugins/ruflo-console/tests/events-store.spec.ts
new file mode 100644
index 0000000000..abe3dc38d1
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-store.spec.ts
@@ -0,0 +1,139 @@
+/**
+ * The persisted schema (ADR-474): lines encode masked and versioned, decode tolerantly (corrupt lines, a cut first line, newer
+ * schema, unknown kind), de-duplicate what two consoles both logged, rotate to the newest half, and the prefs file round-trips.
+ * A property test round-trips random events.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { decodeEvent, decodeEvents, decodeLane, decodeLanes, decodePrefs, emptyPrefs, encodeEvent, encodeLane, encodePrefs, keepNewestHalf, MAX_LOG, MAX_PINS, MAX_RULES, MAX_SEARCHES, tailLines } from '../hooks/data/activity-store'
+import type { ConsoleEvent } from '../hooks/data/events'
+
+const T = Date.UTC(2026, 9, 7, 12)
+const ev = (text: string, atS = 0, extra: Partial<ConsoleEvent> = {}): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000, ...extra })
+
+describe('event lines', () => {
+ it('encode a versioned, masked line with its level, and decode it back', () => {
+ const line = encodeEvent(ev('agent coder failed token=abc123def456 in /home/alice/x', 0, { agentId: 'a1' }), 's1')
+ const parsed = JSON.parse(line) as Record<string, unknown>
+
+ expect(parsed).toMatchObject({ v: 1, kind: 'swarm', level: 'bad', agent: 'a1', s: 's1' })
+ expect(line).not.toContain('abc123def456')
+ expect(line).not.toContain('alice')
+ expect(line.endsWith('\n')).toBe(true)
+ expect(decodeEvent(line.trim())).toMatchObject({ atMs: T, kind: 'swarm', agentId: 'a1', src: 'history' })
+ })
+
+ it('skips corrupt lines, a partial last line, a cut first line and lines from a newer schema, and says how many', () => {
+ const good = encodeEvent(ev('one', 0)) + encodeEvent(ev('two', 1))
+ const text = `${good.slice(7)}not json\n{"v":2,"t":1,"kind":"swarm","text":"future"}\n{"v":1,"t":"x"}\n${encodeEvent(ev('three', 2))}{"v":1,"t":99,"kind":"sw`
+ const out = decodeEvents(text)
+
+ expect(out.items.map(e => e.text)).toEqual(['two', 'three'].filter(t => out.items.some(e => e.text === t)))
+ expect(out.items.map(e => e.text)).toContain('three')
+ expect(out.newer).toBe(1)
+ expect(out.bad).toBeGreaterThanOrEqual(3)
+ })
+
+ it('an unknown kind from an old log is shown as other with its name kept', () => {
+ const line = `${JSON.stringify({ v: 1, t: T, kind: 'telepathy', level: 'info', text: 'hello' })}\n`
+
+ expect(decodeEvents(line).items[0]).toMatchObject({ kind: 'other', text: '[telepathy] hello' })
+ })
+
+ it('de-duplicates one observation logged by two consoles, and caps the retained log', () => {
+ const twice = encodeEvent(ev('same', 0), 'a') + encodeEvent(ev('same', 0), 'b')
+
+ expect(decodeEvents(twice).items).toHaveLength(1)
+
+ const many = Array.from({ length: MAX_LOG + 50 }, (_, i) => encodeEvent(ev(`e${i}`, i))).join('')
+
+ expect(decodeEvents(many, 50_000_000).items).toHaveLength(MAX_LOG)
+ expect(decodeEvents(many, 50_000_000).items.at(-1)?.text).toBe(`e${MAX_LOG + 49}`)
+ })
+
+ it('reads only the tail of a big file and drops the line it cut', () => {
+ const lines = Array.from({ length: 100 }, (_, i) => encodeEvent(ev(`event number ${i}`, i))).join('')
+ const { lines: tail } = tailLines(lines, 500)
+
+ expect(tail.length).toBeLessThan(100)
+ expect(tail.every(line => line.startsWith('{') && line.endsWith('}'))).toBe(true)
+ expect(decodeEvents(null)).toEqual({ items: [], bad: 0, newer: 0, bytes: 0 })
+ })
+
+ it('rotation keeps the newest part, from a line start, about half the cap', () => {
+ const text = Array.from({ length: 200 }, (_, i) => `{"line":${i}}\n`).join('')
+ const kept = keepNewestHalf(text, 1000)
+
+ expect(kept.length).toBeLessThanOrEqual(520)
+ expect(kept.startsWith('{')).toBe(true)
+ expect(kept.endsWith('{"line":199}\n')).toBe(true)
+ expect(keepNewestHalf('short\n', 1000)).toBe('short\n')
+ })
+
+ it('round-trips 500 random events', () => {
+ let seed = 3
+ const rnd = (n: number): number => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) % n)
+ const kinds = ['swarm', 'claims', 'workflows', 'autopilot', 'anatole'] as const
+ const words = ['agent', 'failed', 'done', 'step', 'a1', 'paused', '42', 'run', 'x-y']
+ const events = Array.from({ length: 500 }, (_, i) => ev(Array.from({ length: 1 + rnd(6) }, () => words[rnd(words.length)]).join(' ') + ` #${i}`, i, { kind: kinds[rnd(kinds.length)] as ConsoleEvent['kind'] }))
+ const back = decodeEvents(events.map(e => encodeEvent(e)).join('')).items
+
+ expect(back.map(e => [e.atMs, e.kind, e.text])).toEqual(events.map(e => [e.atMs, e.kind, e.text]))
+ })
+})
+
+describe('lane lines', () => {
+ it('round-trip a span and a tick, and refuse a span that ends before it starts', () => {
+ const span = { k: 'span' as const, lane: 'ruflo:a1', group: 'ruflo' as const, label: 'coder', fromMs: 10, toMs: 20, busy: true }
+ const tick = { k: 'tick' as const, lane: 'claude:main', group: 'claude' as const, label: 'claude (main)', min: 5, n: 3, tools: { Bash: 2, Read: 1 } }
+
+ expect(decodeLane(encodeLane(span).trim())).toEqual(span)
+ expect(decodeLane(encodeLane(tick).trim())).toEqual(tick)
+ expect(decodeLane(encodeLane({ ...span, fromMs: 30 }).trim())).toBeNull()
+ expect(decodeLane('{"v":9,"t":"span"}')).toBe('newer')
+ expect(decodeLanes(`${encodeLane(span)}garbage\n${encodeLane(tick)}`).bad).toBe(1)
+ })
+})
+
+describe('prefs', () => {
+ it('round-trips searches, pins and rules and enforces every limit', () => {
+ const prefs = {
+ searches: Array.from({ length: MAX_SEARCHES + 5 }, (_, i) => ({ name: `s${i}`, q: `kind:swarm w${i}` })),
+ pins: Array.from({ length: MAX_PINS + 5 }, (_, i) => ({ atMs: T + i, kind: 'swarm' as const, text: `p${i}`, level: 'info' as const })),
+ rules: Array.from({ length: MAX_RULES + 5 }, (_, i) => ({ name: `r${i}`, q: `level:bad r${i}` })),
+ }
+ const read = decodePrefs(encodePrefs(prefs))
+
+ expect(read.prefs.searches).toHaveLength(MAX_SEARCHES)
+ expect(read.prefs.pins).toHaveLength(MAX_PINS)
+ expect(read.prefs.rules).toHaveLength(MAX_RULES)
+ expect(read.problem).toBeNull()
+ })
+
+ it('tolerates damage, leaves a newer file alone, masks what it reads, and an absent file is empty', () => {
+ expect(decodePrefs('{broken').problem).not.toBeNull()
+ expect(decodePrefs('[1]').problem).not.toBeNull()
+ expect(decodePrefs(JSON.stringify({ v: 2, searches: [] }))).toMatchObject({ isForeign: true })
+ expect(decodePrefs(null).prefs).toEqual(emptyPrefs())
+ expect(decodePrefs(JSON.stringify({ v: 1, searches: [{ name: 'x', q: 'token=abc123def456 go' }, { name: 3 }], pins: [{ atMs: 'no' }] })).prefs.searches[0]?.q).not.toContain('abc123def456')
+ })
+})
+
+describe('hostile times and counts in the history files (#3817 class)', () => {
+ it('refuses a time past what Date holds, so no page ever calls toISOString on it', () => {
+ expect(decodeEvent('{"v":1,"t":1e300,"kind":"swarm","text":"x"}')).toBeNull()
+ expect(decodeEvent('{"v":1,"t":9e15,"kind":"swarm","text":"x"}')).toBeNull()
+ expect(decodeLane('{"v":1,"t":"span","l":"a","g":"claude","n":"a","a":0,"b":1e300,"y":1}')).toBeNull()
+ expect((decodeEvent('{"v":1,"t":1700000000000,"kind":"swarm","text":"x"}') as ConsoleEvent).atMs).toBe(1700000000000)
+
+ const prefs = decodePrefs(JSON.stringify({ v: 1, pins: [{ atMs: 1e300, kind: 'swarm', text: 'x' }, { atMs: 5, kind: 'swarm', text: 'y' }] }))
+
+ expect(prefs.prefs.pins.map(pin => pin.text)).toEqual(['y'])
+ })
+
+ it('clamps a lane tick count to a bounded whole number', () => {
+ const row = decodeLane('{"v":1,"t":"tick","l":"a","g":"claude","n":"a","m":5,"c":1e300,"tools":{"x":1e300}}')
+
+ expect(row !== null && row !== 'newer' && row.k === 'tick' && row.n <= 1e12 && (row.tools.x ?? 0) <= 1e12).toBe(true)
+ })
+})
diff --git a/plugins/ruflo-console/tests/events-sweep.spec.ts b/plugins/ruflo-console/tests/events-sweep.spec.ts
new file mode 100644
index 0000000000..d66b6e7c59
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-sweep.spec.ts
@@ -0,0 +1,149 @@
+/**
+ * The sweep (ADR-474 review): every button on the Events and the Timeline page, in a state that shows all of them, is pressed once on
+ * a fresh page, and each must change something (a filter, a cursor, a flag, a saved list) or say something (a line, a card, a view).
+ * A chip that is already on is exempt. Also: no two buttons share a key, and no two buttons on a page share a hotkey.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { activityOf } from '../hooks/activity-live'
+import { eventsModel, eventsUi } from '../hooks/events-ui'
+import { timelineModel, timelineUi } from '../hooks/timeline-ui'
+import { eventsView } from '../hooks/views/events'
+import { timelineView } from '../hooks/views/timeline'
+import { buttonOf, flat } from './fixtures/wf-drill-world'
+import { rig, T } from './fixtures/ev-rig'
+
+type Rig = ReturnType<typeof rig>
+
+const snap = (w: Rig): string => {
+ const e = eventsUi(w.state)
+ const t = timelineUi(w.state)
+ const a = activityOf(w.state)
+
+ return JSON.stringify([{ ...e, parsed: e.parsed.source, memo: null, memoKey: '', mutedKinds: [...e.mutedKinds], mutedTemplates: [...e.mutedTemplates], expanded: [...e.expanded] }, { ...t, collapsed: [...t.collapsed], memo: null, memoKey: '' }, a.prefs, w.state.eventFilter, w.asked.length, w.said.length, w.views.length])
+}
+
+const richEvents = (w: Rig): void => {
+ const first = eventsModel(w.state, T).rows.find(row => row.members.length > 1) ?? eventsModel(w.state, T).rows[3]!
+
+ eventsUi(w.state).open = first.id
+ eventsUi(w.state).narrowed = null
+ eventsUi(w.state).mutedKinds.add('tools')
+ eventsUi(w.state).query = 'kind:swarm'
+}
+
+const richTimeline = (w: Rig): void => {
+ const m = timelineModel(w.state, T)
+
+ timelineUi(w.state).open = m.lanes.find(lane => lane.group === 'ruflo')!.lane
+ timelineUi(w.state).offsetMs = 120_000
+}
+
+const pages = [
+ { name: 'events', make: (w: Rig) => eventsView(w.ctx), prep: richEvents },
+ { name: 'timeline', make: (w: Rig) => timelineView(w.ctx), prep: richTimeline },
+] as const
+
+describe('every button does something', () => {
+ for (const page of pages) {
+ const probe = rig(100, { events: 200 })
+
+ page.prep(probe)
+
+ const buttons = flat(page.make(probe)).filter(node => node.kind === 'Button')
+ const keys = buttons.map(node => String(node.props.key))
+
+ it(`${page.name}: keys and hotkeys are unique, and ${keys.length} buttons are found`, () => {
+ expect(new Set(keys).size).toBe(keys.length)
+
+ const hot = buttons.filter(node => node.props.hotkey !== undefined).map(node => String(node.props.hotkey))
+
+ expect(new Set(hot).size).toBe(hot.length)
+ expect(keys.length).toBeGreaterThan(20)
+ })
+
+ for (const key of keys) {
+ it(`${page.name}: ${key}`, async () => {
+ const w = rig(100, { events: 200 })
+
+ page.prep(w)
+
+ const target = buttonOf(page.make(w), key)
+
+ if (target === undefined) throw new Error(`no button ${key}`)
+ if (/^ ?●/.test(String(target.props.label))) return
+
+ const before = snap(w)
+
+ ;(target.props.onPress as () => void)()
+ await new Promise(done => setTimeout(done, 0))
+ expect(snap(w), `${key} (${String(target.props.label).trim()}) did nothing`).not.toBe(before)
+ })
+ }
+ }
+})
+
+describe('layout in the busiest state, at every width and both looks', () => {
+ for (const look of ['plain', 'bbs'] as const) {
+ for (const columns of [56, 60, 72, 80, 100, 125]) {
+ it(`${look} ${columns}: detail open with a burst unfolded, 50 pins, long names, a long error; a lane open on a panned window`, async () => {
+ const { setLook } = await import('../hooks/views/common')
+ const { measure } = await import('./fixtures/wf-layout-rig')
+
+ setLook(look)
+
+ try {
+ const w = rig(columns, { events: 200 })
+ const act = activityOf(w.state)
+
+ act.prefs.pins = Array.from({ length: 50 }, (_, i) => ({ atMs: T - i, kind: 'swarm' as const, text: `pinned ${'wide '.repeat(30)} ${i}`, level: 'bad' as const }))
+ act.prefs.searches = Array.from({ length: 20 }, (_, i) => ({ name: `a very long saved search name ${i}`, q: 'level:bad' }))
+ act.prefs.rules = Array.from({ length: 10 }, (_, i) => ({ name: `a very long alert rule name ${i}`, q: 'level:bad' }))
+ richEvents(w)
+ eventsUi(w.state).expanded.add(eventsUi(w.state).open as string)
+ eventsUi(w.state).parsed = { terms: [], sinceMs: null, errors: ['x'.repeat(300)], source: '' }
+ w.actions.events.muteTemplate('agent coder-12 spawned')
+
+ const fail = (tree: unknown): string => measure(tree as never, columns).map(f => `${f.kind} ${f.width}>${f.avail} ${f.at}`).join('\n')
+
+ expect(fail(eventsView(w.ctx))).toBe('')
+ richTimeline(w)
+ expect(fail(timelineView(w.ctx))).toBe('')
+ } finally {
+ setLook('plain')
+ }
+ })
+ }
+ }
+})
+
+describe('page hotkeys against the pane (the engine: "two on one hotkey: the later wins")', () => {
+ for (const [view, own] of [['events', ['ev-', 'filter']], ['timeline', ['tl-']]] as const) {
+ it(`${view}: in the whole pane, every hotkey the page uses is won by the page's own button, not a tab`, async () => {
+ const { paneView } = await import('../hooks/views/pane')
+ const { VIEWS } = await import('../hooks/state')
+ const w = rig(125, { events: 200 })
+
+ w.state.view = view
+ richEvents(w)
+ richTimeline(w)
+
+ const buttons = flat(paneView(w.ctx)).filter(node => node.kind === 'Button' && node.props.hotkey !== undefined)
+ const winner = new Map<string, string>()
+
+ for (const node of buttons) winner.set(String(node.props.hotkey), String(node.props.key))
+
+ const pageKeys = new Set(buttons.filter(node => own.some(prefix => String(node.props.key).startsWith(prefix))).map(node => String(node.props.hotkey)))
+
+ expect(pageKeys.size).toBeGreaterThan(3)
+
+ for (const hotkey of pageKeys) expect(own.some(prefix => (winner.get(hotkey) as string).startsWith(prefix)), `${hotkey} is won by ${winner.get(hotkey)}`).toBe(true)
+
+ // The collisions with the tab keys are real, and by design: list them so a new one is a decision.
+ const tabKeys = new Set(VIEWS.map(item => item.key).filter(key => key !== ''))
+ const shadowed = [...pageKeys].filter(key => tabKeys.has(key)).sort()
+
+ expect(shadowed).toEqual(view === 'events' ? ['c', 'f', 'l', 't', 'v'] : ['b', 's'])
+ })
+ }
+})
diff --git a/plugins/ruflo-console/tests/events-view.spec.ts b/plugins/ruflo-console/tests/events-view.spec.ts
new file mode 100644
index 0000000000..de95d367c9
--- /dev/null
+++ b/plugins/ruflo-console/tests/events-view.spec.ts
@@ -0,0 +1,171 @@
+/**
+ * The Events page drawn (ADR-474): rows, levels, bursts, chips, the detail pane, pins, rules and mutes, every control pressable, no
+ * duplicate keys, and every row inside the pane at 56, 60, 72, 80, 100 and 125 columns in both looks (the wf-layout harness).
+ */
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { eventsModel, eventsUi, openEventsFor } from '../hooks/events-ui'
+import { setLook } from '../hooks/views/common'
+import { eventsView } from '../hooks/views/events'
+import { buttonOf, click, flat, words } from './fixtures/wf-drill-world'
+import { measure } from './fixtures/wf-layout-rig'
+import { rig, T, WIDTHS } from './fixtures/ev-rig'
+
+afterEach(() => setLook('plain'))
+
+const report = (found: ReturnType<typeof measure>): string => found.map(f => `${f.kind} ${f.width}>${f.avail} ${f.at}`).join('\n')
+const keys = (tree: unknown): string[] => flat(tree).filter(el => el.kind === 'Button').map(el => String(el.props.key))
+
+describe('layout', () => {
+ for (const look of ['plain', 'bbs'] as const) {
+ for (const columns of WIDTHS) {
+ it(`every row fits ${columns} columns (${look}): chips, tools, query, rows, detail, pins, pages`, () => {
+ setLook(look)
+
+ const w = rig(columns)
+ const first = eventsModel(w.state, T).rows[0]!
+
+ expect(report(measure(eventsView(w.ctx), columns))).toBe('')
+
+ eventsUi(w.state).open = first.id
+ eventsUi(w.state).parsed = { terms: [], sinceMs: null, errors: ['⚠ a long problem '.repeat(8)], source: '' }
+ w.actions.events.muteKind('tools')
+ w.actions.events.muteTemplate('ISSUE-1234 progress')
+ expect(report(measure(eventsView(w.ctx), columns))).toBe('')
+ })
+ }
+ }
+
+ it('no two buttons share a key, and a very long event cannot widen a row', () => {
+ const w = rig(56)
+
+ w.act.log.push({ atMs: T, kind: 'swarm', text: 'W'.repeat(900) })
+ w.act.version++
+
+ const tree = eventsView(w.ctx)
+
+ expect(new Set(keys(tree)).size).toBe(keys(tree).length)
+ expect(report(measure(tree, 56))).toBe('')
+ })
+})
+
+describe('hotkeys', () => {
+ it('every hotkey is one digit or lowercase letter (the engine skips a page whose hotkey is anything else)', () => {
+ const w = rig(100)
+
+ w.actions.events.open(eventsModel(w.state, T).rows[0]!.id)
+
+ for (const el of flat(eventsView(w.ctx)).filter(item => item.kind === 'Button' && item.props.hotkey !== undefined)) expect(String(el.props.hotkey)).toMatch(/^[0-9a-z]$/)
+ })
+})
+
+describe('behaviour', () => {
+ it('shows a level mark, the kind and a burst count, and 12 rows a page with older and newer', () => {
+ const w = rig(100, { events: 200 })
+ const text = words(eventsView(w.ctx))
+
+ expect(text).toContain('✖')
+ expect(text).toContain('older ▸')
+ expect(flat(eventsView(w.ctx)).filter(el => el.kind === 'Button' && String(el.props.key).startsWith('ev-open-'))).toHaveLength(12)
+ expect(text).toContain('page 1/')
+ })
+
+ it('level and kind chips filter and count; a query narrows and shows its error inline; clear puts it all back', () => {
+ const w = rig(100)
+ const all = eventsModel(w.state, T).shown.length
+
+ click(eventsView(w.ctx), 'ev-level-bad')
+ const bad = eventsModel(w.state, T).shown.length
+
+ expect(bad).toBeGreaterThan(0)
+ expect(bad).toBeLessThan(all)
+ expect(words(eventsView(w.ctx))).toContain('bad')
+
+ w.actions.events.query('kind:swarm since:soon')
+ expect(words(eventsView(w.ctx))).toContain('since: wants')
+ click(eventsView(w.ctx), 'ev-clear')
+ expect(eventsModel(w.state, T).shown).toHaveLength(all)
+ })
+
+ it('pause freezes the list and counts what arrived; resume shows it', () => {
+ const w = rig(100)
+
+ click(eventsView(w.ctx), 'ev-pause')
+ w.act.log.push({ atMs: T, kind: 'swarm', text: 'later one' }, { atMs: T, kind: 'swarm', text: 'later two' })
+ w.act.version++
+ expect(eventsModel(w.state, T).unread).toBe(2)
+ expect(eventsModel(w.state, T).shown.some(e => e.text === 'later one')).toBe(false)
+ expect(words(eventsView(w.ctx))).toContain('paused (2 new)')
+ click(eventsView(w.ctx), 'ev-pause')
+ expect(eventsModel(w.state, T).shown.some(e => e.text === 'later one')).toBe(true)
+ })
+
+ it('the opened event shows its words, source, level, and the 5 events either side; follow, mute, pin and copy act', async () => {
+ const w = rig(100)
+ const row = eventsModel(w.state, T).rows[6]!
+
+ w.actions.events.open(row.id)
+
+ const tree = eventsView(w.ctx)
+
+ expect(words(tree)).toContain('around it (5 before, 5 after)')
+ expect(new Set(keys(tree)).size).toBe(keys(tree).length)
+ click(tree, 'ev-pin')
+ expect(w.act.prefs.pins).toHaveLength(2)
+ click(eventsView(w.ctx), 'ev-copy')
+ await new Promise(done => setTimeout(done, 0))
+ expect(w.said.at(-1)).toContain(row.event.kind)
+ click(eventsView(w.ctx), 'ev-mute-kind')
+ expect(eventsUi(w.state).mutedKinds.has(row.event.kind)).toBe(true)
+ w.actions.events.unmute()
+ expect(eventsUi(w.state).mutedKinds.size).toBe(0)
+ })
+
+ it('follow keeps one ref and what is near it; the Timeline link sets the same follow and window', () => {
+ const w = rig(100)
+
+ openEventsFor(w.state, 'agent:coder-12', { fromMs: T - 600_000, toMs: T })
+ expect(eventsUi(w.state).followRef).toBe('agent:coder-12')
+ expect(eventsModel(w.state, T).shown.length).toBeGreaterThan(0)
+ expect(eventsModel(w.state, T).shown.length).toBeLessThanOrEqual(120)
+ expect(words(eventsView(w.ctx))).toContain('following agent:coder-12')
+ })
+
+ it('saved searches run, delete and are capped; rules add and remove; limits say so', () => {
+ const w = rig(100)
+
+ w.actions.events.query('level:bad')
+ w.actions.events.saveSearch()
+ expect(w.act.prefs.searches.some(s => s.q === 'level:bad')).toBe(true)
+ w.actions.events.clearFilters()
+ w.actions.events.runSearch('level:bad')
+ expect(eventsUi(w.state).query).toBe('level:bad')
+ w.actions.events.addRule()
+ expect(w.act.prefs.rules).toHaveLength(2)
+ w.actions.events.removeRule('level:bad')
+ expect(w.act.prefs.rules).toHaveLength(1)
+ w.actions.events.query('')
+ w.actions.events.addRule()
+ expect(eventsUi(w.state).said).toContain('valid query')
+ w.actions.events.query('kind:swarm')
+
+ for (let i = 0; i < 12; i++) {
+ w.actions.events.query(`kind:swarm w${i}`)
+ w.actions.events.addRule()
+ }
+
+ expect(w.act.prefs.rules.length).toBeLessThanOrEqual(10)
+ })
+
+ it('an empty log says so honestly, and a filter that matches nothing says that instead', () => {
+ const empty = rig(100, { events: 0 })
+
+ expect(words(eventsView(empty.ctx))).toContain('Nothing has changed since the console loaded')
+
+ const w = rig(100)
+
+ w.actions.events.query('zzzznotthere')
+ expect(words(eventsView(w.ctx))).toContain('no event matches')
+ expect(buttonOf(eventsView(w.ctx), 'ev-forget')).toBeDefined()
+ })
+})
diff --git a/plugins/ruflo-console/tests/fixtures/activity-fs.ts b/plugins/ruflo-console/tests/fixtures/activity-fs.ts
new file mode 100644
index 0000000000..28fb281579
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/activity-fs.ts
@@ -0,0 +1,77 @@
+/**
+ * An in-memory disk for the Events and Timeline persistence tests (ADR-474): `fs` for reads and `run` for the fixed argv the console
+ * writes with (mkdir, the `sh -c 'cat >> "$1"'` append, dd, mv, rm, install). Several consoles can share one disk.
+ */
+import type { Host } from '../../hooks/host'
+
+export type Disk = { files: Map<string, string>; dirs: Set<string>; links: Set<string>; runs: (readonly string[])[]; failAppend: boolean }
+
+export const newDisk = (files: Record<string, string> = {}): Disk => ({ files: new Map(Object.entries(files)), dirs: new Set(['/work', '/work/proj']), links: new Set(), runs: [], failAppend: false })
+
+export function hostOn(disk: Disk): Pick<Host, 'fs' | 'run'> {
+ return {
+ fs: {
+ read: async path => {
+ const found = disk.files.get(path)
+
+ if (found === undefined) throw new Error('missing')
+
+ return found
+ },
+ stat: async path => (disk.links.has(path) ? { isLink: true, kind: 'file', size: 0 } : disk.files.has(path) ? { kind: 'file', size: disk.files.get(path)!.length, mtimeMs: 1 } : disk.dirs.has(path) ? { kind: 'dir' } : undefined),
+ list: async () => [],
+ },
+ run: async (argv, _timeout, stdin = '') => {
+ disk.runs.push(argv)
+
+ const out = (exitCode: number) => ({ exitCode, stdout: '', stderr: '', isStdoutTruncated: false, isStderrTruncated: false })
+
+ if (argv[0] === 'mkdir') {
+ let at = ''
+
+ for (const part of (argv[argv.length - 1] as string).split('/').filter(Boolean)) disk.dirs.add((at += `/${part}`))
+
+ return out(0)
+ }
+
+ if (argv[0] === 'dd') {
+ const path = (argv.find(arg => arg.startsWith('of=')) as string).slice(3)
+
+ if (argv.includes('conv=excl') && disk.files.has(path)) return out(1)
+ if (argv.includes('oflag=append')) {
+ if (disk.failAppend) return out(1)
+ disk.files.set(path, (disk.files.get(path) ?? '') + stdin)
+
+ return out(0)
+ }
+
+ disk.files.set(path, stdin)
+
+ return out(0)
+ }
+
+ if (argv[0] === 'install') {
+ disk.files.set(argv[argv.length - 1] as string, stdin)
+
+ return out(0)
+ }
+
+ if (argv[0] === 'rm') {
+ for (const path of argv.slice(3)) disk.files.delete(path)
+
+ return out(0)
+ }
+
+ if (argv[0] === 'mv') {
+ const [from, to] = [argv[3] as string, argv[4] as string]
+
+ disk.files.set(to, disk.files.get(from) ?? '')
+ disk.files.delete(from)
+
+ return out(0)
+ }
+
+ return out(127)
+ },
+ }
+}
diff --git a/plugins/ruflo-console/tests/fixtures/ev-rig.ts b/plugins/ruflo-console/tests/fixtures/ev-rig.ts
new file mode 100644
index 0000000000..0fe97e6b92
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/ev-rig.ts
@@ -0,0 +1,58 @@
+/**
+ * A recording Events/Timeline page rig (ADR-474): a state with a log and lanes in it, the real actions over a stub host, and a Ctx
+ * whose kit records elements, so a test can press a button by key and the layout meter (wf-layout-rig) can measure every row.
+ */
+import { activityOf, append } from '../../hooks/activity-live'
+import type { ConsoleEvent } from '../../hooks/data/events'
+import { loadRows } from '../../hooks/data/timeline-model'
+import { eventsActions } from '../../hooks/events-ui'
+import type { Host } from '../../hooks/host'
+import { newState } from '../../hooks/state'
+import { timelineActions } from '../../hooks/timeline-ui'
+import { watchActions } from '../../hooks/watch'
+import type { Actions, Ctx } from '../../hooks/views/common'
+import { kit } from './wf-drill-world'
+
+export const T = Math.floor(Date.now() / 60_000) * 60_000
+export const WIDTHS = [56, 60, 72, 80, 100, 125] as const
+
+const KINDS: ConsoleEvent['kind'][] = ['swarm', 'claims', 'workflows', 'autopilot', 'anatole', 'tools', 'learning']
+const LINES = ['agent coder-12 spawned (coder) with a rather long descriptive name that goes on and on', 'run wf_alpha_build finished: 3 of 3 agents done', 'step s7 failed: tests red in packages/very/long/path/to/some/module/file.spec.ts', 'Anatole blocked Bash: rule r-exfil (high)', 'ISSUE-1234 progress 40%', '+2 patterns learned']
+
+export function rig(columns: number, opts: { events?: number; open?: string; lanes?: boolean } = {}) {
+ const state = newState({})
+
+ state.cwd = '/work/proj'
+ state.loadedAtMs = T - 3_600_000
+ state.snapshot = null
+
+ const act = activityOf(state)
+ const log: ConsoleEvent[] = Array.from({ length: opts.events ?? 120 }, (_, i) => ({ atMs: T - (opts.events ?? 120) * 20_000 + i * 20_000, kind: KINDS[i % KINDS.length] as ConsoleEvent['kind'], text: `${LINES[i % LINES.length]} #${Math.floor(i / 7)}`, ...(i % 5 === 0 && { agentId: 'coder-12' }), ...(i % 3 === 0 && { src: 'autopilot' }) }))
+
+ append(act, log)
+ act.loaded.isLoaded = true
+ act.prefs.searches = Array.from({ length: 8 }, (_, i) => ({ name: `saved search number ${i}`, q: `kind:swarm level:bad s${i}` }))
+ act.prefs.rules = [{ name: 'bad swarm things', q: 'level:bad' }]
+ act.prefs.pins = [{ atMs: T - 5000, kind: 'swarm', text: 'a pinned event with a long text '.repeat(6), level: 'warn' }]
+
+ if (opts.lanes !== false) {
+ const rows = ['alpha-agent-with-a-long-name', 'beta', 'gamma', 'delta', 'epsilon'].flatMap((label, i) => [{ k: 'span' as const, lane: `ruflo:${i}`, group: 'ruflo' as const, label, fromMs: T - 14 * 60_000 + i * 30_000, toMs: T - 6 * 60_000 + i * 30_000, busy: i % 2 === 0 }, { k: 'span' as const, lane: `workflow:wf_a/${i}`, group: 'workflow' as const, label: `wf_alpha_build/agent-${i}`, fromMs: T - 12 * 60_000, toMs: T - 3 * 60_000, busy: true }])
+
+ loadRows(act.lanes, [...rows, { k: 'tick', lane: 'claude:main', group: 'claude', label: 'claude (main)', min: Math.floor(T / 60_000) - 4, n: 7, tools: { Bash: 5, Read: 2 } }])
+ }
+
+ const asked: unknown[] = []
+ const said: string[] = []
+ const host = { fs: { stat: async () => undefined, read: async () => '', list: async () => [] }, run: async () => ({ exitCode: 0, stdout: '', stderr: '' }), fillPrompt: async (text: string) => (said.push(text), true), invalidate: () => undefined } as unknown as Host
+ const views: string[] = []
+ const actions = {
+ events: eventsActions(state, host, () => undefined, spec => void asked.push(spec), question => void said.push(question)),
+ timeline: timelineActions(state, host, () => undefined, id => void views.push(id), spec => void asked.push(spec), question => void said.push(question)),
+ watch: watchActions(state, () => undefined, question => void said.push(question)),
+ filter: () => void said.push('filter cycled'),
+ view: (id: string) => void views.push(id),
+ } as unknown as Actions
+ const ctx: Ctx = { kit, state, nowMs: T, columns, pictures: new Map(), act: actions }
+
+ return { state, act, ctx, asked, said, views, actions }
+}
diff --git a/plugins/ruflo-console/tests/timeline-model.spec.ts b/plugins/ruflo-console/tests/timeline-model.spec.ts
new file mode 100644
index 0000000000..722f2d9a98
--- /dev/null
+++ b/plugins/ruflo-console/tests/timeline-model.spec.ts
@@ -0,0 +1,167 @@
+/**
+ * The Timeline's data (ADR-474): spans from samples and intervals (idempotent), tool calls per minute, windows and zoom, lanes with
+ * busy shares, sorting, the parallelism strip, idle gaps, the busiest minute, event markers on lanes, the axis, and the lines.
+ */
+import { describe, expect, it } from 'vitest'
+
+import { buildLines, runsOf } from '../hooks/data/timeline-lines'
+import type { ConsoleEvent } from '../hooks/data/events'
+import { addTools, axisLine, busiestMinute, cellsOf, clockOf, completeTicks, concurrency, idleGaps, lanesIn, lastProblem, loadRows, markerIndex, newLaneStore, observe, setInterval, sortLanes, trim, windowOf, zoomed } from '../hooks/data/timeline-model'
+
+const T = Date.UTC(2026, 9, 7, 12)
+const M = 60_000
+const sample = (lane: string, busy: boolean) => ({ lane: `ruflo:${lane}`, group: 'ruflo' as const, label: lane, busy })
+
+describe('spans', () => {
+ it('a status read opens a span; a change closes it and returns the row to persist; a vanished lane closes at now', () => {
+ const store = newLaneStore()
+
+ expect(observe(store, 'ruflo', [sample('a', true)], T)).toEqual([])
+ expect(observe(store, 'ruflo', [sample('a', true)], T + M)).toEqual([])
+
+ const closed = observe(store, 'ruflo', [sample('a', false)], T + 2 * M)
+
+ expect(closed).toMatchObject([{ k: 'span', lane: 'ruflo:a', fromMs: T, toMs: T + 2 * M, busy: true }])
+ expect(observe(store, 'ruflo', [], T + 5 * M)).toMatchObject([{ busy: false, fromMs: T + 2 * M, toMs: T + 5 * M }])
+ expect(store.open.size).toBe(0)
+ })
+
+ it('an interval is stored once however many reads show it; running is held open', () => {
+ const store = newLaneStore()
+
+ expect(setInterval(store, 'workflow:r/a', 'workflow', 'r/a', T, null)).toBeNull()
+ expect(setInterval(store, 'workflow:r/a', 'workflow', 'r/a', T, T + M)).toMatchObject({ k: 'span' })
+ expect(setInterval(store, 'workflow:r/a', 'workflow', 'r/a', T, T + M)).toBeNull()
+ expect(store.spans).toHaveLength(1)
+ expect(setInterval(store, 'x', 'mission', 'x', 0, 5)).toBeNull()
+ })
+
+ it('persisted rows load once and are not duplicated by a later interval of the same start', () => {
+ const store = newLaneStore()
+
+ loadRows(store, [{ k: 'span', lane: 'autopilot:s1', group: 'autopilot', label: 's1', fromMs: T, toMs: T + M, busy: true }])
+ expect(setInterval(store, 'autopilot:s1', 'autopilot', 's1', T, T + M)).toBeNull()
+ })
+})
+
+describe('tool calls', () => {
+ it('count per minute by tool, new calls only, finished minutes persisted once', () => {
+ const store = newLaneStore()
+ const calls = [{ atMs: T + 1000, tool: 'Bash' }, { atMs: T + 2000, tool: 'Bash' }, { atMs: T + M + 1000, tool: 'Read' }]
+
+ expect(addTools(store, 'claude:main', 'claude', 'claude (main)', calls, T + 90_000)).toMatchObject([{ k: 'tick', n: 2, tools: { Bash: 2 } }])
+ expect(addTools(store, 'claude:main', 'claude', 'claude (main)', calls, T + 90_000)).toEqual([])
+ expect(completeTicks(store, T + 3 * M)).toMatchObject([{ k: 'tick', n: 1, tools: { Read: 1 } }])
+ trim(store, T + 30 * 86_400_000)
+ expect(store.ticks.size).toBe(0)
+ })
+})
+
+describe('windows', () => {
+ it('a window ends at now minus the pan, a session is as long as the console has been up, and zoom steps through the list', () => {
+ expect(windowOf('15m', 0, T, T - 1)).toMatchObject({ fromMs: T - 15 * M, toMs: T, spanMs: 15 * M })
+ expect(windowOf('1h', 30 * M, T, T)).toMatchObject({ toMs: T - 30 * M })
+ expect(windowOf('session', 0, T, T - 10 * M).spanMs).toBe(10 * M)
+ expect(windowOf('session', 0, T, T).spanMs).toBe(M)
+ expect(zoomed('15m', 1)).toBe('1h')
+ expect(zoomed('15m', -1)).toBe('5m')
+ expect(zoomed('5m', -1)).toBe('5m')
+ expect(zoomed('24h', 1)).toBe('24h')
+ })
+})
+
+function world() {
+ const store = newLaneStore()
+
+ loadRows(store, [
+ { k: 'span', lane: 'ruflo:a', group: 'ruflo', label: 'alpha', fromMs: T, toMs: T + 10 * M, busy: true },
+ { k: 'span', lane: 'ruflo:a', group: 'ruflo', label: 'alpha', fromMs: T + 10 * M, toMs: T + 20 * M, busy: false },
+ { k: 'span', lane: 'ruflo:b', group: 'ruflo', label: 'beta', fromMs: T, toMs: T + 20 * M, busy: true },
+ { k: 'tick', lane: 'claude:main', group: 'claude', label: 'claude (main)', min: Math.floor(T / M) + 3, n: 5, tools: { Bash: 4, Read: 1 } },
+ { k: 'tick', lane: 'claude:main', group: 'claude', label: 'claude (main)', min: Math.floor(T / M) + 4, n: 9, tools: { Bash: 9 } },
+ ])
+
+ const win = { fromMs: T, toMs: T + 20 * M }
+
+ return { store, win, lanes: lanesIn(store, win, T + 20 * M) }
+}
+
+describe('lanes, parallelism, gaps', () => {
+ it('busy shares, longest stretch, tool counts, and sorts', () => {
+ const { lanes } = world()
+ const alpha = lanes.find(l => l.lane === 'ruflo:a')
+ const claude = lanes.find(l => l.lane === 'claude:main')
+
+ expect(alpha).toMatchObject({ busyPct: 50, longestMs: 10 * M, observedMs: 20 * M })
+ expect(lanes.find(l => l.lane === 'ruflo:b')?.busyPct).toBe(100)
+ expect(claude).toMatchObject({ calls: 14, busyPct: null })
+ expect(claude?.byTool[0]).toEqual(['Bash', 13])
+ expect(sortLanes(lanes, 'busy')[0]?.lane).toBe('ruflo:b')
+ expect(sortLanes(lanes, 'calls')[0]?.lane).toBe('claude:main')
+ expect(sortLanes(lanes, 'name')[0]?.label).toBe('alpha')
+ expect(sortLanes(lanes, 'recent')).toHaveLength(3)
+ })
+
+ it('counts lanes busy at once, with the peak and the mean over busy bars', () => {
+ const { store, win, lanes } = world()
+ const conc = concurrency(lanes, win, store, 20)
+
+ // Two busy lanes, and the tool-call lane counts as busy in the two minutes it called a tool (a call is activity).
+ expect(conc.peak).toBe(3)
+ expect(conc.counts.slice(0, 10).every(n => n >= 2)).toBe(true)
+ expect(conc.counts[15]).toBe(1)
+ expect(conc.mean).toBeGreaterThan(1)
+ expect(conc.peakAtMs).toBe(T + 3 * M)
+ })
+
+ it('finds a lane idle for 5 minutes or more while another was busy, and the busiest minute', () => {
+ const { store, win, lanes } = world()
+ const gaps = idleGaps(lanes, win, store)
+
+ expect(gaps).toHaveLength(1)
+ expect(gaps[0]).toMatchObject({ lane: 'ruflo:a' })
+ expect(gaps[0]!.toMs - gaps[0]!.fromMs).toBeGreaterThanOrEqual(5 * M)
+ expect(idleGaps(lanes, win, store, 30 * M)).toEqual([])
+ expect(busiestMinute(store, win)).toEqual({ atMs: (Math.floor(T / M) + 4) * M, n: 9 })
+ expect(busiestMinute(newLaneStore(), win)).toBeNull()
+ })
+
+ it('cells say busy, idle, tool or unobserved', () => {
+ const { store, win, lanes } = world()
+ const cells = cellsOf(lanes.find(l => l.lane === 'ruflo:a')!, win, 20, store)
+
+ expect(cells[2]).toBe(2)
+ expect(cells[15]).toBe(1)
+ expect([...cellsOf(lanes.find(l => l.lane === 'claude:main')!, win, 20, store)].filter(n => n === 3)).toHaveLength(2)
+ })
+})
+
+describe('events on lanes, the axis and the lines', () => {
+ const bad = (ref: string, atS: number, text = 'x failed'): ConsoleEvent => ({ kind: 'swarm', text, atMs: T + atS * 1000, ref })
+
+ it('a warn or bad event lands on its lane by ref, else on the top lane, and info is not drawn', () => {
+ const { win, lanes } = world()
+ const events = [bad('agent:a', 60), bad('run:zzz', 120), { kind: 'swarm' as const, text: 'topology mesh', atMs: T + 90_000, ref: 'agent:a' }]
+
+ expect((markerIndex(events, lanes, win, 20).get('ruflo:a') ?? []).filter(x => x !== null)).toEqual(['bad'])
+ expect((markerIndex(events, lanes, win, 20).get('') ?? []).filter(x => x !== null)).toEqual(['bad'])
+ expect(lastProblem(events, T + 200_000)?.atMs).toBe(T + 120_000)
+ expect(lastProblem(events, T)).toBeNull()
+ })
+
+ it('the axis labels fit and the lines carry the legend facts', () => {
+ const { store, win, lanes } = world()
+
+ expect(axisLine(win, 60)).toHaveLength(60)
+ expect(axisLine(win, 60)).toMatch(/\d\d:\d\d/)
+ expect(clockOf(T)).toMatch(/^\d\d:\d\d$/)
+
+ const lines = buildLines([{ type: 'group', group: 'ruflo', count: 2, isOpen: true }, { type: 'lane', lane: lanes[0]! }], store, [bad('agent:a', 60)], lanes, win, concurrency(lanes, win, store, 20), 80, lanes[0]!.lane)
+ const text = lines.map(line => line.label + line.cells.map(cell => cell.ch).join('')).join('\n')
+
+ expect(lines.map(line => line.kind)).toEqual(['axis', 'events', 'group', 'lane', 'conc'])
+ expect(text).toContain('█')
+ expect(text).toContain('▲')
+ expect(runsOf(lines[3]!.cells).every((run, i, all) => i === 0 || run.tone !== all[i - 1]!.tone)).toBe(true)
+ })
+})
diff --git a/plugins/ruflo-console/tests/timeline-view.spec.ts b/plugins/ruflo-console/tests/timeline-view.spec.ts
new file mode 100644
index 0000000000..32ab37e0d0
--- /dev/null
+++ b/plugins/ruflo-console/tests/timeline-view.spec.ts
@@ -0,0 +1,172 @@
+/**
+ * The Timeline page drawn (ADR-474): groups, the text lines that carry what the picture carries, window, zoom, pan and sort controls,
+ * a lane opened for detail, the cross-link to Events, export, paging past 12 lanes, and every row inside the pane at 56 to 125 columns.
+ */
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { activityOf } from '../hooks/activity-live'
+import { eventsUi } from '../hooks/events-ui'
+import { loadRows } from '../hooks/data/timeline-model'
+import { timelineModel, timelineUi } from '../hooks/timeline-ui'
+import { setLook } from '../hooks/views/common'
+import { linesFor } from '../hooks/views/timeline-lines'
+import { timelineView } from '../hooks/views/timeline'
+import { linesPicture } from '../hooks/gfx/ev-charts'
+import { click, flat, words } from './fixtures/wf-drill-world'
+import { measure } from './fixtures/wf-layout-rig'
+import { rig, T, WIDTHS } from './fixtures/ev-rig'
+
+afterEach(() => setLook('plain'))
+
+const report = (found: ReturnType<typeof measure>): string => found.map(f => `${f.kind} ${f.width}>${f.avail} ${f.at}`).join('\n')
+const keys = (tree: unknown): string[] => flat(tree).filter(el => el.kind === 'Button').map(el => String(el.props.key))
+
+describe('layout', () => {
+ for (const look of ['plain', 'bbs'] as const) {
+ for (const columns of WIDTHS) {
+ it(`every row fits ${columns} columns (${look}), also with a lane open and every window`, () => {
+ setLook(look)
+
+ const w = rig(columns)
+
+ expect(report(measure(timelineView(w.ctx), columns))).toBe('')
+
+ const lane = timelineModel(w.state, T).lanes[0]!
+
+ w.actions.timeline.open(lane.lane)
+ for (const id of ['5m', '1h', '24h', 'session'] as const) {
+ w.actions.timeline.window(id)
+ expect(report(measure(timelineView(w.ctx), columns))).toBe('')
+ }
+ })
+ }
+ }
+})
+
+describe('hotkeys', () => {
+ it('every hotkey is one digit or lowercase letter, and none repeats on the page', () => {
+ const w = rig(100)
+
+ w.actions.timeline.open('ruflo:0')
+
+ const hot = flat(timelineView(w.ctx)).filter(item => item.kind === 'Button' && item.props.hotkey !== undefined).map(item => String(item.props.hotkey))
+
+ expect(hot.length).toBeGreaterThan(3)
+ for (const key of hot) expect(key).toMatch(/^[0-9a-z]$/)
+ expect(new Set(hot).size).toBe(hot.length)
+ })
+})
+
+describe('behaviour', () => {
+ it('lanes are grouped with headers; collapsing a group hides its lanes; keys are unique', () => {
+ const w = rig(100)
+ const text = words(timelineView(w.ctx))
+
+ expect(text).toContain('▾ ruflo (5)')
+ expect(text).toContain('▾ workflow (5)')
+ expect(text).toContain('alpha-agent')
+
+ click(timelineView(w.ctx), 'tl-group-ruflo')
+ expect(words(timelineView(w.ctx))).not.toContain('alpha-agent')
+ expect(words(timelineView(w.ctx))).toContain('▸ ruflo (5)')
+ expect(new Set(keys(timelineView(w.ctx))).size).toBe(keys(timelineView(w.ctx)).length)
+ })
+
+ it('the text twin carries the picture: the same lines, cell for cell', () => {
+ const w = rig(80)
+ const model = timelineModel(w.state, T)
+ const lines = linesFor(w.state, model, 80)
+ const grid = linesPicture(lines, 80)
+ const lane = lines.find(line => line.kind === 'lane')!
+ const at = lines.indexOf(lane)
+
+ expect(String.fromCodePoint(grid.glyph(lane.label.length + 1 + 3, at))).toBe(lane.cells[3]!.ch)
+
+ const text = words(timelineView(w.ctx))
+
+ expect(text).toContain('parallel')
+ expect(text).toContain('█ busy')
+ expect(text).toContain('parallel: peak')
+ })
+
+ it('zoom, pan, now, sort and window act on the model', () => {
+ const w = rig(100)
+ const ui = timelineUi(w.state)
+
+ click(timelineView(w.ctx), 'tl-zout')
+ expect(ui.window).toBe('1h')
+ click(timelineView(w.ctx), 'tl-zin')
+ click(timelineView(w.ctx), 'tl-zin')
+ expect(ui.window).toBe('5m')
+ click(timelineView(w.ctx), 'tl-back')
+ expect(ui.offsetMs).toBe(150_000)
+ click(timelineView(w.ctx), 'tl-fwd')
+ expect(ui.offsetMs).toBe(0)
+ click(timelineView(w.ctx), 'tl-fwd')
+ expect(ui.offsetMs).toBe(0)
+ ui.offsetMs = 3_600_000
+ click(timelineView(w.ctx), 'tl-now')
+ expect(ui.offsetMs).toBe(0)
+ click(timelineView(w.ctx), 'tl-sort')
+ expect(ui.sort).toBe('calls')
+ })
+
+ it('a lane opened shows spans, gaps, tools and its events; its buttons follow it on Events and go to its page', () => {
+ const w = rig(100)
+ const claude = timelineModel(w.state, T).lanes.find(l => l.group === 'claude')!
+
+ w.actions.timeline.open(claude.lane)
+
+ const text = words(timelineView(w.ctx))
+
+ expect(text).toContain('tools: Bash 5 · Read 2')
+ expect(text).toContain('7 tool calls')
+
+ w.actions.timeline.open(null)
+ w.actions.timeline.open('ruflo:0')
+ expect(words(timelineView(w.ctx))).toContain('longest busy stretch')
+ click(timelineView(w.ctx), 'tl-lane-events')
+ expect(eventsUi(w.state).followRef).toBe('agent:0')
+ expect(eventsUi(w.state).narrowed).not.toBeNull()
+ expect(w.views).toContain('events')
+ click(timelineView(w.ctx), 'tl-lane-go')
+ expect(w.views.at(-1)).toBe('swarm')
+ })
+
+ it('pages past 12 lanes and builds only one page of lines', () => {
+ const w = rig(100)
+ const act = activityOf(w.state)
+
+ loadRows(act.lanes, Array.from({ length: 200 }, (_, i) => ({ k: 'span' as const, lane: `ruflo:many${i}`, group: 'ruflo' as const, label: `lane ${i}`, fromMs: T - 600_000, toMs: T, busy: true })))
+
+ const model = timelineModel(w.state, T)
+
+ expect(model.total).toBeGreaterThan(200)
+ expect(linesFor(w.state, model, 100).filter(line => line.kind === 'lane').length).toBeLessThanOrEqual(12)
+ click(timelineView(w.ctx), 'tl-next')
+ expect(timelineUi(w.state).page).toBe(1)
+ })
+
+ it('an empty window says so honestly; jump to the last problem moves the window and says where', () => {
+ const empty = rig(100, { lanes: false })
+
+ empty.state.snapshot = {} as never
+
+ expect(words(timelineView(empty.ctx))).toContain('No lane was observed in this window')
+
+ const w = rig(100)
+
+ w.actions.timeline.problem()
+ expect(timelineUi(w.state).said).toMatch(/jumped to|no warn or bad/)
+ })
+
+ it('export asks through the confirm card with a checked path, and a bad path says why', async () => {
+ const w = rig(100)
+
+ await w.actions.timeline.exportTo('md', 'tl.md')
+ expect(w.asked).toHaveLength(1)
+ await w.actions.timeline.exportTo('md', '../x.md')
+ expect(w.asked).toHaveLength(1)
+ expect(timelineUi(w.state).said).toContain('..')
+ })
+})
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index d4a85e8def..235d078763 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -251,10 +251,14 @@ describe('views', () => {
test('timeline, approvals and events draw from what was seen; the drill-down opens an agent', { options: { boot: false } }, async ($, on) => {
const world = worldOf(on, RUFLO_FILES)
- mock.clock(on)
+ const clock = mock.clock(on)
await $.session.start(SESSION)
- expect((await drawn($, 'timeline')).rasters).toEqual(['title', 'gantt'])
+ // The lanes come from a status read taken on the 1.5 s activity tick (ADR-474): with the agents read, the lane picture is drawn.
+ await $.command.run(command('status'))
+ await clock.advance(2000)
+ await clock.advance(2000)
+ expect((await drawn($, 'timeline')).rasters).toEqual(['title', 'tl-picture'])
const approvals = await drawn($, 'approvals')
diff --git a/plugins/ruflo-console/tests/watch.test.ts b/plugins/ruflo-console/tests/watch.test.ts
index f103df02a6..8600712add 100644
--- a/plugins/ruflo-console/tests/watch.test.ts
+++ b/plugins/ruflo-console/tests/watch.test.ts
@@ -1,6 +1,6 @@
/**
- * The Timeline and Events pages in the pane: the look-back chips redraw the title, and the event page's kind chips, search field,
- * pause button and empty-state wording are there and answer.
+ * The Timeline and Events pages in the pane (ADR-474): the Timeline's window chips redraw the title, and the Events page's kind and level
+ * chips, search field, pause button and empty-state wording are there and answer.
*/
import type { TestBody } from 'claude-code/testing'
import { describe, expect, mock, test } from 'claude-code/testing'
@@ -26,16 +26,18 @@ async function opened($: Body[0], on: Body[1], view: string) {
}
describe('timeline and events pages', () => {
- test('timeline: the look-back chips change the window named in the title', { options: { boot: false } }, async ($, on) => {
+ test('timeline: the window chips change the window named in the title', { options: { boot: false } }, async ($, on) => {
const pane = await opened($, on, 'timeline')
const first = await pane.drawn()
- expect(keys(first)).toEqual(expect.arrayContaining(['tl-range-5', 'tl-range-15', 'tl-range-60']))
- expect(textOf(first)).toContain('last 15 min')
- await pane.press({ key: 'tl-range-60' })
- expect(textOf(await pane.drawn())).toContain('last 60 min')
- await pane.press({ key: 'tl-range-5' })
- expect(textOf(await pane.drawn())).toContain('last 5 min')
+ expect(keys(first)).toEqual(expect.arrayContaining(['tl-win-5m', 'tl-win-15m', 'tl-win-1h', 'tl-win-6h', 'tl-win-24h', 'tl-win-session', 'tl-zin', 'tl-zout', 'tl-now', 'tl-sort']))
+ expect(textOf(first)).toContain('15 min')
+ await pane.press({ key: 'tl-win-1h' })
+ expect(textOf(await pane.drawn())).toContain('1 h')
+ await pane.press({ key: 'tl-win-5m' })
+ expect(textOf(await pane.drawn())).toContain('5 min')
+ await pane.press({ key: 'tl-zout' })
+ expect(textOf(await pane.drawn())).toContain('15 min')
await pane.unmount()
})
@@ -43,7 +45,7 @@ describe('timeline and events pages', () => {
const pane = await opened($, on, 'events')
const first = await pane.drawn()
- expect(keys(first)).toEqual(expect.arrayContaining(['ev-kind-all', 'ev-pause']))
+ expect(keys(first)).toEqual(expect.arrayContaining(['ev-kind-all', 'ev-level-all', 'ev-win-all', 'ev-pause', 'ev-clear', 'ev-export-md', 'ev-forget']))
expect(inputKeys(first)).toContain('ev-query')
expect(textOf(first)).toContain('live')
await pane.press({ key: 'ev-pause' })
@@ -56,9 +58,8 @@ describe('timeline and events pages', () => {
const none = await pane.drawn()
expect(textOf(none)).toMatch(/no event matches|Nothing has changed/)
- expect(keys(none)).toContain('ev-clear')
await pane.press({ key: 'ev-clear' })
- expect(keys(await pane.drawn())).not.toContain('ev-clear')
+ expect(textOf(await pane.drawn())).toContain('filters cleared')
await pane.unmount()
})
})
diff --git a/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts b/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts
index 64255ca7b1..66facdfc76 100644
--- a/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts
+++ b/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts
@@ -100,3 +100,19 @@ describe('root secret ignore (#2637)', () => {
expect(result.created.files).toContain('.gitignore (updated)');
});
});
+
+describe('.claude-flow/.gitignore template (ruflo-console 0.36 history folder)', () => {
+ it('ignores console/ (the console\'s own events, lanes, prefs and exports) along with the other runtime folders', async () => {
+ const options = structuredClone(MINIMAL_INIT_OPTIONS);
+ options.targetDir = projectPath;
+ options.skipGlobalClaudeMd = true;
+
+ const result = await executeInit(options);
+
+ expect(result.success).toBe(true);
+ const lines = readFileSync(join(projectPath, '.claude-flow', '.gitignore'), 'utf8').split('\n');
+ for (const entry of ['data/', 'logs/', 'sessions/', 'neural/', 'console/', '*.log', '*.tmp']) {
+ expect(lines).toContain(entry);
+ }
+ });
+});
diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts
index 0c6bd253da..7ffabfebf1 100644
--- a/v3/@claude-flow/cli/src/init/executor.ts
+++ b/v3/@claude-flow/cli/src/init/executor.ts
@@ -1615,6 +1615,7 @@ data/
logs/
sessions/
neural/
+console/
*.log
*.tmp
`;
diff --git a/v3/docs/adr/ADR-474-events-page-capabilities.md b/v3/docs/adr/ADR-474-events-page-capabilities.md
new file mode 100644
index 0000000000..650cca3e61
--- /dev/null
+++ b/v3/docs/adr/ADR-474-events-page-capabilities.md
@@ -0,0 +1,136 @@
+# ADR 474: Console: Events and Timeline pages: capabilities
+
+Status: Accepted
+
+Date: 2026-10-07
+
+Builds on: ADR-461 (saved views and the console's own state file), ADR-466 (the autopilot journal), ADR-469 (the layout harness), ADR-473 (the bench pass)
+
+## 1. Context
+
+The Events page showed the last 300 events of this session, kept in memory only: a kind chip row, a text find, a pause, a 15-minute
+sparkline, a paged list and one expandable row. A restart emptied it. It only knew the diff of two ruflo reads and the console's own tool
+calls, it had no sense of what mattered, the find was a substring, and nothing could be followed, exported or alerted on.
+
+The Timeline page drew a gantt of ruflo agents' busy and idle status and Claude Code tool-call ticks over 5, 15 or 60 minutes, observed only
+since the console loaded, 12 lanes at most, with no history, no zoom, no events on it, and no way to ask "who was running at once".
+
+Both pages are about what happened and when, so they share one store, one write path and one idea of "the session" versus "what is kept".
+
+## 2. Decision
+
+**One bounded store** (`hooks/data/activity-store.ts`, pure schema; `hooks/activity-io.ts`, the only write path; `hooks/activity-live.ts`,
+the live pass). Three files under the project's `.claude-flow/console/`:
+
+| file | holds | cap |
+|---|---|---|
+| `events.jsonl` | one line per event | 2 MiB, then cut to the newest half |
+| `lanes.jsonl` | busy/idle spans per lane, tool calls per lane per minute | 1 MiB, same rule |
+| `events-prefs.json` | up to 20 saved searches, 50 pins, 10 alert rules | 64 kB |
+
+**Event schema** (`v: 1`): `{"v":1,"t":<ms>,"kind":"swarm|claims|federation|learning|tools|mods|missions|workflows|autopilot|anatole|notices|other",
+"level":"ok|info|warn|bad","text":"<masked, at most 240 chars>","agent"?:"","ref"?:"agent:<id>|claim:<id>|run:<id>|task:<id>|mission:<id>|step:<id>|rule:<id>","src"?:"","s"?:"<console id>"}`.
+Lane lines: `{"v":1,"t":"span","l":<lane>,"g":<group>,"n":<label>,"a":<from>,"b":<to>,"y":1|0}` and `{"v":1,"t":"tick","l","g","n","m":<minute>,"c":<calls>,"tools":{"Bash":2}}`.
+Groups: `ruflo`, `claude`, `workflow`, `mission`, `autopilot`. A line that is not JSON, is cut off, has a wrong type, or says a newer `v` is
+counted and skipped (the page says how many), never thrown on. An unknown kind from an old or newer log is read as `other` with its name kept in
+the text. A prefs file from a newer console is never written over.
+
+**One write path.** Lines are queued and written in batches (at most one write per file in flight, at most 32 kB per batch, every 4 s, 1.5 s
+tick), never one write per event. The append is one fixed argv shared with the autopilot journal (`data/append-argv.ts`: `dd of=<path> oflag=append conv=notrunc bs=1M iflag=fullblock status=none`, no shell, the path
+is one argv element). `bs=1M iflag=fullblock` makes a batch one O_APPEND write, which the kernel keeps whole when two consoles share the file; with dd's default 512-byte blocks
+1094 of 4800 lines were torn by two writers. The journal (ADR-466) had the old argv and now uses the same helper; a real-dd test with eight writers covers each. The folder is made once with `mkdir -p`; the path
+is checked for a link on the way down before every write and a link is refused. Rotation: past the cap the newest half is written to
+`<file>.tmp` (after `rm -f`, with `conv=excl`) and renamed over the file. A failed write keeps the lines queued, waits 30 s and retries; the queue
+is bounded (2000 lines) so a dead disk costs memory only up to that. Two consoles on one project may both log what both observed; the reader drops
+a line with the same second, kind and text (read-time de-duplication) and each line carries a short console id. A rotation raced by another console
+can lose the few lines that arrived in between: this is a history, not a ledger.
+
+**History on open.** The tail of each file (the last 1 MB, from a line start; the page prints the bytes read, the cap and the bad-line count)
+is parsed into a retained log of at most 10 000 events and a lane store of at most 20 000 spans. A window control: session (this console only),
+15 min, 1 h, 24 h, all kept.
+
+**Sources** (each observed, none invented; the first read of a source is a baseline and yields nothing): the diff of ruflo reads and the
+tool calls (as before); workflow runs from the Workflows read the console already holds (started, finished, failed, stuck, empty; seen only while
+the Workflows page has been read, said on the page); the autopilot's loop (start, resume, pause, stop, a step handed over, done, failed, parked,
+the kill flag); Anatole alerts (blocked or notified, with the rule id); band notices raised; permission denies; plugin and mod load changes.
+
+**Severity** (`data/event-severity.ts`, one pure function over kind and words): a failure word is `bad`, a warning word `warn`, a completion word
+`ok`, the rest `info`; "0 failed" and "no errors" are calm. An Anatole block is `bad`, a notify `warn`. Level chips with counts, a colour and mark on
+every row, a warn/bad count in the page rule and a count of unread warn/bad events.
+
+**Query language** (`data/event-query.ts`): free words (AND), `"phrase"`, `-negation`, `kind:`, `level:`, `agent:`, `src:`, `ref:`, `since:90s|15m|1h|2d`,
+`a|b` for OR inside a value, `/regex/` or `/regex/i`. A problem is an inline line under the query box and the rest still applies. A regex is refused
+over 48 characters, with a back-reference, a lookaround, more than two quantifiers (`?` counts), or a quantified group that holds a quantifier or an alternation;
+the text it runs against is cut to 200 characters; so a pattern costs at most O(n^2) of 200. Callers that scan many events also pass a time budget (120 ms):
+once it is spent a regex term stops being evaluated and the page says how many events were not searched. (An earlier cap of five quantifiers let `a*a*a*a*b` run for
+43 s over 50 kB of text and 280 ms over 200 characters; the test that found it stays.) Matches are highlighted in rows. Saved searches (20) run from chips.
+
+**Grouping and correlation.** A burst (same kind, agent and template within 30 s) is one row with `×k` and an expand. `follow <ref>` keeps one
+ref's events and anything within 30 s of them. The detail pane shows the words, level, source, ref, the entity's current state read from the snapshot
+(agent, claim, task, run, mission) with a button to its page, and the five events either side.
+
+**Live tail and actions.** j/k move a focus, pause with an unread counter, pins (50), mutes of a kind or a line template for the session (a chip that
+undoes it), copy-as-text of the focused line (masked; it is put in the prompt box, the console has no clipboard), alert rules (10): the current query
+becomes a rule evaluated over NEW events only, never history, raising a band notice through `addNotice` (one per rule per minute), export of the
+filtered events as markdown or JSONL.
+
+**Timeline.** Lanes in five collapsible groups, fed from ruflo agent statuses (sampled), Claude Code main and subagent tool calls (aggregated per
+minute), Workflow agents and mission tasks and autopilot steps (intervals already timed in data the console parsed; stored once however many reads
+show them), Anatole and other warn/bad events as markers on the owning lane or a top events lane. Windows 5 m, 15 m, 1 h, 6 h, 24 h, session;
+zoom, pan (half a window), now, start, jump to the last problem; sort by busy share, calls, name or recency; axis with local time; a parallelism strip with
+peak and mean, idle gaps (a lane idle five minutes or more while another was busy) and the busiest minute; a lane detail (spans with durations and
+gaps, tool calls by tool, longest busy stretch, its last ten events, buttons to follow it on the Events page over the same window, to its page, and to
+ask Claude); an export of lane summaries and the concurrency figures as markdown or CSV (a cell that starts `= + - @` is defused). The cross-link is
+one function (`openEventsFor`) used by both pages. The picture and the text are built from the same list of lines (`data/timeline-lines.ts`), so the
+text twin carries exactly what the picture does.
+
+**Export guard** (`data/event-export.ts`): a bare name goes under `.claude-flow/console/exports/`, a relative path under the project; `..`,
+`~`, a backslash, control characters, a path over 300 characters, a bad extension, a path outside the project, a link on the way and an existing file are
+refused before the confirm card is shown; the write is `dd conv=excl` or GNU `install -D` (the same argv as the Workflows export), content on stdin,
+masked, at most 400 kB, at most 2000 events.
+
+**Commands.** `/ruflo events [kind|level|since:15m|"query"|window <w>|clear|forget|export <path>|follow <ref>|pin|rule]` and
+`/ruflo timeline [5m|15m|1h|6h|24h|session|zoom <in|out>|follow <ref>|export <path>]`; bare, each opens its page. `forget` asks, then removes
+`events.jsonl` and `lanes.jsonl` (saved searches, pins and rules stay). `/ruflo filter <kind>` keeps working.
+
+**Keys** (buttons with hotkeys; the pane's global keys keep theirs): Events j/k move, `t` pause, `l` level, `c` clear filters, `f` kind, `v` copy;
+Timeline j/k lane, `b` `n` pan earlier or later, `s` sort, `o` open the lane (zoom, now and last problem are buttons: the engine accepts only a digit or a lowercase letter as a hotkey, and the letters left are tab keys). The brief asked for p (pause), y (copy), g/G, h/l
+and Enter; p, y, g and h are already the palette, the confirm, the Timeline tab and help, so the nearest free keys are used and the page says so on its buttons.
+
+## 3. Privacy
+
+What is persisted: masked event text (credentials, `key=value` secrets, bearer strings, JWTs, long key-like runs, home-directory user names, escapes,
+control, bidi and tag characters all removed before encoding), the kind, level, a ref, a time. No prompt, no model reply, no tool input, no file content and
+no value from a tool call: a tool event is the tool's name and the agent. Lane lines hold lane ids, labels, times and tool names with counts. Everything
+lives only in the project's `.claude-flow/console/`, never leaves the machine, is not read by any model turn, and is documented as local state.
+Retention: 2 MiB of events and 1 MiB of lanes, the newest half kept at the cap; the retained log in memory is 10 000 events.
+**Disable:** the plugin option `eventsPersist` (declared in `plugin.json`, default true; false queues and writes nothing: no event, lane, saved search, pin, rule, folder or ignore file; the pages still work for the session). Reading existing history still happens.
+**Clear:** `/ruflo events forget` or the page's "forget history" button, behind the confirm card. Saved searches, pins and rules are
+a separate file the person made; they are masked on write and on read.
+
+## 4. Consequences
+
+A restart no longer empties the Events page; a stuck run, a blocked call and a failed step are findable by level; two consoles on one project show
+each other's history after a reload. A few kilobytes are written every few seconds in a busy session, in batches. The log is a convenience history: a
+rotation raced by a second console can lose a few lines, and the pages say what was read. Workflow run events appear only while the Workflows page
+has been the page in front (that is when the console reads runs), and the Timeline says "observed since the console loaded" beside its history.
+The console writes its own `.claude-flow/console/.gitignore`, and `ruflo init` now lists `console/` in the `.claude-flow/.gitignore` template (a shipped CLI file: it needs the CLI release), so the history is not committed by accident.
+
+**Known open limits (low severity, not fixed in 0.36.0):** rotating an over-cap file keeps only its newest half and drops the rest; two consoles on one project can each overshoot the cap before either rotates; `forget history` clears the logs but keeps pins and alert rules (the person's own file); persisted mission and step text is cut to 60 characters; a permission deny is logged twice.
+
+## 5. Tests and benchmark
+
+Pure specs in `plugins/ruflo-console/tests/`: `events-severity`, `events-query` (parser, evaluator, adversarial regexes, huge inputs, a 3000-string
+property test that no query throws), `events-group`, `events-store` (round-trip property over 500 random events, corrupt and cut lines, schema skew,
+rotation, prefs limits), `events-persist` (batching, append argv, missing folder, failing disk, link refusal, bounded queue, rotation, two writers,
+history on open, the option off, rules over new events only), `events-export` (traversal, symlink, overwrite refusal, masking, CSV defusing, size cap),
+`events-rules` (also the derived sources), `events-view` and `timeline-view` (rows, controls, no duplicate keys, honest empty states, and every row
+inside the pane at 56, 60, 72, 80, 100 and 125 columns in both looks with the `wf-layout-rig` meter), `events-commands`, `timeline-model`.
+`scripts/bench-events.mjs` (plain node via tsx): load the tail of a 2 MiB log, four query shapes over 10 000 events, one Events page, one Timeline page
+over 200 lanes x 24 h, append 100 events, append 100 lane samples; `--check` fails on a missed budget.
+
+## 6. Rollback
+
+Revert the commit. The files under `.claude-flow/console/` are the console's own and are ignored by older consoles (a line of another schema is
+skipped, a prefs file of a newer schema is left alone), so a rollback needs no cleanup; `rm .claude-flow/console/events.jsonl lanes.jsonl events-prefs.json`
+removes the history.