Skip to content

armgit / ruflo

Public Imported from GitHub
0

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

feat(ruflo-console): Automation view and Learning Lab

ruv96343f8f49c1
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.ts
index 5fb683024c..3b5e13f368 100644
--- a/plugins/ruflo-console/hooks/actions.ts
+++ b/plugins/ruflo-console/hooks/actions.ts
@@ -23,6 +23,8 @@ export type ActionSpec = {
note?: string
/** How long the CLI may take; 90 s when unset. */
timeoutMs?: number
+ /** A lab entry that reads its own output: it may keep what it parsed, and answers the result panel's lines (masked where it must be). */
+ read?: (stdout: string, stderr: string, ok: boolean) => string[]
}
export const exec = (tool: string, params: Record<string, string>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const
diff --git a/plugins/ruflo-console/hooks/automate.ts b/plugins/ruflo-console/hooks/automate.ts
new file mode 100644
index 0000000000..ff9afc6f29
--- /dev/null
+++ b/plugins/ruflo-console/hooks/automate.ts
@@ -0,0 +1,340 @@
+/**
+ * The Automation view's work: workflows, the twelve background workers and their daemon, autopilot, sessions, config
+ * and tasks, each as one fixed argv checked against @claude-flow/cli 3.51.1 (commands/{workflow,hooks,daemon,autopilot,
+ * session,config,task}.ts and the mcp-tools they call). A read ($0, changes nothing) runs at once and its output lands
+ * in the result panel; anything that writes, deletes, starts a process or may call a paid model asks first, and its
+ * confirm row says so. Free text passes `freeText`, keys `configKeyOf`, ids `idOf`, paths `relPathOf`. Pure: specs and
+ * entries only, built from the state; the runner runs them.
+ *
+ * What cannot work is said, not faked: `hooks worker status` and `cancel` keep workers in a per-process map, so a fresh
+ * `ruflo` run never sees a worker another run dispatched; the cards read the daemon's own state file instead.
+ */
+import type { ActionSpec } from './actions'
+import { configKeyOf, freeText, keyValueOf, isSecretKey, laneOf, looksSecret, MASK, objectIn, parseAutopilot, parseConfig, parseSessions, parseTemplates, parseWorkflows, relPathOf, shownValue, WORKER_ABOUT, WORKER_NAMES } from './data/automate'
+import { idOf, plain, type AgentRecord, type TaskRecord } from './data/parse'
+import { labLines, type LabCost } from './mh-lab'
+import type { State } from './state'
+import { selection } from './views/select'
+
+/** An `mcp exec` argv: the params are one JSON argv element, never a shell string (numbers and booleans keep their type). */
+export const tool = (name: string, params: Record<string, unknown>): readonly string[] => ['mcp', 'exec', '-t', name, '-p', JSON.stringify(params)]
+
+/** One palette entry from this view: a spec (null with its reason when it cannot run now), or a text entry whose id is its keyword. */
+export type AutoEntry = { id: string; group: string; label: string; spec?: ActionSpec | null; why?: string; make?: (text: string) => ActionSpec | null }
+
+type Extra = { note?: string; read?: ActionSpec['read']; timeoutMs?: number; verify?: ActionSpec['verify']; expect?: string }
+
+/** A lab spec: it reports into the result panel (and `/ruflo run <id>` answers with it); only a read skips the confirm. */
+export function autoSpec(id: string, label: string, cost: LabCost, args: readonly string[], extra: Extra = {}): ActionSpec {
+ return {
+ label,
+ args,
+ expect: extra.expect ?? (cost === 'read' ? 'its output in the result panel' : `its result in the result panel${extra.note !== undefined ? `; ${extra.note}` : ''}`),
+ lab: id,
+ ...(cost === 'read' && { isReadOnly: true }),
+ ...(extra.note !== undefined && { note: extra.note }),
+ ...(extra.read !== undefined && { read: extra.read }),
+ ...(extra.timeoutMs !== undefined && { timeoutMs: extra.timeoutMs }),
+ ...(extra.verify !== undefined && { verify: extra.verify }),
+ }
+}
+
+/** Keeps a parsed list when the output had one, then answers the panel's lines from it (or the CLI's own when it had none). */
+function keep<T>(parse: (stdout: string) => T[] | null, put: (list: T[]) => void, line: (item: T) => string, empty: string): ActionSpec['read'] {
+ return (stdout, stderr) => {
+ const list = parse(stdout)
+
+ if (list === null) return labLines('auto', stdout, stderr)
+
+ put(list)
+
+ return list.length === 0 ? [empty] : list.map(line)
+ }
+}
+
+/** The ids and statuses a write answered: a workflow's new status is kept on its row, the rest is shown as is. */
+function statusRead(state: State): ActionSpec['read'] {
+ return (stdout, stderr) => {
+ const value = objectIn(stdout)
+ const id = idOf(value?.workflowId)
+ const status = typeof value?.status === 'string' ? plain(value.status, 20) : null
+ const row = state.auto.workflows?.find(workflow => workflow.id === id)
+
+ if (row !== undefined && status !== null) row.status = status
+
+ return labLines('auto', stdout, stderr)
+ }
+}
+
+const DISPATCH_NOTE = 'writes a job file to .claude-flow/daemon-queue for the daemon; with no daemon running nothing executes, and a --headless daemon may call claude under its AI budget'
+export const WORKER_CANCEL_WHY = 'n/a: hooks worker status and cancel keep workers in a per-process map, so a fresh ruflo run never sees a worker another run dispatched; the cards read .claude-flow/daemon-state.json instead'
+
+/** The fixed entries: lists and reads, the daemon, autopilot, and the typed ones. Per-row entries come from `rowEntries`. */
+function fixedEntries(state: State): AutoEntry[] {
+ const out: AutoEntry[] = []
+ const spec = (id: string, group: string, label: string, cost: LabCost, args: readonly string[], extra?: Extra) => out.push({ id, group, label, spec: autoSpec(id, label, cost, args, extra) })
+ const auto = state.auto
+
+ spec('auto-wf-list', 'workflows', 'workflows: list them with their status', 'read', tool('workflow_list', { limit: 20 }), {
+ read: keep(parseWorkflows, list => (auto.workflows = list), row => `${row.id} · ${row.name} · ${row.status} · ${row.steps} step${row.steps === 1 ? '' : 's'}`, '(no workflows yet: create one below)'),
+ })
+ spec('auto-wf-templates', 'workflows', 'workflow templates: list the saved ones', 'read', tool('workflow_template', { action: 'list' }), {
+ read: keep(parseTemplates, list => (auto.templates = list), row => `${row.id} · ${row.name} · ${row.steps} steps`, '(no templates: ▸ tpl saves a workflow as one)'),
+ })
+
+ for (const name of WORKER_NAMES) {
+ spec(`auto-worker-${name}`, 'workers', `dispatch the ${name} worker (${WORKER_ABOUT[name]})`, 'writes', ['hooks', 'worker', 'dispatch', '--trigger', name], { note: DISPATCH_NOTE, expect: 'the worker queued for the daemon' })
+ }
+
+ spec('auto-workers-list', 'workers', 'workers: the twelve, their priority and time', 'read', ['hooks', 'worker', 'list'])
+ spec('auto-workers-status', 'workers', 'workers: status of this process’s dispatches', 'read', ['hooks', 'worker', 'status', '--all'])
+ out.push({ id: 'auto-worker-cancel', group: 'workers', label: 'cancel a running worker', spec: null, why: WORKER_CANCEL_WHY })
+ spec('auto-daemon-status', 'workers', 'daemon: its status and every worker’s runs', 'read', ['daemon', 'status'])
+ spec('auto-daemon-start', 'workers', 'start the worker daemon (local-only workers)', 'local', ['daemon', 'start'], {
+ note: 'starts a background process for this project that runs the enabled workers on their schedule, local-only (no --headless, so no model calls), until ruflo daemon stop or its 12 h TTL',
+ verify: snapshot => snapshot.daemon?.running === true,
+ })
+ spec('auto-daemon-stop', 'workers', 'stop the worker daemon', 'writes', ['daemon', 'stop'], { note: 'stops this project’s daemon and its workers', verify: snapshot => snapshot.daemon?.running !== true })
+
+ spec('auto-ap-status', 'autopilot', 'autopilot: enabled, iterations, task progress', 'read', ['autopilot', 'status', '--json'], {
+ read: (stdout, stderr) => {
+ const status = parseAutopilot(stdout)
+
+ if (status === null) return labLines('auto', stdout, stderr)
+ auto.autopilot = status
+
+ return [`${status.isEnabled ? 'ENABLED' : 'disabled'} · iteration ${status.iterations}/${status.maxIterations} · timeout ${status.timeoutMinutes} min`, `tasks ${status.done}/${status.total} (${status.percent}%) · sources ${status.sources.join(', ') || 'n/a'}`]
+ },
+ })
+ spec('auto-ap-enable', 'autopilot', 'enable autopilot: keep agents working until every task is done', 'writes', ['autopilot', 'enable'], { note: 'writes .claude-flow/data/autopilot-state.json; the stop hook then re-engages the session until its tasks are done or the iteration cap is hit' })
+ spec('auto-ap-disable', 'autopilot', 'disable autopilot', 'writes', ['autopilot', 'disable'], { note: 'writes .claude-flow/data/autopilot-state.json' })
+ spec('auto-ap-reset', 'autopilot', 'reset autopilot’s iteration counter and timer', 'writes', ['autopilot', 'reset'], { note: 'writes .claude-flow/data/autopilot-state.json' })
+ spec('auto-ap-predict', 'autopilot', 'autopilot predict: the next best action', 'read', ['autopilot', 'predict', '--json'])
+ spec('auto-ap-learn', 'autopilot', 'autopilot learn: success patterns from past completions', 'read', ['autopilot', 'learn', '--json'])
+ spec('auto-ap-log', 'autopilot', 'autopilot log: the last 20 events', 'read', ['autopilot', 'log', '--last', '20', '--json'])
+ out.push({ id: 'auto-ap-history', group: 'autopilot', label: 'auto-ap-history <query>: search past completions', make: text => historySpec(text) })
+
+ spec('auto-ses-list', 'sessions', 'sessions: list the saved ones', 'read', tool('session_list', { limit: 20 }), {
+ read: keep(parseSessions, list => (auto.sessions = list), row => `${row.id} · ${row.name}`, '(no saved sessions: save one below)'),
+ })
+ spec('auto-ses-current', 'sessions', 'session: the current one', 'read', tool('session_current', {}))
+ out.push({ id: 'auto-ses-save', group: 'sessions', label: 'auto-ses-save <name>: save memory, agents and tasks as a session', make: text => sessionSave(state, text) })
+
+ spec('auto-cfg-list', 'config', 'config: every key, secrets masked', 'read', tool('config_list', {}), {
+ read: keep(parseConfig, list => (auto.config = list), row => `${row.key} = ${row.shown} (${row.source})`, '(no config values)'),
+ })
+ out.push({ id: 'auto-cfg-get', group: 'config', label: 'auto-cfg-get <key>: one config value (secrets masked)', make: configGet })
+ out.push({ id: 'auto-cfg-set', group: 'config', label: 'auto-cfg-set <key> <value>: set a config value', make: configSet })
+
+ spec('auto-task-list', 'tasks', 'tasks: list them with status and agents', 'read', tool('task_list', { limit: 50 }))
+ out.push({ id: 'auto-task-new', group: 'tasks', label: 'auto-task-new [type:] <description>: create a task', make: taskCreate })
+ out.push({ id: 'auto-wf-new', group: 'workflows', label: 'auto-wf-new <prompt>: a one-step workflow for an agent', make: text => workflowCreate(state, text) })
+ out.push({ id: 'auto-wf-validate', group: 'workflows', label: 'auto-wf-validate <file>: check a workflow file’s structure', make: workflowValidate })
+
+ return out
+}
+
+export function historySpec(text: string): ActionSpec | null {
+ const query = freeText(text, 120)
+
+ return query === null ? null : autoSpec('auto-ap-history', `autopilot history for "${query.slice(0, 40)}"`, 'read', ['autopilot', 'history', '--query', query, '--json'])
+}
+
+export function sessionSave(state: State, text: string): ActionSpec | null {
+ const name = freeText(text, 64)
+
+ return name === null
+ ? null
+ : autoSpec('auto-ses-save', `save the session "${name}"`, 'writes', tool('session_save', { name }), {
+ note: 'writes a session file in .claude-flow/sessions holding memory, agents and tasks',
+ read: (stdout, stderr, ok) => {
+ if (ok) state.auto.sessions = null
+
+ return labLines('auto-ses-save', stdout, stderr)
+ },
+ })
+}
+
+/** A config value through the masks: the key or value that looks secret is never drawn, nor its previous value. */
+function configRead(stdout: string, stderr: string): string[] {
+ const value = objectIn(stdout)
+ const key = typeof value?.key === 'string' ? configKeyOf(value.key) : null
+
+ if (value === null || key === null) return labLines('auto-cfg', stdout, stderr).map(line => (looksSecret(line.split(': ').pop()) ? MASK : line))
+
+ const now = shownValue(key, value.value)
+ const before = 'previousValue' in value ? ` (was ${shownValue(key, value.previousValue).shown})` : ''
+
+ return [`${key} = ${now.shown}${before}`, `source ${plain(String(value.source ?? value.scope ?? 'n/a'), 20)}${value.path !== undefined ? ` · ${plain(String(value.path), 120)}` : ''}`]
+}
+
+export function configGet(text: string): ActionSpec | null {
+ const key = configKeyOf(text)
+
+ return key === null ? null : autoSpec('auto-cfg-get', `config value of ${key}`, 'read', tool('config_get', { key }), { read: configRead })
+}
+
+/** A set never carries a secret: the confirm row prints the argv, so a credential-shaped key or value is refused here. */
+export function configSet(text: string): ActionSpec | null {
+ const pair = keyValueOf(text)
+
+ if (pair === null || isSecretKey(pair.key) || looksSecret(pair.value)) return null
+
+ return autoSpec('auto-cfg-set', `set config ${pair.key} to ${JSON.stringify(pair.value)}`, 'writes', tool('config_set', { key: pair.key, value: pair.value }), { note: 'writes .claude-flow/config.json', read: configRead })
+}
+
+const TASK_TYPES = ['feature', 'bugfix', 'research', 'refactor', 'test', 'docs'] as const
+
+/** `bugfix: the login loop` makes a bugfix; with no known type first, a feature. */
+export function taskCreate(text: string): ActionSpec | null {
+ const match = /^(\w+):\s*(.*)$/.exec(text.trim())
+ const type = match !== null && (TASK_TYPES as readonly string[]).includes(match[1]?.toLowerCase() ?? '') ? (match[1] ?? 'feature').toLowerCase() : 'feature'
+ const description = freeText(match !== null && type !== 'feature' ? (match[2] ?? '') : text, 300)
+
+ return description === null
+ ? null
+ : autoSpec('auto-task-new', `create a ${type} task "${description.slice(0, 40)}"`, 'writes', tool('task_create', { type, description }), {
+ note: 'writes .claude-flow/tasks/store.json',
+ expect: 'the task on the board as pending',
+ verify: snapshot => snapshot.tasks.some(task => task.description === description),
+ })
+}
+
+/** One task step for the first agent on disk (a run needs one); the prompt is the person's, the name its first words. */
+export function workflowCreate(state: State, text: string): ActionSpec | null {
+ const prompt = freeText(text, 300)
+ const agentId = idOf(state.snapshot?.agents[0]?.id)
+
+ if (prompt === null) return null
+
+ return autoSpec('auto-wf-new', `create a workflow "${prompt.slice(0, 40)}"${agentId === null ? ' (no agent yet: a run needs one)' : ` for ${agentId}`}`, 'writes', tool('workflow_create', { name: prompt.slice(0, 60), description: prompt, steps: [{ name: 'task', type: 'task', config: { prompt, ...(agentId !== null && { agentId }) } }] }), {
+ note: 'writes .claude-flow/workflows/store.json; nothing runs until ▸ run',
+ read: (stdout, stderr, ok) => {
+ if (ok) state.auto.workflows = null
+
+ return labLines('auto-wf-new', stdout, stderr)
+ },
+ })
+}
+
+export function workflowValidate(text: string): ActionSpec | null {
+ const file = relPathOf(text)
+
+ return file === null ? null : autoSpec('auto-wf-validate', `validate the workflow file ${file}`, 'read', tool('workflow_validate', { file }))
+}
+
+/** The buttons a workflow row offers, by its status: running pauses or cancels, paused resumes, the rest run. */
+export function workflowVerbs(status: string): ('status' | 'run' | 'pause' | 'resume' | 'cancel' | 'tpl')[] {
+ if (status === 'running') return ['status', 'pause', 'cancel']
+ if (status === 'paused') return ['status', 'resume', 'cancel', 'tpl']
+
+ return ['status', 'run', 'tpl']
+}
+
+/** The lanes a task's buttons move it along: pending is assigned or cancelled, running completed or cancelled, done retried. */
+export function taskVerbs(status: string): ('assign' | 'done' | 'cancel' | 'retry')[] {
+ const lane = laneOf(status)
+
+ return lane === 'pending' ? ['assign', 'cancel'] : lane === 'running' ? ['done', 'cancel'] : /fail|cancel/.test(status) ? ['retry'] : []
+}
+
+export function taskSpec(verb: 'assign' | 'done' | 'cancel' | 'retry', task: TaskRecord, agent: AgentRecord | null): ActionSpec | null {
+ const taskId = idOf(task.id)
+ const id = `auto-task-${verb}-${task.id}`
+ const agentId = idOf(agent?.id)
+
+ if (taskId === null) return null
+
+ switch (verb) {
+ case 'assign':
+ return agentId === null
+ ? null
+ : autoSpec(id, `assign task ${taskId} to ${agent?.name ?? agent?.type ?? agentId}`, 'writes', tool('task_assign', { taskId, agentIds: [agentId] }), { note: 'writes .claude-flow/tasks/store.json', verify: snapshot => snapshot.tasks.some(entry => entry.id === taskId && entry.assignedTo.includes(agentId)) })
+ case 'done':
+ return autoSpec(id, `mark task ${taskId} complete`, 'writes', tool('task_complete', { taskId }), { note: 'writes .claude-flow/tasks/store.json', verify: snapshot => snapshot.tasks.some(entry => entry.id === taskId && entry.status === 'completed') })
+ case 'cancel':
+ return autoSpec(id, `cancel task ${taskId}`, 'writes', tool('task_cancel', { taskId, reason: 'cancelled from ruflo-console' }), { note: 'writes .claude-flow/tasks/store.json', verify: snapshot => snapshot.tasks.some(entry => entry.id === taskId && entry.status === 'cancelled') })
+ case 'retry':
+ return autoSpec(id, `retry task ${taskId} as a new pending task`, 'writes', tool('task_retry', { taskId }), { note: 'writes .claude-flow/tasks/store.json: a new pending copy of the task' })
+ }
+}
+
+const WF_NOTE = 'writes .claude-flow/workflows/store.json'
+
+export function workflowSpec(verb: 'status' | 'run' | 'pause' | 'resume' | 'cancel' | 'tpl', workflowId: string, state: State): ActionSpec | null {
+ const id = idOf(workflowId)
+ const lab = `auto-wf-${verb}-${workflowId}`
+
+ if (id === null) return null
+
+ switch (verb) {
+ case 'status':
+ return autoSpec(lab, `status of workflow ${id}`, 'read', tool('workflow_status', { workflowId: id, verbose: true }), { read: statusRead(state) })
+ case 'run':
+ return autoSpec(lab, `run workflow ${id} (its task steps call a model)`, 'spends', tool('workflow_execute', { workflowId: id }), {
+ note: 'COSTS MONEY: each task step calls the agent’s configured model (agent_execute) until the workflow ends, fails or is paused',
+ read: statusRead(state),
+ timeoutMs: 600_000,
+ })
+ case 'pause':
+ return autoSpec(lab, `pause workflow ${id}`, 'writes', tool('workflow_pause', { workflowId: id }), { note: `${WF_NOTE}; a run stops before its next step`, read: statusRead(state) })
+ case 'resume':
+ return autoSpec(lab, `resume workflow ${id}`, 'writes', tool('workflow_resume', { workflowId: id }), { note: `${WF_NOTE}; marks it running, its steps do not execute until ▸ run`, read: statusRead(state) })
+ case 'cancel':
+ return autoSpec(lab, `cancel workflow ${id}`, 'writes', tool('workflow_cancel', { workflowId: id, reason: 'cancelled from ruflo-console' }), { note: `${WF_NOTE}; skips its remaining steps`, read: statusRead(state) })
+ case 'tpl':
+ return autoSpec(lab, `save workflow ${id} as a template`, 'writes', tool('workflow_template', { action: 'save', workflowId: id }), { note: WF_NOTE })
+ }
+}
+
+export function sessionSpec(verb: 'restore' | 'export' | 'delete', sessionId: string): ActionSpec | null {
+ const id = idOf(sessionId)
+ const lab = `auto-ses-${verb}-${sessionId}`
+
+ if (id === null) return null
+
+ switch (verb) {
+ case 'restore':
+ return autoSpec(lab, `restore session ${id}`, 'writes', tool('session_restore', { sessionId: id }), { note: 'OVERWRITES this project’s current memory, agents and tasks with the saved ones' })
+ case 'export':
+ // The export holds memory entries: only its id, path and time are shown, never the data.
+ return autoSpec(lab, `export session ${id} to session-${id}.json`, 'writes', tool('session_export', { sessionId: id, outputPath: `session-${id}.json` }), {
+ note: `writes session-${id}.json in the project; it holds the session’s memory entries`,
+ read: (stdout, stderr) => {
+ const value = objectIn(stdout)
+
+ return value === null ? labLines(lab, '', stderr) : [`${plain(String(value.sessionId ?? id), 80)} → ${plain(String(value.path ?? value.error ?? 'n/a'), 160)}`, `exported ${plain(String(value.exportedAt ?? 'n/a'), 40)}`]
+ },
+ })
+ case 'delete':
+ return autoSpec(lab, `delete session ${id}`, 'writes', tool('session_delete', { sessionId: id }), { note: 'DELETES the saved session file; it cannot be undone' })
+ }
+}
+
+/** Every entry for the state as it is: the fixed ones, then one per verb of each listed workflow, template, session and task. */
+export function automateEntries(state: State): AutoEntry[] {
+ const out = fixedEntries(state)
+ // Assign goes to the agent picked on the board (a, as on the claims board).
+ const agent = selection(state).agent
+
+ for (const workflow of (state.auto.workflows ?? []).slice(0, 8)) {
+ for (const verb of workflowVerbs(workflow.status)) out.push({ id: `auto-wf-${verb}-${workflow.id}`, group: 'workflows', label: `${verb} workflow ${workflow.name}`, spec: workflowSpec(verb, workflow.id, state), why: 'that workflow id cannot be passed to ruflo' })
+ }
+
+ for (const template of (state.auto.templates ?? []).slice(0, 6)) {
+ const templateId = idOf(template.id)
+
+ out.push({ id: `auto-tpl-new-${template.id}`, group: 'workflows', label: `new workflow from template ${template.name}`, spec: templateId === null ? null : autoSpec(`auto-tpl-new-${template.id}`, `new workflow from template ${templateId}`, 'writes', tool('workflow_template', { action: 'create', templateId }), { note: WF_NOTE }), why: 'that template id cannot be passed to ruflo' })
+ }
+
+ for (const session of (state.auto.sessions ?? []).slice(0, 8)) {
+ for (const verb of ['restore', 'export', 'delete'] as const) out.push({ id: `auto-ses-${verb}-${session.id}`, group: 'sessions', label: `${verb} session ${session.name}`, spec: sessionSpec(verb, session.id), why: 'that session id cannot be passed to ruflo' })
+ }
+
+ for (const task of (state.snapshot?.tasks ?? []).slice(0, 24)) {
+ for (const verb of taskVerbs(task.status)) out.push({ id: `auto-task-${verb}-${task.id}`, group: 'tasks', label: `${verb} task ${task.id}`, spec: taskSpec(verb, task, agent), why: verb === 'assign' ? 'no agent to assign it to: spawn one (Swarm)' : 'that task id cannot be passed to ruflo' })
+ }
+
+ return out
+}
+
diff --git a/plugins/ruflo-console/hooks/data/automate.ts b/plugins/ruflo-console/hooks/data/automate.ts
new file mode 100644
index 0000000000..8ec6206263
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/automate.ts
@@ -0,0 +1,268 @@
+/**
+ * What the Automation and Neural views read and keep: the lists a click asked for (workflows, templates, sessions,
+ * config, autopilot), the training runs of this session, and the checks every typed value passes before it becomes an
+ * argv element. Read against @claude-flow/cli 3.51.1 (mcp-tools/{workflow,session,config,task}-tools.ts,
+ * commands/{autopilot,neural}.ts) and what it printed in a scratch project. Pure: no `$`, nothing here runs anything.
+ *
+ * Config values are masked as they are parsed, so a secret never reaches the state, the result panel or a log line.
+ */
+import { idOf, msOf, numberOf, plain, recordOf, stringOf } from './parse'
+
+export type WorkflowRow = { id: string; name: string; status: string; steps: number; createdAtMs?: number }
+export type TemplateRow = { id: string; name: string; steps: number }
+export type SessionRow = { id: string; name: string; savedAtMs?: number }
+/** `shown` is the value as the view may draw it: a secret-looking key or value is already replaced by a mask. */
+export type ConfigRow = { key: string; shown: string; source: string; isSecret: boolean }
+export type AutopilotStatus = { isEnabled: boolean; iterations: number; maxIterations: number; timeoutMinutes: number; done: number; total: number; percent: number; sources: string[] }
+/** One `neural train` run: the pattern, the epochs asked, and the loss its table printed (Final Loss, else Avg Loss). */
+export type TrainRun = { pattern: string; epochs: number; loss?: number; seconds?: number; backend?: string; atMs: number }
+
+export type AutoState = {
+ workflows: WorkflowRow[] | null
+ templates: TemplateRow[] | null
+ sessions: SessionRow[] | null
+ config: ConfigRow[] | null
+ autopilot: AutopilotStatus | null
+ trains: TrainRun[]
+ /** The pattern and epochs the train buttons use, picked in the view. */
+ pattern: Pattern
+ epochs: number
+}
+
+export const emptyAuto = (): AutoState => ({ workflows: null, templates: null, sessions: null, config: null, autopilot: null, trains: [], pattern: 'coordination', epochs: 20 })
+
+/** The pattern types `neural train -p` takes (commands/neural.ts). */
+export const PATTERNS = ['coordination', 'optimization', 'prediction', 'security', 'testing'] as const
+export type Pattern = (typeof PATTERNS)[number]
+export const EPOCHS = [10, 20, 50, 100] as const
+
+/** The twelve background workers `hooks_worker-dispatch` accepts (its trigger enum), in its own order. */
+export const WORKER_NAMES = ['ultralearn', 'optimize', 'consolidate', 'predict', 'audit', 'map', 'preload', 'deepdive', 'document', 'refactor', 'benchmark', 'testgaps'] as const
+export type WorkerName = (typeof WORKER_NAMES)[number]
+
+/** What each worker does, in `hooks worker list`'s words. */
+export const WORKER_ABOUT: Record<WorkerName, string> = {
+ ultralearn: 'deep knowledge acquisition',
+ optimize: 'performance optimization',
+ consolidate: 'memory consolidation',
+ predict: 'predictive preloading',
+ audit: 'security analysis',
+ map: 'codebase mapping',
+ preload: 'resource preloading',
+ deepdive: 'deep code analysis',
+ document: 'auto-documentation',
+ refactor: 'refactoring suggestions',
+ benchmark: 'performance benchmarking',
+ testgaps: 'test coverage analysis',
+}
+
+/** Typed text: printable, no control characters, never read as a flag. */
+const TYPED = /^[\p{L}\p{N} .,:;!?'"()[\]{}/@#%&*+=_~<>|$^-]+$/u
+
+/** Free text from a field as one argv element or JSON string: cleaned, 1..max characters, not starting with -. */
+export function freeText(value: string, max = 200): string | null {
+ const text = plain(value, max + 1)
+
+ return text === '' || text.length > max || text.startsWith('-') || !TYPED.test(text) ? null : text
+}
+
+const DANGEROUS = new Set(['__proto__', 'constructor', 'prototype'])
+
+/** A config key in dot notation (`swarm.maxAgents`): word segments only, at most ten, nothing that reaches a prototype. */
+export function configKeyOf(value: string): string | null {
+ const key = value.trim()
+
+ return key.length <= 128 && /^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+){0,9}$/.test(key) && !key.split('.').some(part => DANGEROUS.has(part)) ? key : null
+}
+
+/** A key that names a credential: its value is never drawn, and the console never sets it (the confirm row prints argv). */
+export const isSecretKey = (key: string): boolean => /(key|token|secret|passw|credential|auth|cookie|private|bearer|jwt|session)/i.test(key)
+
+/** A value shaped like a credential, whatever its key says: provider prefixes, JWTs, or a long unbroken token. */
+export function looksSecret(value: unknown): boolean {
+ if (typeof value !== 'string') return false
+
+ return /^(sk-|sk_|pk_|rk_|ghp_|gho_|ghs_|github_pat_|glpat-|xox[abpors]-|AKIA|ASIA|AIza|eyJ|npm_|hf_)/.test(value) || /^[A-Za-z0-9+/_=-]{32,}$/.test(value)
+}
+
+export const MASK = '•••••• (hidden)'
+
+/** A config value as the view may show it: a mask for anything secret, else the value, short. */
+export function shownValue(key: string, value: unknown): { shown: string; isSecret: boolean } {
+ const isSecret = isSecretKey(key) || looksSecret(value) || (recordOf(value) !== null && Object.entries(recordOf(value) ?? {}).some(([inner, field]) => isSecretKey(inner) || looksSecret(field)))
+
+ if (isSecret) return { shown: MASK, isSecret: true }
+ if (value === undefined) return { shown: 'n/a', isSecret: false }
+
+ return { shown: plain(typeof value === 'string' ? value : JSON.stringify(value) ?? String(value), 80), isSecret: false }
+}
+
+/** A typed config value as `config_set` stores it: true/false and plain numbers keep their type, the rest is text. */
+export function configValueOf(value: string): string | number | boolean | null {
+ const text = value.trim()
+
+ if (text === 'true' || text === 'false') return text === 'true'
+ if (/^-?\d{1,15}(\.\d{1,6})?$/.test(text)) return Number(text)
+
+ return freeText(text, 200)
+}
+
+/** `key value` from one field: the key, then the rest as the value. */
+export function keyValueOf(value: string): { key: string; value: string | number | boolean } | null {
+ const [head = '', ...rest] = value.trim().split(/\s+/)
+ const key = configKeyOf(head)
+ const parsed = rest.length === 0 ? null : configValueOf(rest.join(' '))
+
+ return key === null || parsed === null ? null : { key, value: parsed }
+}
+
+/** A path inside the project for a tool to read: relative, no `..`, no leading dash or dot-dot, plain characters. */
+export function relPathOf(value: string): string | null {
+ const path = value.trim()
+
+ return path.length <= 200 && /^[A-Za-z0-9_.][A-Za-z0-9_./-]*$/.test(path) && !path.split('/').includes('..') && !path.startsWith('-') ? path : null
+}
+
+/**
+ * The JSON object a run printed: from the first line that opens one to the last brace. Not `jsonAfter`, which also takes
+ * a line opening `[`: `hooks route` prints `[hooks] Semantic router initialized…` before its JSON.
+ */
+export function objectIn(stdout: string): Record<string, unknown> | null {
+ const text = stdout.length > 1_000_000 ? stdout.slice(0, 1_000_000) : stdout
+ const start = /^[ \t]*\{/m.exec(text)
+
+ if (start === null) return null
+
+ try {
+ return recordOf(JSON.parse(text.slice(start.index, text.lastIndexOf('}') + 1)))
+ } catch {
+ return null
+ }
+}
+
+const rows = (value: unknown): Record<string, unknown>[] => (Array.isArray(value) ? value : []).slice(0, 50).map(recordOf).filter((row): row is Record<string, unknown> => row !== null)
+
+/** `workflow_list`: `{ workflows: [{ workflowId, name, status, stepCount, createdAt }] }`, newest first. */
+export function parseWorkflows(stdout: string): WorkflowRow[] | null {
+ const value = objectIn(stdout)
+
+ if (value === null || !Array.isArray(value.workflows)) return null
+
+ return rows(value.workflows).flatMap(row => {
+ const id = idOf(row.workflowId)
+ const createdAtMs = msOf(row.createdAt)
+
+ return id === null ? [] : [{ id, name: plain(row.name, 60) || id, status: stringOf(row.status, 20) ?? 'unknown', steps: numberOf(row.stepCount) ?? 0, ...(createdAtMs !== undefined && { createdAtMs }) }]
+ })
+}
+
+/** `workflow_template { action: list }`: `{ templates: [{ templateId, name, stepCount }] }`. */
+export function parseTemplates(stdout: string): TemplateRow[] | null {
+ const value = objectIn(stdout)
+
+ if (value === null || !Array.isArray(value.templates)) return null
+
+ return rows(value.templates).flatMap(row => {
+ const id = idOf(row.templateId)
+
+ return id === null ? [] : [{ id, name: plain(row.name, 60) || id, steps: numberOf(row.stepCount) ?? 0 }]
+ })
+}
+
+/** `session_list`: `{ sessions: [{ sessionId, name, savedAt }] }`, newest first. */
+export function parseSessions(stdout: string): SessionRow[] | null {
+ const value = objectIn(stdout)
+
+ if (value === null || !Array.isArray(value.sessions)) return null
+
+ return rows(value.sessions).flatMap(row => {
+ const id = idOf(row.sessionId)
+ const savedAtMs = msOf(row.savedAt)
+
+ return id === null || id === 'unknown' ? [] : [{ id, name: plain(row.name, 60) || id, ...(savedAtMs !== undefined && { savedAtMs }) }]
+ })
+}
+
+/** `config_list`: `{ configs: [{ key, value, source }] }`, every value masked here, before it is kept. */
+export function parseConfig(stdout: string): ConfigRow[] | null {
+ const value = objectIn(stdout)
+
+ if (value === null || !Array.isArray(value.configs)) return null
+
+ return rows(value.configs)
+ .slice(0, 40)
+ .flatMap(row => {
+ const key = typeof row.key === 'string' ? configKeyOf(row.key) : null
+
+ return key === null ? [] : [{ key, ...shownValue(key, row.value), source: stringOf(row.source, 20) ?? 'n/a' }]
+ })
+}
+
+/** `autopilot status --json`: enabled, iterations of max, the timeout, and task progress. */
+export function parseAutopilot(stdout: string): AutopilotStatus | null {
+ const value = objectIn(stdout)
+ const tasks = recordOf(value?.tasks)
+
+ if (value === null || typeof value.enabled !== 'boolean') return null
+
+ return {
+ isEnabled: value.enabled,
+ iterations: numberOf(value.iterations) ?? 0,
+ maxIterations: numberOf(value.maxIterations) ?? 0,
+ timeoutMinutes: numberOf(value.timeoutMinutes) ?? 0,
+ done: numberOf(tasks?.completed) ?? 0,
+ total: numberOf(tasks?.total) ?? 0,
+ percent: numberOf(tasks?.percent) ?? 0,
+ sources: (Array.isArray(value.taskSources) ? value.taskSources : []).slice(0, 6).flatMap(source => (typeof source === 'string' ? [plain(source, 24)] : [])),
+ }
+}
+
+/** The `| Metric | Value |` rows a CLI table printed, as [name, value] pairs; the header row is left out. */
+export function tableRows(stdout: string): [string, string][] {
+ return stdout.split('\n').flatMap(line => {
+ const match = /^\|\s*([^|]+?)\s*\|\s*([^|]*?)\s*\|$/.exec(line.trim())
+
+ return match === null || match[1] === 'Metric' ? [] : [[plain(match[1], 40), plain(match[2], 80)] as [string, string]]
+ })
+}
+
+/** What `neural train` printed, as one run: its loss from Final Loss (native backend) or Avg Loss (JS fallback). */
+export function parseTrain(stdout: string, atMs: number): TrainRun | null {
+ const table = new Map(tableRows(stdout))
+ const epochs = Number(table.get('Epochs'))
+ const pattern = table.get('Pattern Type')
+
+ if (pattern === undefined || !Number.isFinite(epochs)) return null
+
+ const loss = Number(table.get('Final Loss') ?? table.get('Avg Loss'))
+ const seconds = Number.parseFloat(table.get('Total Time') ?? '')
+ const backend = table.get('Backend')
+
+ return {
+ pattern: plain(pattern, 20),
+ epochs,
+ atMs,
+ ...(Number.isFinite(loss) && { loss }),
+ ...(Number.isFinite(seconds) && { seconds }),
+ ...(backend !== undefined && backend !== '' && { backend: backend.split(' ')[0] }),
+ }
+}
+
+const BARS = '▁▂▃▄▅▆▇█'
+
+/** A series as a one-line sparkline, highest value tallest; a flat or single series sits mid-height. */
+export function sparkline(values: readonly number[]): string {
+ const finite = values.filter(Number.isFinite)
+ const lo = Math.min(...finite)
+ const hi = Math.max(...finite)
+
+ return finite.map(value => BARS[hi === lo ? 3 : Math.round(((value - lo) / (hi - lo)) * (BARS.length - 1))]).join('')
+}
+
+/** A task's lane on the kanban: what ruflo's task tools write (pending, in_progress, completed, failed, cancelled). */
+export function laneOf(status: string): 'pending' | 'running' | 'done' {
+ if (/^(in_progress|running|assigned|active|busy)$/.test(status)) return 'running'
+ if (/^(completed|done|failed|cancelled|canceled|error)$/.test(status)) return 'done'
+
+ return 'pending'
+}
diff --git a/plugins/ruflo-console/hooks/neural.ts b/plugins/ruflo-console/hooks/neural.ts
new file mode 100644
index 0000000000..f5e0f7926a
--- /dev/null
+++ b/plugins/ruflo-console/hooks/neural.ts
@@ -0,0 +1,108 @@
+/**
+ * The Learning Lab: ruflo's neural commands and the router's "which agent?" as fixed argv, checked against
+ * @claude-flow/cli 3.51.1 (commands/neural.ts, commands/hooks.ts route/explain, mcp-tools/neural-tools.ts). Reads run at
+ * once into the result panel; training, quantizing and compressing are local compute that writes the neural store, so
+ * each asks first. `neural train` prints no per-epoch lines when it is not on a TTY, so the loss sparkline is one point
+ * per training run, read from the table it prints at the end (Final Loss, else Avg Loss). Pure: specs only.
+ */
+import type { ActionSpec } from './actions'
+import { autoSpec, tool, type AutoEntry } from './automate'
+import { EPOCHS, freeText, objectIn, parseTrain, PATTERNS, tableRows, type Pattern } from './data/automate'
+import { numberOf, plain, recordOf } from './data/parse'
+import { labLines } from './mh-lab'
+import type { State } from './state'
+
+const TRAIN_NOTE = 'local compute, seconds to minutes; writes .claude-flow/neural (patterns.json and a checkpoint); no model calls'
+
+/** `coordination 50`: a pattern type, then epochs from 1 to 500 (default 20). */
+export function trainArgs(text: string): { pattern: Pattern; epochs: number } | null {
+ const [word = '', count] = text.trim().toLowerCase().split(/\s+/)
+ const pattern = PATTERNS.find(candidate => candidate === word)
+ const epochs = count === undefined ? 20 : /^\d{1,3}$/.test(count) ? Number(count) : NaN
+
+ return pattern === undefined || !Number.isInteger(epochs) || epochs < 1 || epochs > 500 ? null : { pattern, epochs }
+}
+
+export function trainSpec(state: State, text: string, id = 'nn-train'): ActionSpec | null {
+ const picked = trainArgs(text)
+
+ if (picked === null) return null
+
+ return autoSpec(id, `train ${picked.pattern} patterns for ${picked.epochs} epochs`, 'local', ['neural', 'train', '--pattern', picked.pattern, '--epochs', String(picked.epochs)], {
+ note: TRAIN_NOTE,
+ timeoutMs: 600_000,
+ read: (stdout, stderr, ok) => {
+ const run = ok ? parseTrain(stdout, Date.now()) : null
+
+ if (run === null) return labLines('nn-train', stdout, stderr)
+
+ state.auto.trains.push(run)
+ if (state.auto.trains.length > 40) state.auto.trains.splice(0, state.auto.trains.length - 40)
+
+ return tableRows(stdout).map(([name, value]) => `${name}: ${value}`)
+ },
+ })
+}
+
+/** `hooks route --format json`: the pick, its confidence, the method, then the runners-up. */
+function routeRead(stdout: string, stderr: string): string[] {
+ const value = objectIn(stdout)
+ const primary = recordOf(value?.primaryAgent)
+
+ if (value === null || primary === null) return labLines('nn-route', stdout, stderr)
+
+ const confidence = numberOf(primary.confidence)
+ const out = [`→ ${plain(String(primary.type ?? 'n/a'), 30)}${confidence !== undefined ? ` · ${Math.round(confidence * 100)}%` : ''} · ${plain(String(recordOf(value.routing)?.method ?? 'n/a'), 30)}${value.matchedPattern !== undefined ? ` · pattern ${plain(String(value.matchedPattern), 30)}` : ''}`]
+
+ for (const alt of (Array.isArray(value.alternativeAgents) ? value.alternativeAgents : []).slice(0, 4).map(recordOf)) {
+ const score = numberOf(alt?.confidence ?? alt?.score)
+
+ if (alt !== null) out.push(` or ${plain(String(alt.type ?? alt.agent ?? ''), 30)}${score !== undefined ? ` · ${Math.round(score * 100)}%` : ''}`)
+ }
+
+ if (typeof primary.reason === 'string') out.push(plain(primary.reason, 150))
+
+ return out
+}
+
+export function routeSpec(text: string): ActionSpec | null {
+ const task = freeText(text, 300)
+
+ return task === null ? null : autoSpec('nn-route', `which agent for "${task.slice(0, 40)}"`, 'read', ['hooks', 'route', '--task', task, '--format', 'json'], { read: routeRead })
+}
+
+export function explainSpec(text: string): ActionSpec | null {
+ const task = freeText(text, 300)
+
+ return task === null ? null : autoSpec('nn-explain', `explain the routing of "${task.slice(0, 40)}"`, 'read', ['hooks', 'explain', '--task', task])
+}
+
+export function predictSpec(text: string): ActionSpec | null {
+ const input = freeText(text, 300)
+
+ return input === null ? null : autoSpec('nn-predict', `predict for "${input.slice(0, 40)}"`, 'read', ['neural', 'predict', '--input', input, '--format', 'json'])
+}
+
+/** The inspect entries, then the asked ones (quantize, compress), then the typed ones; ids are what `/ruflo run` takes. */
+export function neuralEntries(state: State): AutoEntry[] {
+ const fixed: [string, string, ActionSpec][] = [
+ ['nn-status', 'neural status: every learning component and whether it is loaded', autoSpec('nn-status', 'neural status', 'read', ['neural', 'status'])],
+ ['nn-patterns', 'neural patterns: the stored patterns, their confidence and use', autoSpec('nn-patterns', 'neural patterns', 'read', ['neural', 'patterns', '--action', 'list'])],
+ ['nn-analyze', 'neural optimize --method analyze: pattern memory by component', autoSpec('nn-analyze', 'pattern memory analysis', 'read', ['neural', 'optimize', '--method', 'analyze'])],
+ ['nn-intel', 'hooks intelligence stats: SONA, MoE, EWC++, LoRA and the router', autoSpec('nn-intel', 'intelligence stats', 'read', tool('hooks_intelligence_stats', {}))],
+ ['nn-quantize', 'neural optimize --method quantize: patterns to Int8', autoSpec('nn-quantize', 'quantize the stored patterns to Int8', 'local', ['neural', 'optimize', '--method', 'quantize'], { note: 'local compute; rewrites the stored pattern embeddings as Int8 (about 4x smaller, slightly less exact)' })],
+ ['nn-compress', 'neural_compress quantize: compress the neural store', autoSpec('nn-compress', 'compress the neural store (quantize)', 'local', tool('neural_compress', { method: 'quantize' }), { note: 'local compute; rewrites the neural store in .claude-flow/neural (needs memory init first)' })],
+ ]
+ const out: AutoEntry[] = fixed.map(([id, label, spec]) => ({ id, group: 'neural', label, spec }))
+
+ for (const pattern of PATTERNS) {
+ for (const epochs of EPOCHS) out.push({ id: `nn-train-${pattern}-${epochs}`, group: 'neural', label: `train ${pattern} patterns, ${epochs} epochs`, spec: trainSpec(state, `${pattern} ${epochs}`, `nn-train-${pattern}-${epochs}`) })
+ }
+
+ out.push({ id: 'nn-train', group: 'neural', label: 'nn-train <pattern> [epochs]: train neural patterns', make: text => trainSpec(state, text) })
+ out.push({ id: 'nn-route', group: 'neural', label: 'nn-route <task>: which agent for this task?', make: routeSpec })
+ out.push({ id: 'nn-explain', group: 'neural', label: 'nn-explain <task>: why the router picks that agent', make: explainSpec })
+ out.push({ id: 'nn-predict', group: 'neural', label: 'nn-predict <text>: the trained models’ top predictions', make: predictSpec })
+
+ return out
+}
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index 320a67f328..675e68498f 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -6,7 +6,9 @@
import { HIVE_ROLES, pickedProposal } from './data/hive'
import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote } from './hive'
import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'
+import { automateEntries } from './automate'
import { LAB, labSpec, labWhy } from './mh-lab'
+import { neuralEntries } from './neural'
import { AGENT_TYPES, agentLogs, dispatchWorker, memorySearch, memoryStore, reroute, setClaimStatus, spawnAgent, stopAgent, swarmInit, swarmStop, vote, WORKERS } from './ops'
import { VIEWS, type State, type ViewId } from './state'
import { selection } from './views/select'
@@ -49,7 +51,8 @@ export function fuzzy(query: string, label: string): number | null {
return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0)
}
-const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast'] as const
+/** A text entry's id is its keyword: the Automation and Learning Lab ones are prefixed, so none shadows another. */
+const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast', 'auto-wf-new', 'auto-wf-validate', 'auto-ap-history', 'auto-ses-save', 'auto-cfg-get', 'auto-cfg-set', 'auto-task-new', 'nn-train', 'nn-route', 'nn-explain', 'nn-predict'] as const
/** Every entry for the state as it is, before filtering. */
export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
@@ -116,6 +119,11 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
// The MetaHarness lab: reads run at once, the rest ask first; promotion is never an entry (see mh-lab.ts).
for (const entry of LAB) add(entry.id, 'metaharness', entry.label, { kind: 'spec', spec: labSpec(entry, state), why: labWhy(entry) })
+ // Automation and the Learning Lab: reads run at once, the rest ask first; per-row verbs come from the lists last read.
+ for (const entry of [...automateEntries(state), ...neuralEntries(state)]) {
+ add(entry.id, entry.group, entry.label, entry.make !== undefined ? { kind: 'text', keyword: entry.id, make: entry.make } : { kind: 'spec', spec: entry.spec ?? null, why: entry.why ?? '' })
+ }
+
for (const worker of WORKERS) add(`worker-${worker}`, 'workers', `dispatch the ${worker} background worker`, { kind: 'spec', spec: dispatchWorker(worker), why: 'unknown worker' })
add('route', 'learning', 'route <task words>: ask the router for a pick', { kind: 'text', keyword: 'route', make: reroute })
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index 6a61fe2313..20894c9361 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -60,7 +60,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
// A lab run's output goes to the lab's result panel, scrolled from its top; the footer keeps the one-line outcome.
if (spec.lab !== undefined) {
- state.lab.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: labLines(spec.lab, result.stdout, result.stderr), atMs: Date.now() }
+ state.lab.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: spec.read?.(result.stdout, result.stderr, ok) ?? labLines(spec.lab, result.stdout, result.stderr), atMs: Date.now() }
state.select.item = 0
}
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index 4270e97672..8469f19591 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -1,5 +1,6 @@
import type { PluginOptions, Timer } from 'claude-code'
+import { emptyAuto, type AutoState } from './data/automate'
import type { ProbeResult } from './data/cli'
import type { ConsoleEvent } from './data/events'
import type { ReadCache } from './data/files'
@@ -10,7 +11,7 @@ import type { RufloRoute, RufloSnapshot } from '../types'
export const PLUGIN_NAME = 'ruflo-console'
export const PANE_ID = 'ruflo-console'
-export type ViewId = 'menu' | 'overview' | 'swarm' | 'hive' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'missions' | 'xruv' | 'terminal' | 'skills' | 'agent'
+export type ViewId = 'menu' | 'overview' | 'swarm' | 'hive' | 'claims' | 'federation' | 'plugins' | 'learning' | 'metaharness' | 'memory' | 'cost' | 'timeline' | 'approvals' | 'events' | 'missions' | 'xruv' | 'terminal' | 'skills' | 'automate' | 'neural' | 'agent'
/**
* The views in tab order, each with its hotkey and the inline height it asks for. Digits are the first nine; the three
@@ -42,6 +43,9 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st
{ id: 'terminal', key: 'i', label: 'Terminal', short: 'Trm', icon: '💻', blurb: 'an AI terminal: codex, claude or both, each a session that remembers the conversation, streamed live', rows: 32 },
// No hotkey: every digit and letter is taken. The tab, the menu prompt and /ruflo skills reach it by name.
{ id: 'skills', key: '', label: 'Skills', short: 'Skl', icon: '🧰', blurb: 'agent skills (npx skills, skills.sh): what is installed here and globally, search, add, update, remove, create', rows: 34 },
+ // No hotkeys either: the menu prompt, the tab and /ruflo automate or /ruflo neural reach them by name.
+ { id: 'automate', key: '', label: 'Automation', short: 'Aut', icon: '🤖', blurb: 'workflows, the twelve background workers and their daemon, autopilot, sessions, config and a task kanban', rows: 44 },
+ { id: 'neural', key: '', label: 'Learning Lab', short: 'Lab', icon: '🧪', blurb: 'train neural patterns and watch the loss, ask the router which agent fits a task, and why', rows: 36 },
]
export const AGENT_VIEW = { id: 'agent' as const, rows: 28 }
@@ -217,6 +221,8 @@ export type State = {
}
/** The skills view: installed skills, the last search, and the change running now. */
skills: SkillsState
+ /** The Automation and Learning Lab views: the lists a click asked for, and this session's training runs. */
+ auto: AutoState
timers: Map<string, Timer>
stats: { renders: number[]; refreshes: number[]; frames: number[] }
}
@@ -261,6 +267,7 @@ export function newState(raw: PluginOptions | undefined): State {
barDrawnAtMs: 0,
terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, scroll: 0, unseen: 0, asked: null },
skills: emptySkills(),
+ auto: emptyAuto(),
timers: new Map(),
stats: { renders: [], refreshes: [], frames: [] },
}
diff --git a/plugins/ruflo-console/hooks/views/automate.ts b/plugins/ruflo-console/hooks/views/automate.ts
new file mode 100644
index 0000000000..7d138a37a1
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/automate.ts
@@ -0,0 +1,297 @@
+import type { RenderElement } from 'claude-code'
+
+import { automateEntries, taskVerbs, workflowVerbs, WORKER_CANCEL_WHY } from '../automate'
+import { laneOf, WORKER_ABOUT, WORKER_NAMES, type WorkerName } from '../data/automate'
+import type { TaskRecord } from '../data/parse'
+import type { LabCost } from '../mh-lab'
+import { neuralEntries } from '../neural'
+import { ago, button, clip, col, row, rule, text, THEME, type Ctx } from './common'
+import { selection } from './select'
+
+/** Result lines in view at once; j/k scroll the rest. */
+const RESULT_ROWS = 12
+
+/** Each cost as a four-cell tag, as the MetaHarness lab draws them. */
+export const TAG: Record<LabCost, { text: string; color: () => string }> = {
+ read: { text: ' $0 ', color: () => THEME.ok },
+ writes: { text: ' wr ', color: () => THEME.info },
+ local: { text: 'cpu ', color: () => THEME.warn },
+ spends: { text: ' $$ ', color: () => THEME.bad },
+}
+
+export type Item = { id: string; label: string; cost: LabCost }
+
+/** A strip of buttons, each after its cost tag: a $0 one runs at once, the rest ask first. */
+export function strip(ctx: Ctx, key: string, items: readonly Item[]): RenderElement {
+ return row(
+ ctx,
+ items.flatMap(item => [ctx.kit.Text({ bold: true, color: TAG[item.cost].color(), children: ` ${TAG[item.cost].text}` }), ctx.kit.Button({ key: `run-${item.id}`, label: `▸ ${item.label}`, plain: true, onPress: () => void ctx.act.run(item.id) })]),
+ key,
+ )
+}
+
+/** True when Enter repeats the text the pending ask came from: the field holds the keys, so Enter again confirms. */
+export function isAskedAgain(ctx: Ctx, id: string, value: string): boolean {
+ const pending = ctx.state.pending
+ const entry = [...automateEntries(ctx.state), ...neuralEntries(ctx.state)].find(candidate => candidate.id === id)
+
+ return pending !== null && value.trim() !== '' && entry?.make?.(value)?.label === pending.label
+}
+
+/** A typed entry's field: Enter runs a read at once, or asks for a change; Enter again on the same text confirms it. */
+export function field(ctx: Ctx, id: string, label: string, placeholder: string, submitLabel = 'ask'): RenderElement {
+ if (ctx.kit.Input === undefined) return text(ctx, ` ${label}: this surface has no text field; /ruflo run ${id} <text> does the same`, { dimColor: true })
+
+ return ctx.kit.Input({ key: `in-${id}`, label, placeholder, submitLabel, onSubmit: value => (isAskedAgain(ctx, id, value) ? ctx.act.confirm() : void ctx.act.run(id, value)) })
+}
+
+/** The last run whose id has one of `prefixes`: what it was, how it exited, its cost note and a window of its lines. */
+export function resultRows(ctx: Ctx, prefixes: readonly string[]): RenderElement[] {
+ const { state, nowMs } = ctx
+ const mine = (id: string | undefined) => id !== undefined && prefixes.some(prefix => id.startsWith(prefix))
+ const result = mine(state.lab.result?.id) ? state.lab.result : null
+ const running = mine(state.lab.running?.id) ? state.lab.running : null
+ const right = running !== null ? `running ${Math.round((nowMs - running.startedAtMs) / 1000)}s` : result === null ? 'nothing run yet' : `${result.ok ? '✓' : '✗'} exit ${result.exitCode ?? 'n/a'} · ${ago(result.atMs, nowMs)}`
+ const rows: RenderElement[] = [rule(ctx, 'Result', right)]
+
+ if (running !== null) rows.push(text(ctx, ` ▸ ${running.label} … ${Math.floor(nowMs / 500) % 2 === 0 ? '█' : ' '}`, { color: THEME.warn }))
+ if (result === null) {
+ if (running === null) rows.push(text(ctx, ' ▸ press any entry: a $0 read shows here at once; wr, cpu and $$ ask first (y), then show here', { dimColor: true }))
+
+ return rows
+ }
+
+ rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad }))
+ if (result.note !== undefined) rows.push(text(ctx, ` ${result.note}`, { color: /money|models/i.test(result.note) ? THEME.bad : THEME.warn }))
+
+ const top = Math.max(0, Math.min(state.select.item, result.lines.length - RESULT_ROWS))
+
+ for (const line of result.lines.slice(top, top + RESULT_ROWS)) rows.push(text(ctx, ` ${line}`))
+ if (result.lines.length > RESULT_ROWS) {
+ rows.push(row(ctx, [text(ctx, ` lines ${top + 1}-${Math.min(result.lines.length, top + RESULT_ROWS)} of ${result.lines.length} `, { dimColor: true }), button(ctx, 'res-up', 'up', () => ctx.act.select(-1), { hotkey: 'k' }), button(ctx, 'res-down', 'down', () => ctx.act.select(1), { hotkey: 'j' })]))
+ }
+
+ return rows
+}
+
+/** One worker's light: running now (◌), failing (◐), has run (●), or never run here (○). */
+function light(ctx: Ctx, name: WorkerName): { glyph: string; color: string; line: string } {
+ const record = ctx.state.snapshot?.daemon?.workers.find(worker => worker.name === name)
+
+ if (ctx.state.lab.running?.id === `auto-worker-${name}`) return { glyph: '◌', color: THEME.warn, line: 'dispatching…' }
+ if (record === undefined || record.runs === 0) return { glyph: '○', color: THEME.info, line: 'never run here' }
+ if (record.failures > 0) return { glyph: '◐', color: THEME.warn, line: `${record.runs} runs · ${record.failures} failed` }
+
+ return { glyph: '●', color: THEME.ok, line: `${record.runs} runs · 0 failed` }
+}
+
+/** The twelve workers as cards, four to a row where they fit: light, name, purpose, runs, last run, and ▸ run. */
+function workerRows(ctx: Ctx): RenderElement[] {
+ const { state, nowMs } = ctx
+ const daemon = state.snapshot?.daemon ?? null
+ const perRow = ctx.columns >= 100 ? 4 : ctx.columns >= 72 ? 3 : 2
+ const width = Math.max(18, Math.floor((ctx.columns - perRow) / perRow))
+ const said = daemon === null ? 'no .claude-flow/daemon-state.json: the daemon has never run here' : `${daemon.running ? 'running' : 'stopped'} per daemon-state.json${daemon.savedAtMs !== undefined ? `, written ${ago(daemon.savedAtMs, nowMs)}` : ''}`
+ const rows: RenderElement[] = [rule(ctx, 'Workers', `daemon ${daemon?.running === true ? '● on' : '○ off'}`)]
+
+ rows.push(text(ctx, ` daemon: ${said}`, { color: daemon?.running === true ? THEME.ok : THEME.warn }))
+
+ const card = (name: WorkerName) => {
+ const lit = light(ctx, name)
+ const record = daemon?.workers.find(worker => worker.name === name)
+
+ return ctx.kit.Box({
+ flexDirection: 'column',
+ width,
+ borderStyle: 'single',
+ borderColor: lit.color,
+ key: `worker-${name}`,
+ children: [
+ ctx.kit.Text({ bold: true, color: lit.color, wrap: 'truncate-end', children: clip(`${lit.glyph} ${name.toUpperCase()}`, width - 2) }),
+ ctx.kit.Text({ color: THEME.info, wrap: 'truncate-end', children: clip(WORKER_ABOUT[name], width - 2) }),
+ ctx.kit.Text({ dimColor: true, wrap: 'truncate-end', children: clip(`${lit.line}${record?.lastRunMs !== undefined ? ` · ${ago(record.lastRunMs, nowMs)}` : ''}`, width - 2) }),
+ ctx.kit.Button({ key: `run-auto-worker-${name}`, label: '▸ run', plain: true, onPress: () => void ctx.act.run(`auto-worker-${name}`) }),
+ ],
+ })
+ }
+
+ for (let i = 0; i < WORKER_NAMES.length; i += perRow) rows.push(ctx.kit.Box({ flexDirection: 'row', gap: 1, key: `workers-${i}`, children: WORKER_NAMES.slice(i, i + perRow).map(card) }))
+
+ rows.push(text(ctx, ' ● has run · ◐ has failures · ○ never run here · ▸ run queues it for the daemon (asks first)', { dimColor: true }))
+ rows.push(strip(ctx, 'workers-strip', [
+ { id: 'auto-daemon-status', label: 'daemon status', cost: 'read' },
+ { id: 'auto-workers-list', label: 'list', cost: 'read' },
+ { id: 'auto-workers-status', label: 'dispatches', cost: 'read' },
+ { id: daemon?.running === true ? 'auto-daemon-stop' : 'auto-daemon-start', label: daemon?.running === true ? 'stop daemon' : 'start daemon', cost: daemon?.running === true ? 'writes' : 'local' },
+ ]))
+ rows.push(text(ctx, ` cancel: ${WORKER_CANCEL_WHY}`, { dimColor: true }))
+
+ return rows
+}
+
+/** One kanban card: the task, its type and agents, and the buttons that move it on. */
+function taskCard(ctx: Ctx, task: TaskRecord, width: number): RenderElement {
+ const agent = selection(ctx.state).agent
+
+ return ctx.kit.Box({
+ flexDirection: 'column',
+ key: `task-${task.id}`,
+ children: [
+ ctx.kit.Text({ bold: true, color: THEME.head, wrap: 'truncate-end', children: clip(`${task.type} · ${task.status}`, width - 2) }),
+ ctx.kit.Text({ color: THEME.info, wrap: 'truncate-end', children: clip(task.description || task.id, width - 2) }),
+ ...(task.assignedTo.length > 0 ? [ctx.kit.Text({ dimColor: true, wrap: 'truncate-end', children: clip(`→ ${task.assignedTo.join(', ')}`, width - 2) })] : []),
+ ctx.kit.Box({
+ flexDirection: 'row',
+ children: taskVerbs(task.status).map(verb => ctx.kit.Button({ key: `run-auto-task-${verb}-${task.id}`, label: `▸ ${verb === 'assign' ? `→${clip(agent?.name ?? agent?.type ?? 'agent', 10)}` : verb} `, plain: true, dimColor: verb === 'assign' && agent === null, onPress: () => void ctx.act.run(`auto-task-${verb}-${task.id}`) })),
+ }),
+ ],
+ })
+}
+
+/** The task board: pending, running and done side by side, from .claude-flow/tasks/store.json as last read. */
+function kanbanRows(ctx: Ctx): RenderElement[] {
+ const tasks = ctx.state.snapshot?.tasks ?? []
+ const agent = selection(ctx.state).agent
+ const width = Math.max(16, Math.floor((ctx.columns - 2) / 3))
+ const lanes = (['pending', 'running', 'done'] as const).map(lane => ({ lane, tasks: tasks.filter(task => laneOf(task.status) === lane) }))
+ const rows: RenderElement[] = [rule(ctx, 'Tasks', `${lanes.map(lane => `${lane.tasks.length} ${lane.lane}`).join(' · ')} · tasks/store.json`)]
+
+ rows.push(row(ctx, [text(ctx, ` assign goes to: ${agent === null ? 'no agent on disk (spawn one in Swarm)' : `${agent.name ?? agent.type} (${agent.status}) `}`, { color: THEME.info }), ...(agent !== null ? [button(ctx, 'task-agent-next', 'next agent', ctx.act.agentNext, { hotkey: 'a' })] : [])], 'task-agent'))
+ rows.push(
+ ctx.kit.Box({
+ flexDirection: 'row',
+ gap: 1,
+ key: 'kanban',
+ children: lanes.map(({ lane, tasks: list }) =>
+ ctx.kit.Box({
+ flexDirection: 'column',
+ width,
+ borderStyle: 'single',
+ borderColor: lane === 'running' ? THEME.warn : lane === 'done' ? THEME.ok : THEME.info,
+ key: `lane-${lane}`,
+ children: [
+ ctx.kit.Text({ bold: true, color: THEME.head, children: `${lane.toUpperCase()} (${list.length})` }),
+ ...(list.length === 0 ? [ctx.kit.Text({ dimColor: true, children: '(none)' })] : list.slice(0, 6).map(task => taskCard(ctx, task, width))),
+ ...(list.length > 6 ? [ctx.kit.Text({ dimColor: true, children: `+${list.length - 6} more` })] : []),
+ ],
+ }),
+ ),
+ }),
+ )
+ rows.push(field(ctx, 'auto-task-new', 'new task', 'bugfix: the login loop (a type first is optional; feature by default)'))
+ rows.push(strip(ctx, 'tasks-strip', [{ id: 'auto-task-list', label: 'list tasks', cost: 'read' }]))
+
+ return rows
+}
+
+const STATUS_COLOR = (status: string): string => (status === 'running' ? THEME.warn : status === 'completed' ? THEME.ok : /fail|cancel/.test(status) ? THEME.bad : THEME.info)
+
+function workflowRows(ctx: Ctx): RenderElement[] {
+ const { workflows, templates } = ctx.state.auto
+ const rows: RenderElement[] = [rule(ctx, 'Workflows', workflows === null ? 'not listed yet' : `${workflows.length} listed · workflows/store.json`)]
+
+ rows.push(strip(ctx, 'wf-strip', [{ id: 'auto-wf-list', label: 'list', cost: 'read' }, { id: 'auto-wf-templates', label: 'templates', cost: 'read' }]))
+ if (workflows === null) rows.push(text(ctx, ' ▸ list reads them (workflow_list): each row then gets status, run ($$), pause, resume, cancel', { dimColor: true }))
+
+ for (const workflow of (workflows ?? []).slice(0, 8)) {
+ rows.push(
+ row(
+ ctx,
+ [
+ ctx.kit.Text({ bold: true, color: THEME.head, children: clip(` ${workflow.name} `, 28).padEnd(28, '.') }),
+ ctx.kit.Text({ color: STATUS_COLOR(workflow.status), children: ` ${workflow.status} · ${workflow.steps} step${workflow.steps === 1 ? '' : 's'} ` }),
+ ...workflowVerbs(workflow.status).map(verb => ctx.kit.Button({ key: `run-auto-wf-${verb}-${workflow.id}`, label: ` ▸ ${verb === 'run' ? 'run $$' : verb}`, plain: true, dimColor: verb !== 'run', onPress: () => void ctx.act.run(`auto-wf-${verb}-${workflow.id}`) })),
+ ],
+ `wf-${workflow.id}`,
+ ),
+ )
+ }
+
+ for (const template of (templates ?? []).slice(0, 6)) {
+ rows.push(row(ctx, [text(ctx, ` template ${clip(template.name, 40)} · ${template.steps} steps `, { dimColor: true }), ctx.kit.Button({ key: `run-auto-tpl-new-${template.id}`, label: ' ▸ new', plain: true, onPress: () => void ctx.act.run(`auto-tpl-new-${template.id}`) })], `tpl-${template.id}`))
+ }
+
+ rows.push(field(ctx, 'auto-wf-new', 'new workflow', 'the prompt for its one task step, for the first agent on disk'))
+ rows.push(field(ctx, 'auto-wf-validate', 'validate', 'a workflow file in the project, e.g. workflows/build.json', 'check'))
+
+ return rows
+}
+
+function autopilotRows(ctx: Ctx): RenderElement[] {
+ const status = ctx.state.auto.autopilot
+ const rows: RenderElement[] = [rule(ctx, 'Autopilot', status === null ? 'not read yet' : status.isEnabled ? '● enabled' : '○ disabled')]
+
+ rows.push(
+ text(ctx, status === null ? ' ▸ status reads .claude-flow/data/autopilot-state.json and the task sources' : ` iteration ${status.iterations}/${status.maxIterations} · timeout ${status.timeoutMinutes} min · tasks ${status.done}/${status.total} (${status.percent}%) · ${status.sources.join(', ')}`, {
+ color: status?.isEnabled === true ? THEME.ok : THEME.info,
+ }),
+ )
+ rows.push(strip(ctx, 'ap-read', [{ id: 'auto-ap-status', label: 'status', cost: 'read' }, { id: 'auto-ap-predict', label: 'predict', cost: 'read' }, { id: 'auto-ap-learn', label: 'learn', cost: 'read' }, { id: 'auto-ap-log', label: 'log', cost: 'read' }]))
+ rows.push(strip(ctx, 'ap-write', [{ id: status?.isEnabled === true ? 'auto-ap-disable' : 'auto-ap-enable', label: status?.isEnabled === true ? 'disable' : 'enable', cost: 'writes' }, { id: 'auto-ap-reset', label: 'reset', cost: 'writes' }]))
+ rows.push(field(ctx, 'auto-ap-history', 'history', 'search past completions: auth refactor', 'search'))
+
+ return rows
+}
+
+function sessionRows(ctx: Ctx): RenderElement[] {
+ const sessions = ctx.state.auto.sessions
+ const rows: RenderElement[] = [rule(ctx, 'Sessions', sessions === null ? 'not listed yet' : `${sessions.length} saved`)]
+
+ rows.push(strip(ctx, 'ses-strip', [{ id: 'auto-ses-list', label: 'list', cost: 'read' }, { id: 'auto-ses-current', label: 'current', cost: 'read' }]))
+
+ for (const session of (sessions ?? []).slice(0, 8)) {
+ rows.push(
+ row(
+ ctx,
+ [
+ ctx.kit.Text({ bold: true, color: THEME.head, children: clip(` ${session.name} `, 30).padEnd(30, '.') }),
+ ctx.kit.Text({ color: THEME.info, children: ` ${session.savedAtMs !== undefined ? ago(session.savedAtMs, ctx.nowMs) : 'n/a'} ` }),
+ ...(['restore', 'export', 'delete'] as const).map(verb => ctx.kit.Button({ key: `run-auto-ses-${verb}-${session.id}`, label: ` ▸ ${verb}`, plain: true, dimColor: verb !== 'export', onPress: () => void ctx.act.run(`auto-ses-${verb}-${session.id}`) })),
+ ],
+ `ses-${session.id}`,
+ ),
+ )
+ }
+
+ rows.push(field(ctx, 'auto-ses-save', 'save as', 'a name for memory, agents and tasks as they are now', 'save'))
+
+ return rows
+}
+
+function configRows(ctx: Ctx): RenderElement[] {
+ const config = ctx.state.auto.config
+ const rows: RenderElement[] = [rule(ctx, 'Config', config === null ? 'not listed yet' : `${config.length} keys · ${config.filter(entry => entry.isSecret).length} masked`)]
+
+ rows.push(strip(ctx, 'cfg-strip', [{ id: 'auto-cfg-list', label: 'list', cost: 'read' }]))
+
+ for (const entry of (config ?? []).slice(0, 16)) {
+ rows.push(row(ctx, [ctx.kit.Text({ color: THEME.ok, children: ` ${entry.key.padEnd(28)} ` }), ctx.kit.Text({ color: entry.isSecret ? THEME.warn : THEME.info, wrap: 'truncate-end', children: clip(`${entry.shown} (${entry.source})`, Math.max(4, ctx.columns - 32)) })], `cfg-${entry.key}`))
+ }
+
+ rows.push(field(ctx, 'auto-cfg-get', 'get', 'a key: swarm.topology', 'get'))
+ rows.push(field(ctx, 'auto-cfg-set', 'set', 'a key and a value: swarm.maxAgents 8 (credentials are never set here)', 'set'))
+
+ return rows
+}
+
+/**
+ * Automation: the background workers as cards with their daemon, the task kanban, workflows, autopilot, sessions and
+ * config. Nothing runs on open: the cards and the board come from ruflo's own files; every list is a $0 click; every
+ * change asks first with its exact argv, and its cost or what it deletes on the confirm row.
+ */
+export function automateView(ctx: Ctx): RenderElement {
+ return col(
+ ctx,
+ [
+ ...resultRows(ctx, ['auto-']),
+ ...workerRows(ctx),
+ ...kanbanRows(ctx),
+ ...workflowRows(ctx),
+ ...autopilotRows(ctx),
+ ...sessionRows(ctx),
+ ...configRows(ctx),
+ text(ctx, ` $0 read, runs at once · wr writes · cpu local compute or a process · $$ calls a paid model · a field's Enter asks, Enter again (or y) runs`, { dimColor: true }),
+ ],
+ 'automate',
+ )
+}
diff --git a/plugins/ruflo-console/hooks/views/mh-lab.ts b/plugins/ruflo-console/hooks/views/mh-lab.ts
index 5ecbf4906a..99b92540b4 100644
--- a/plugins/ruflo-console/hooks/views/mh-lab.ts
+++ b/plugins/ruflo-console/hooks/views/mh-lab.ts
@@ -37,7 +37,9 @@ function entryRow(ctx: Ctx, entry: LabEntry, lead: number): RenderElement {
/** The last run: what it was, how it exited, what it cost, and a window of its lines. */
function resultRows(ctx: Ctx): RenderElement[] {
const { state, nowMs } = ctx
- const { result, running } = state.lab
+ // The runner's lab result is shared with the Automation and Learning Lab views: this panel shows MetaHarness runs only.
+ const result = state.lab.result?.id.startsWith('mh-') === true ? state.lab.result : null
+ const running = state.lab.running?.id.startsWith('mh-') === true ? state.lab.running : null
const right = running !== null ? `running ${Math.round((nowMs - running.startedAtMs) / 1000)}s` : result === null ? 'nothing run yet' : `${result.ok ? '✓' : '✗'} exit ${result.exitCode ?? 'n/a'} · ${ago(result.atMs, nowMs)}`
const rows: RenderElement[] = [rule(ctx, 'Result', right)]
diff --git a/plugins/ruflo-console/hooks/views/neural.ts b/plugins/ruflo-console/hooks/views/neural.ts
new file mode 100644
index 0000000000..4e94c3b83c
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/neural.ts
@@ -0,0 +1,99 @@
+import type { RenderElement } from 'claude-code'
+
+import { EPOCHS, PATTERNS, sparkline } from '../data/automate'
+import { field, resultRows, strip } from './automate'
+import { ago, col, count, kv, row, rule, text, THEME, type Ctx } from './common'
+
+const BAR = 24
+
+/** What ruflo's learning wrote to disk: trajectories, patterns and signals, and when it last adapted. */
+function intelligenceRows(ctx: Ctx): RenderElement[] {
+ const { state, nowMs } = ctx
+ const neural = state.snapshot?.neural ?? null
+ const rows: RenderElement[] = [rule(ctx, 'Intelligence', neural === null ? 'no .claude-flow/neural/stats.json' : 'neural/stats.json')]
+
+ rows.push(kv(ctx, 'trajectories', count(neural?.trajectories)))
+ rows.push(kv(ctx, 'patterns learned', count(neural?.patterns)))
+ rows.push(kv(ctx, 'signals', count(neural?.signals)))
+ rows.push(kv(ctx, 'last adapted', neural?.lastAdaptationMs !== undefined ? ago(neural.lastAdaptationMs, nowMs) : 'n/a'))
+ rows.push(kv(ctx, 'sona patterns', count(state.snapshot?.sona?.patterns)))
+ rows.push(strip(ctx, 'nn-read', [{ id: 'nn-status', label: 'status', cost: 'read' }, { id: 'nn-patterns', label: 'patterns', cost: 'read' }, { id: 'nn-analyze', label: 'memory', cost: 'read' }, { id: 'nn-intel', label: 'intelligence stats', cost: 'read' }]))
+
+ return rows
+}
+
+/**
+ * Training: a progress bar while a run is out (the CLI prints no epochs off a TTY, so it sweeps rather than fills), the
+ * loss of each run this session as a sparkline, and a row per pattern with its epoch buttons.
+ */
+function trainingRows(ctx: Ctx): RenderElement[] {
+ const { state, nowMs } = ctx
+ const trains = state.auto.trains
+ const last = trains[trains.length - 1]
+ const losses = trains.flatMap(run => (run.loss === undefined ? [] : [run.loss]))
+ const running = state.lab.running?.id.startsWith('nn-train') === true ? state.lab.running : null
+ const rows: RenderElement[] = [rule(ctx, 'Training', `${trains.length} run${trains.length === 1 ? '' : 's'} this session`)]
+
+ if (running !== null) {
+ const at = Math.floor((nowMs - running.startedAtMs) / 250) % (BAR * 2)
+ const head = at < BAR ? at : BAR * 2 - at - 1
+ const bar = Array.from({ length: BAR }, (_, i) => (Math.abs(i - head) <= 2 ? '█' : '░')).join('')
+
+ rows.push(text(ctx, ` ▸ ${running.label} [${bar}] ${Math.round((nowMs - running.startedAtMs) / 1000)}s`, { bold: true, color: THEME.warn }))
+ }
+
+ rows.push(
+ text(ctx, losses.length === 0 ? ' loss: n/a until a run ends (each run adds one point: Final Loss, else Avg Loss)' : ` loss ${sparkline(losses)} last ${losses[losses.length - 1]?.toExponential(3)} · low ${Math.min(...losses).toExponential(3)} · ${losses.length} point${losses.length === 1 ? '' : 's'}`, {
+ color: losses.length === 0 ? THEME.info : THEME.ok,
+ dimColor: losses.length === 0,
+ }),
+ )
+ if (last !== undefined) rows.push(text(ctx, ` last run: ${last.pattern} · ${last.epochs} epochs${last.seconds !== undefined ? ` · ${last.seconds}s` : ''}${last.backend !== undefined ? ` · ${last.backend}` : ''} · ${ago(last.atMs, nowMs)}`, { dimColor: true }))
+
+ for (const pattern of PATTERNS) {
+ rows.push(
+ row(
+ ctx,
+ [
+ ctx.kit.Text({ bold: true, color: THEME.warn, children: ' cpu ' }),
+ ctx.kit.Text({ bold: true, color: THEME.head, children: ` ${pattern} `.padEnd(16, '.') }),
+ ctx.kit.Text({ color: THEME.info, children: ' epochs ' }),
+ ...EPOCHS.map(epochs => ctx.kit.Button({ key: `run-nn-train-${pattern}-${epochs}`, label: ` ▸ ${epochs}`, plain: true, onPress: () => void ctx.act.run(`nn-train-${pattern}-${epochs}`) })),
+ ],
+ `train-${pattern}`,
+ ),
+ )
+ }
+
+ rows.push(field(ctx, 'nn-train', 'train', 'a pattern and epochs: coordination 150 (1-500)', 'train'))
+ rows.push(strip(ctx, 'nn-write', [{ id: 'nn-quantize', label: 'quantize patterns (Int8)', cost: 'local' }, { id: 'nn-compress', label: 'compress the store', cost: 'local' }]))
+
+ return rows
+}
+
+function routerRows(ctx: Ctx): RenderElement[] {
+ return [
+ rule(ctx, 'Router', 'which agent for this task? · $0, local'),
+ field(ctx, 'nn-route', 'route', 'a task: fix the login bug in auth.ts', 'route'),
+ field(ctx, 'nn-explain', 'explain', 'a task, to see why the router picks its agent', 'explain'),
+ field(ctx, 'nn-predict', 'predict', 'text for the trained models’ top predictions', 'predict'),
+ ]
+}
+
+/**
+ * The Learning Lab: what ruflo has learned (from its own files), training with a loss sparkline, and the router's
+ * "which agent?" and "why?". Opening it runs nothing; reads run on a click, training and compression ask first.
+ */
+export function neuralView(ctx: Ctx): RenderElement {
+ return col(
+ ctx,
+ [
+ ...resultRows(ctx, ['nn-']),
+ ...intelligenceRows(ctx),
+ ...trainingRows(ctx),
+ ...routerRows(ctx),
+ text(ctx, ' $0 read, runs at once · cpu local compute that writes .claude-flow/neural, asks first · no entry here calls a paid model', { dimColor: true }),
+ ],
+ 'neural',
+ )
+}
diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts
index 585f47c21c..99a6f17c07 100644
--- a/plugins/ruflo-console/hooks/views/pane.ts
+++ b/plugins/ruflo-console/hooks/views/pane.ts
@@ -8,6 +8,7 @@ import type { RenderElement } from 'claude-code'
import { HELP } from '../commands'
import { isBooting, isCompactPane, VIEWS, type ViewId } from '../state'
import { agentView } from './agent'
+import { automateView } from './automate'
import { claimsView } from './claims'
import { ago, button, clip, col, isBbs, row, setLook, text, THEME, type Ctx } from './common'
import { costView } from './cost'
@@ -18,6 +19,7 @@ import { approvalsView, eventsView, timelineView } from './manage'
import { memoryView } from './memory'
import { menuView } from './menu'
import { metaharnessView } from './metaharness'
+import { neuralView } from './neural'
import { missionsView } from './missions'
import { overviewView } from './overview'
import { paletteView } from './palette'
@@ -53,6 +55,8 @@ const BODIES: Record<ViewId, (ctx: Ctx) => RenderElement> = {
xruv: xruvView,
terminal: terminalView,
skills: skillsView,
+ automate: automateView,
+ neural: neuralView,
agent: agentView,
}
diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh
index 5dae65d642..25a592300f 100755
--- a/plugins/ruflo-console/scripts/smoke.sh
+++ b/plugins/ruflo-console/scripts/smoke.sh
@@ -72,7 +72,7 @@ step "13. marketplace lists ruflo-console"
grep -q '"name": "ruflo-console"' "$REPO/.claude-plugin/marketplace.json" && ok || bad "missing marketplace entry"
step "14. pure specs pass under vitest"
-if (cd "$REPO" && npx vitest run plugins/ruflo-console/tests/pure.spec.ts plugins/ruflo-console/tests/vendored-types.spec.ts plugins/ruflo-console/tests/mh-lab.spec.ts>/dev/null 2>&1); then ok; else bad "vitest specs failed"; fi
+if (cd "$REPO" && npx vitest run plugins/ruflo-console/tests/pure.spec.ts plugins/ruflo-console/tests/vendored-types.spec.ts plugins/ruflo-console/tests/mh-lab.spec.ts plugins/ruflo-console/tests/automate.spec.ts>/dev/null 2>&1); then ok; else bad "vitest specs failed"; fi
printf "\n%d passed, %d failed\n" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]]
diff --git a/plugins/ruflo-console/tests/automate.spec.ts b/plugins/ruflo-console/tests/automate.spec.ts
new file mode 100644
index 0000000000..91076a02f3
--- /dev/null
+++ b/plugins/ruflo-console/tests/automate.spec.ts
@@ -0,0 +1,170 @@
+/**
+ * The Automation view's and the Learning Lab's pure parts under vitest: the catalog's invariants (fixed argv, what asks
+ * first, what says it spends or deletes), the checks every typed value passes, the secret masks, and the readers
+ * against what the CLI printed. Run with
+ * npx vitest run plugins/ruflo-console/tests/automate.spec.ts
+ */
+import { describe, expect, it } from 'vitest'
+
+import { automateEntries, configGet, configSet, historySpec, sessionSave, sessionSpec, taskCreate, taskVerbs, workflowCreate, workflowSpec, workflowValidate, workflowVerbs } from '../hooks/automate'
+import { configKeyOf, configValueOf, freeText, keyValueOf, laneOf, MASK, parseAutopilot, parseConfig, parseSessions, parseTemplates, parseTrain, parseWorkflows, relPathOf, sparkline } from '../hooks/data/automate'
+import { neuralEntries, routeSpec, trainArgs, trainSpec } from '../hooks/neural'
+import { newState } from '../hooks/state'
+import { AUTO_OUT, FAKE_SECRET, SESSION_ID, WF_ID } from './fixtures/automate'
+
+const listed = () => {
+ const state = newState({})
+
+ state.auto.workflows = parseWorkflows(AUTO_OUT['workflow-list'] ?? '')
+ state.auto.templates = parseTemplates(AUTO_OUT['template-list'] ?? '')
+ state.auto.sessions = parseSessions(AUTO_OUT['session-list'] ?? '')
+
+ return state
+}
+
+describe('the catalog', () => {
+ it('every id is unique and prefixed; no argv reaches a shell; reads alone skip the confirm', () => {
+ const state = listed()
+ const entries = [...automateEntries(state), ...neuralEntries(state)]
+ const ids = entries.map(entry => entry.id)
+
+ expect(new Set(ids).size).toBe(ids.length)
+ expect(ids.every(id => /^(auto|nn)-/.test(id))).toBe(true)
+
+ for (const entry of entries) {
+ const spec = entry.spec
+
+ if (spec === undefined || spec === null) continue
+ expect(spec.args.some(word => /^(sh|bash|-c)$/.test(word)), entry.id).toBe(false)
+ expect(spec.lab, entry.id).toBe(entry.id)
+ if (spec.isReadOnly !== true) expect(spec.note, entry.id).toBeDefined()
+ }
+ })
+
+ it('a workflow run says it costs money; restore overwrites; delete deletes; worker cancel is n/a with the reason', () => {
+ const state = listed()
+ const entries = automateEntries(state)
+ const run = workflowSpec('run', WF_ID, state)
+
+ expect(run?.args).toEqual(['mcp', 'exec', '-t', 'workflow_execute', '-p', JSON.stringify({ workflowId: WF_ID })])
+ expect(run?.isReadOnly).toBeUndefined()
+ expect(run?.note).toMatch(/^COSTS MONEY/)
+ expect(sessionSpec('restore', SESSION_ID)?.note).toMatch(/OVERWRITES/)
+ expect(sessionSpec('delete', SESSION_ID)?.note).toMatch(/DELETES/)
+ expect(entries.find(entry => entry.id === 'auto-worker-cancel')).toMatchObject({ spec: null, why: expect.stringMatching(/per-process/) })
+ expect(entries.filter(entry => entry.id.startsWith('auto-worker-') && entry.spec !== null && entry.spec !== undefined)).toHaveLength(12)
+ expect(entries.find(entry => entry.id === 'auto-worker-ultralearn')?.spec?.args).toEqual(['hooks', 'worker', 'dispatch', '--trigger', 'ultralearn'])
+ expect(entries.map(entry => entry.id)).toEqual(expect.arrayContaining([`auto-wf-status-${WF_ID}`, `auto-wf-run-${WF_ID}`, `auto-ses-export-${SESSION_ID}`, 'auto-tpl-new-template-1790990000001-zz9']))
+ expect(neuralEntries(state).every(entry => !/COSTS MONEY/.test(entry.spec?.note ?? ''))).toBe(true)
+ })
+
+ it('verbs follow status: running pauses, paused resumes, pending tasks are assigned, failed ones retried', () => {
+ expect(workflowVerbs('running')).toEqual(['status', 'pause', 'cancel'])
+ expect(workflowVerbs('paused')).toContain('resume')
+ expect(workflowVerbs('pending')).toContain('run')
+ expect(taskVerbs('pending')).toEqual(['assign', 'cancel'])
+ expect(taskVerbs('in_progress')).toEqual(['done', 'cancel'])
+ expect(taskVerbs('failed')).toEqual(['retry'])
+ expect(taskVerbs('completed')).toEqual([])
+ expect(['pending', 'in_progress', 'completed', 'cancelled', 'weird'].map(laneOf)).toEqual(['pending', 'running', 'done', 'done', 'pending'])
+ })
+})
+
+describe('typed values', () => {
+ it('free text is bounded, printable and never a flag', () => {
+ expect(freeText('fix the login bug')).toBe('fix the login bug')
+ expect(freeText('--force')).toBeNull()
+ expect(freeText('')).toBeNull()
+ expect(freeText('x'.repeat(201))).toBeNull()
+ expect(freeText('a\u0000b')).toBe('a b')
+ })
+
+ it('config keys, values, pairs and paths', () => {
+ expect(configKeyOf('swarm.maxAgents')).toBe('swarm.maxAgents')
+ expect(configKeyOf('__proto__.x')).toBeNull()
+ expect(configKeyOf('a..b')).toBeNull()
+ expect(configValueOf('8')).toBe(8)
+ expect(configValueOf('true')).toBe(true)
+ expect(configValueOf('mesh')).toBe('mesh')
+ expect(keyValueOf('swarm.topology mesh')).toEqual({ key: 'swarm.topology', value: 'mesh' })
+ expect(keyValueOf('swarm.topology')).toBeNull()
+ expect(relPathOf('workflows/build.json')).toBe('workflows/build.json')
+ expect(relPathOf('../etc/passwd')).toBeNull()
+ expect(relPathOf('/etc/passwd')).toBeNull()
+ expect(relPathOf('-rf')).toBeNull()
+ })
+
+ it('typed specs build one fixed argv each, and refuse what fails the checks', () => {
+ const state = newState({})
+
+ expect(taskCreate('bugfix: the login loop')?.args).toEqual(['mcp', 'exec', '-t', 'task_create', '-p', JSON.stringify({ type: 'bugfix', description: 'the login loop' })])
+ expect(taskCreate('ship it: now')?.args[5]).toBe(JSON.stringify({ type: 'feature', description: 'ship it: now' }))
+ expect(taskCreate('-x')).toBeNull()
+ expect(historySpec('auth refactor')?.args).toEqual(['autopilot', 'history', '--query', 'auth refactor', '--json'])
+ expect(sessionSave(state, 'before-refactor')?.args).toEqual(['mcp', 'exec', '-t', 'session_save', '-p', '{"name":"before-refactor"}'])
+ expect(workflowValidate('../x.json')).toBeNull()
+ expect(workflowCreate(state, 'review the diff')?.label).toContain('no agent yet')
+ expect(trainArgs('coordination 150')).toEqual({ pattern: 'coordination', epochs: 150 })
+ expect(trainArgs('coordination 9999')).toBeNull()
+ expect(trainArgs('nope 10')).toBeNull()
+ expect(trainSpec(state, 'testing')?.args).toEqual(['neural', 'train', '--pattern', 'testing', '--epochs', '20'])
+ expect(routeSpec('fix the login bug')?.args).toEqual(['hooks', 'route', '--task', 'fix the login bug', '--format', 'json'])
+ })
+})
+
+describe('secrets', () => {
+ it('config_list values are masked as they are parsed: by key, and by a credential-shaped value', () => {
+ const rows = parseConfig(AUTO_OUT['config-list'] ?? '') ?? []
+
+ expect(rows.map(row => [row.key, row.shown])).toEqual([
+ ['logging.level', 'info'],
+ ['providers.anthropic.apiKey', MASK],
+ ['swarm.maxAgents', '8'],
+ ['webhook.url', MASK],
+ ])
+ expect(JSON.stringify(rows)).not.toContain(FAKE_SECRET)
+ })
+
+ it('config get never prints a secret; config set refuses a secret key or value outright', () => {
+ const lines = configGet('providers.anthropic.apiKey')?.read?.(AUTO_OUT['config-get-secret'] ?? '', '', true) ?? []
+
+ expect(lines.join('\n')).not.toContain(FAKE_SECRET)
+ expect(lines[0]).toBe(`providers.anthropic.apiKey = ${MASK}`)
+ expect(configSet('providers.anthropic.apiKey abc')).toBeNull()
+ expect(configSet(`webhook.url ${FAKE_SECRET}`)).toBeNull()
+ expect(configSet('swarm.maxAgents 8')?.args).toEqual(['mcp', 'exec', '-t', 'config_set', '-p', '{"key":"swarm.maxAgents","value":8}'])
+ })
+
+ it('a session export shows its id and path, never its data', () => {
+ const lines = sessionSpec('export', SESSION_ID)?.read?.(`Result:\n${JSON.stringify({ sessionId: SESSION_ID, path: `session-${SESSION_ID}.json`, data: { memory: FAKE_SECRET }, exportedAt: '2026-10-02T10:00:00.000Z' })}`, '', true) ?? []
+
+ expect(lines).toEqual([`${SESSION_ID} → session-${SESSION_ID}.json`, 'exported 2026-10-02T10:00:00.000Z'])
+ })
+})
+
+describe('readers', () => {
+ it('workflows, templates, sessions and autopilot from their JSON', () => {
+ expect(parseWorkflows(AUTO_OUT['workflow-list'] ?? '')).toEqual([{ id: WF_ID, name: 'ship the console', status: 'pending', steps: 1, createdAtMs: Date.parse('2026-10-02T10:00:00.000Z') }])
+ expect(parseWorkflows(AUTO_OUT['workflow-empty'] ?? '')).toEqual([])
+ expect(parseWorkflows('nope')).toBeNull()
+ expect(parseSessions(AUTO_OUT['session-list'] ?? '')?.[0]?.name).toBe('before-refactor')
+ expect(parseAutopilot(AUTO_OUT['autopilot-status'] ?? '')).toEqual({ isEnabled: false, iterations: 0, maxIterations: 50, timeoutMinutes: 240, done: 0, total: 0, percent: 100, sources: ['team-tasks', 'swarm-tasks', 'file-checklist'] })
+ })
+
+ it('a training run: Final Loss from the native table, Avg Loss from the JS one; the sparkline rises with the loss', () => {
+ expect(parseTrain(AUTO_OUT['neural-train'] ?? '', 5)).toEqual({ pattern: 'coordination', epochs: 5, atMs: 5, loss: 0.004289, seconds: 0.4, backend: 'native' })
+ expect(parseTrain(AUTO_OUT['neural-train-js'] ?? '', 6)?.loss).toBe(0.0213)
+ expect(parseTrain('Training failed', 7)).toBeNull()
+ expect(sparkline([0.5, 0.25, 0])).toBe('█▅▁')
+ expect(sparkline([1])).toBe('▄')
+ })
+
+ it('a train spec keeps its run for the sparkline; the route reader names the pick and the runner-up', () => {
+ const state = newState({})
+ const lines = trainSpec(state, 'coordination 5')?.read?.(AUTO_OUT['neural-train'] ?? '', '', true) ?? []
+
+ expect(state.auto.trains).toHaveLength(1)
+ expect(lines).toContain('Final Loss: 4.289e-3')
+ expect(routeSpec('fix the login bug')?.read?.(AUTO_OUT['hooks-route'] ?? '', '', true)).toEqual(['→ tester · 49% · semantic-native · pattern testing-task', ' or reviewer · 39%', 'Semantic similarity to "testing-task" pattern (49%)'])
+ })
+})
diff --git a/plugins/ruflo-console/tests/fixtures/automate.ts b/plugins/ruflo-console/tests/fixtures/automate.ts
new file mode 100644
index 0000000000..36645d6982
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/automate.ts
@@ -0,0 +1,83 @@
+/**
+ * What @claude-flow/cli 3.51.1 printed for the Automation and Learning Lab entries, captured in a scratch project
+ * (`git init` under /tmp). The workflow, session and secret config rows are made up in the same shapes; every secret
+ * here is fake and exists to prove it is never drawn.
+ */
+const mcp = (tool: string, result: unknown) => `[INFO] Executing tool: ${tool}\n\n[OK] Tool executed in 6.64ms\n\nResult:\n${JSON.stringify(result, null, 2)}\n`
+
+export const WF_ID = 'workflow-1790990000000-abc123'
+export const SESSION_ID = 'session-1790990000000-q1w2e3'
+export const FAKE_SECRET = 'sk-not-a-real-key-console-test'
+
+export const AUTO_OUT: Record<string, string> = {
+ 'workflow-list': mcp('workflow_list', { workflows: [{ workflowId: WF_ID, name: 'ship the console', status: 'pending', stepCount: 1, createdAt: '2026-10-02T10:00:00.000Z' }], total: 1, filters: {} }),
+ 'workflow-empty': mcp('workflow_list', { workflows: [], total: 0, filters: {} }),
+ 'template-list': mcp('workflow_template', { action: 'list', templates: [{ templateId: 'template-1790990000001-zz9', name: 'ship Template', stepCount: 1, createdAt: '2026-10-02T10:00:00.000Z' }], total: 1 }),
+ 'session-list': mcp('session_list', { sessions: [{ sessionId: SESSION_ID, name: 'before-refactor', savedAt: '2026-10-02T09:00:00.000Z', stats: null }], total: 1, limit: 20 }),
+ 'config-list': mcp('config_list', {
+ configs: [
+ { key: 'logging.level', value: 'info', source: 'stored' },
+ { key: 'providers.anthropic.apiKey', value: FAKE_SECRET, source: 'stored' },
+ { key: 'swarm.maxAgents', value: 8, source: 'stored' },
+ { key: 'webhook.url', value: FAKE_SECRET, source: 'stored' },
+ ],
+ total: 4,
+ scope: 'default',
+ }),
+ 'config-get-secret': mcp('config_get', { key: 'providers.anthropic.apiKey', value: FAKE_SECRET, scope: 'default', exists: true, source: 'stored' }),
+ 'autopilot-status': '{\n "enabled": false,\n "sessionId": "6d2c7525-679a-4503-8842-8cdb44defdf1",\n "iterations": 0,\n "maxIterations": 50,\n "timeoutMinutes": 240,\n "elapsedMs": 0,\n "tasks": {\n "completed": 0,\n "total": 0,\n "percent": 100\n },\n "taskSources": [\n "team-tasks",\n "swarm-tasks",\n "file-checklist"\n ]\n}\n',
+ 'neural-train': [
+ '',
+ 'Neural Pattern Training (RuVector WASM)',
+ '───────────────────────────────────────────────────────',
+ '✅ Using native better-sqlite3',
+ 'Training complete: 5 epochs in 0.4s',
+ '',
+ '+--------------------+----------------------------------+',
+ '| Metric | Value |',
+ '+--------------------+----------------------------------+',
+ '| Pattern Type | coordination |',
+ '| Epochs | 5 |',
+ '| Batch Size | 32 |',
+ '| Total Time | 0.4s |',
+ '| Backend | native (@ruvector/ruvllm Trai... |',
+ '| Final Loss | 4.289e-3 |',
+ '| Checkpoint | /tmp/automate-probe/.claude-f... |',
+ '+--------------------+----------------------------------+',
+ '',
+ '✓ 5 patterns saved to /tmp/automate-probe/.claude-flow/neural/patterns.json',
+ ].join('\n'),
+ 'neural-train-js': '| Pattern Type | testing |\n| Epochs | 10 |\n| Total Time | 1.2s |\n| Avg Loss | 0.0213 |\n',
+ 'hooks-route': [
+ '[hooks] Semantic router initialized: native VectorDb (HNSW, 16k+ routes/s), embedder=hash',
+ JSON.stringify(
+ {
+ task: 'fix the login bug',
+ routing: { method: 'semantic-native', backend: 'native VectorDb (HNSW)', latencyMs: 0.105 },
+ matchedPattern: 'testing-task',
+ matched: true,
+ primaryAgent: { type: 'tester', confidence: 0.49, reason: 'Semantic similarity to "testing-task" pattern (49%)' },
+ alternativeAgents: [{ type: 'reviewer', confidence: 0.39, reason: 'Alternative agent for reviewer capabilities' }],
+ },
+ null,
+ 2,
+ ),
+ ].join('\n'),
+}
+
+/** Answers the Automation and Learning Lab argv from AUTO_OUT; null for anything else (the caller falls back). */
+export function autoAnswer(argv: readonly string[]): { exitCode: number; stdout: string; stderr: string } | null {
+ const line = argv.join(' ')
+ const out = (name: string) => ({ exitCode: 0, stdout: AUTO_OUT[name] ?? '', stderr: '' })
+
+ if (line.includes('workflow_list')) return out('workflow-list')
+ if (line.includes('workflow_template')) return out('template-list')
+ if (line.includes('session_list')) return out('session-list')
+ if (line.includes('config_list')) return out('config-list')
+ if (line.includes('config_get')) return out('config-get-secret')
+ if (line.includes('autopilot status')) return out('autopilot-status')
+ if (line.includes('neural train')) return out('neural-train')
+ if (line.includes('hooks route')) return out('hooks-route')
+
+ return null
+}
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index 39a1187e2b..1f0a9c1b00 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -1,6 +1,7 @@
import type { TestBody } from 'claude-code/testing'
import { describe, expect, mock, test } from 'claude-code/testing'
+import { autoAnswer, FAKE_SECRET, WF_ID } from './fixtures/automate'
import { HIVE_FILES, RAFT_ID, WORKERS } from './fixtures/hive'
import { MISSION_OBSERVATION } from './fixtures/missions'
import { HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'
@@ -369,4 +370,82 @@ describe('views', () => {
expect(textOf(await pane.drawn())).toContain('no area "nope"')
await pane.unmount()
})
+
+ test('automate: worker cards and the kanban from disk, nothing run on open; a read runs at once, a spend asks first, secrets masked', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+ const mine = () => world.runs.map(argv => argv.slice(4)).filter(argv => /workflow_|session_|config_|task_|neural|autopilot|hooks (route|explain|worker)|daemon/.test(argv.join(' ')))
+
+ world.respond = argv => autoAnswer(argv) ?? cliAnswer(argv)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const { text, rasters } = await drawn($, 'automate')
+
+ expect(rasters).toEqual(['header', 'title'])
+ expect(text).toContain('● MAP')
+ expect(text).toContain('137 runs · 0 failed')
+ expect(text).toContain('◐ OPTIMIZE')
+ expect(text).toContain('○ ULTRALEARN')
+ expect(text).toContain('PENDING (1)')
+ expect(text).toContain('Build the console overview')
+ expect(text).toMatch(/WORKFLOWS[\s\S]*AUTOPILOT[\s\S]*SESSIONS[\s\S]*CONFIG/)
+ expect(mine()).toEqual([])
+
+ const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN })
+
+ await pane.press({ key: 'run-auto-wf-list' })
+ expect(mine()).toEqual([['mcp', 'exec', '-t', 'workflow_list', '-p', '{"limit":20}']])
+ expect(textOf(await pane.drawn())).toContain('ship the console')
+
+ await pane.press({ key: `run-auto-wf-run-${WF_ID}` })
+ const asked = textOf(await pane.drawn())
+
+ expect(asked).toContain(`Confirm: run workflow ${WF_ID} (its task steps call a model)?`)
+ expect(asked).toContain('COSTS MONEY')
+ expect(mine()).toHaveLength(1)
+ await pane.press({ key: 'confirm' })
+ expect(mine()[1]).toEqual(['mcp', 'exec', '-t', 'workflow_execute', '-p', JSON.stringify({ workflowId: WF_ID })])
+
+ await pane.press({ key: 'run-auto-cfg-list' })
+ const config = textOf(await pane.drawn())
+
+ expect(config).toContain('providers.anthropic.apiKey')
+ expect(config).toContain('•••••• (hidden)')
+ expect(config).not.toContain(FAKE_SECRET)
+ await pane.unmount()
+ })
+
+ test('learning lab: what was learned from disk; training asks first, runs one argv and draws the loss; route runs at once', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+ const mine = () => world.runs.map(argv => argv.slice(4).join(' ')).filter(line => /^(neural|hooks (route|explain)|mcp exec -t (neural|hooks_intelligence))/.test(line))
+
+ world.respond = argv => autoAnswer(argv) ?? cliAnswer(argv)
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const { text, rasters } = await drawn($, 'neural')
+
+ expect(rasters).toEqual(['header', 'title'])
+ expect(text).toMatch(/trajectories\s+30\.8k/)
+ expect(text).toMatch(/TRAINING[\s\S]*ROUTER/)
+ expect(mine()).toEqual([])
+
+ const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
+
+ await pane.press({ key: 'run-nn-train-coordination-20' })
+ expect(textOf(await pane.drawn())).toContain('Confirm: train coordination patterns for 20 epochs?')
+ expect(mine()).toEqual([])
+ await pane.press({ key: 'confirm' })
+ expect(mine()).toEqual(['neural train --pattern coordination --epochs 20'])
+
+ const trained = textOf(await pane.drawn())
+
+ expect(trained).toContain('Final Loss: 4.289e-3')
+ expect(trained).toMatch(/loss ▄ +last 4\.289e-3/)
+
+ await pane.input({ key: 'in-nn-route', text: 'fix the login bug', kind: 'submit' })
+ expect(mine()[1]).toBe('hooks route --task fix the login bug --format json')
+ expect(textOf(await pane.drawn())).toContain('→ tester · 49%')
+ await pane.unmount()
+ })
})