From d1d4dab56d616614781a38709f8588c908762aef Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 15:09:02 -0400 Subject: [PATCH 1/6] fix(ruflo-console): sentries start /loop as a command, and every result is a bordered status card with aligned tables (0.33.21) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sentry "▶ start" confirmed but created no loop: the console sent "/loop …" with $.prompt.submit, which gives the model a message that merely looks like a command. It now runs as the /loop command ($.command.run, as if typed); mid-turn it is placed in the prompt box and says so; a refusal is reported. The Security page shows the outcome under the sentries as a card (✓/✗, title, age, wrapped detail, next step). Results in general: every view's Result panel (Security, Dev Tools, Automate, Evolve, Memory lab, MetaHarness lab, Vector, x.ruv, Plugin catalog) is now one round border coloured by how the run went (green, red, amber while running, dim when idle). The CLI's ASCII tables had lost their padding by the time they were shown; they are read back as cells and drawn again with box characters and aligned columns at the one place results are stored (runner.ts), and blank-line runs are collapsed. Co-Authored-By: RuFlo --- .../ruflo-console/.claude-plugin/plugin.json | 2 +- plugins/ruflo-console/hooks/loops.ts | 32 ++++++- plugins/ruflo-console/hooks/mission-types.ts | 2 +- plugins/ruflo-console/hooks/result-lines.ts | 78 +++++++++++++++++ plugins/ruflo-console/hooks/runner.ts | 3 +- plugins/ruflo-console/hooks/version.ts | 2 +- plugins/ruflo-console/hooks/views/automate.ts | 5 +- plugins/ruflo-console/hooks/views/devtools.ts | 5 +- plugins/ruflo-console/hooks/views/evolve.ts | 5 +- .../ruflo-console/hooks/views/memory-lab.ts | 5 +- plugins/ruflo-console/hooks/views/mh-lab.ts | 5 +- .../hooks/views/plugin-catalog.ts | 3 +- plugins/ruflo-console/hooks/views/secure.ts | 5 +- plugins/ruflo-console/hooks/views/sentries.ts | 10 +++ .../ruflo-console/hooks/views/status-card.ts | 49 +++++++++++ plugins/ruflo-console/hooks/views/vector.ts | 5 +- plugins/ruflo-console/hooks/views/xruv.ts | 5 +- plugins/ruflo-console/scripts/smoke.sh | 4 +- plugins/ruflo-console/tests/loops.spec.ts | 84 +++++++++++++++++-- .../ruflo-console/tests/result-lines.spec.ts | 63 ++++++++++++++ .../ruflo-console/tests/status-card.spec.ts | 69 +++++++++++++++ 21 files changed, 407 insertions(+), 34 deletions(-) create mode 100644 plugins/ruflo-console/hooks/result-lines.ts create mode 100644 plugins/ruflo-console/hooks/views/status-card.ts create mode 100644 plugins/ruflo-console/tests/result-lines.spec.ts create mode 100644 plugins/ruflo-console/tests/status-card.spec.ts diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json index 23c7ee1464..7dcea1338e 100644 --- a/plugins/ruflo-console/.claude-plugin/plugin.json +++ b/plugins/ruflo-console/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-console", "description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.", - "version": "0.33.20", + "version": "0.33.21", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-console/hooks/loops.ts b/plugins/ruflo-console/hooks/loops.ts index edcabe42df..db1507ce04 100644 --- a/plugins/ruflo-console/hooks/loops.ts +++ b/plugins/ruflo-console/hooks/loops.ts @@ -138,13 +138,37 @@ export type LoopActions = { manage: () => void } +/** A `/loop` input: the arguments after the command name. */ +const LOOP_COMMAND = /^\/loop(?:\s+([\s\S]*))?$/ + export function loopActions(state: State, host: Host, runner: Runner): LoopActions { const cfg = loopsOf(state) - const say = (label: string, ok: boolean, detail: string) => { - mcOf(state).last = { label, ok, detail } + const say = (label: string, ok: boolean, detail: string, next?: string) => { + mcOf(state).last = { label, ok, detail, atMs: Date.now(), ...(next !== undefined && { next }) } host.invalidate() } - const send = (text: string): Promise => (state.turnActive ? host.fillPrompt(text).then(() => undefined) : host.submitPrompt(text)) + // `/loop` is a slash command, so it runs as one (`$.command.run`, as if typed). Submitting it as a prompt sends the model a message that + // merely looks like a command: no loop is created. Any other text (the manage ask) is a real prompt. Mid-turn the command can only wait in + // the prompt box, and the person is told so: nothing starts until they press Enter, and a silent fill looked like a click that did nothing. + const send = async (text: string): Promise => { + if (state.turnActive) { + const isFilled = await host.fillPrompt(text) + + return say( + isFilled ? 'waiting in your prompt box' : 'could not fill the prompt box', + isFilled, + isFilled ? 'Claude is mid-turn, so the command is in your prompt box.' : `the prompt box is not available (a dialog is open?); type it yourself: ${plain(text, 100)}`, + isFilled ? 'press Enter in the prompt box to start it' : 'close the dialog, then start it again', + ) + } + + const loop = LOOP_COMMAND.exec(text) + + if (loop === null) return host.submitPrompt(text) + + await host.runSlash('loop', loop[1] ?? '') + say('loop command sent', true, 'Sent as /loop: it starts a Claude Code turn, and Claude reports what it scheduled in the conversation.', 'watch the conversation; ☰ list / stop my sentries shows and stops it') + } const ask = (text: string, label: string, note: string): void => runner.ask( { @@ -158,7 +182,7 @@ export function loopActions(state: State, host: Host, runner: Runner): LoopActio try { await send(text) } catch (error) { - say('Claude did not take it', false, plain(error instanceof Error ? error.message : String(error), 140)) + say('Claude did not take it', false, plain(error instanceof Error ? error.message : String(error), 140), 'check the command is offered here (/reload-plugins), then start it again') } }, } satisfies ActionSpec, diff --git a/plugins/ruflo-console/hooks/mission-types.ts b/plugins/ruflo-console/hooks/mission-types.ts index 82858e33c8..19883f8fae 100644 --- a/plugins/ruflo-console/hooks/mission-types.ts +++ b/plugins/ruflo-console/hooks/mission-types.ts @@ -42,7 +42,7 @@ export type McState = { /** AIDefence's verdict on the goal (null: not screened yet or the screen is off), and whether the screen is on. */ screen: Screen | null isScreenOn: boolean - last: { label: string; ok: boolean; detail: string } | null + last: { label: string; ok: boolean; detail: string; atMs?: number; next?: string } | null } export type MissionActions = { diff --git a/plugins/ruflo-console/hooks/result-lines.ts b/plugins/ruflo-console/hooks/result-lines.ts new file mode 100644 index 0000000000..314f75e7c8 --- /dev/null +++ b/plugins/ruflo-console/hooks/result-lines.ts @@ -0,0 +1,78 @@ +/** + * Tidies the lines of a result before any view draws them. The CLI prints its tables as ASCII (`+----+` rules and `| cell | cell |` rows); + * by the time the console has cleaned the text for display the padding is gone and the columns no longer line up. This reads such a block + * back as cells and draws it again with box characters and aligned columns. Everything else passes through, only with trailing space + * removed and runs of blank lines collapsed to one. Pure, bounded, and it never invents text: a block it cannot read as a table stays as it was. + */ + +const RULE = /^\s*\+[-=+]{2,}\+\s*$/ +const ROW = /^\s*\|.*\|\s*$/ +/** The widest a column is drawn; a longer cell is cut with an ellipsis. */ +const MAX_CELL = 48 +/** The most table lines read as one block (a runaway block stays as plain lines). */ +const MAX_BLOCK = 200 + +const cellsOf = (line: string): string[] => line.trim().slice(1, -1).split('|').map(cell => cell.trim()) +const cut = (cell: string): string => (cell.length > MAX_CELL ? `${cell.slice(0, MAX_CELL - 1)}…` : cell) + +/** One table block (rules and rows, in order) as box-drawn lines, or null when it is not a rectangular table of at least two rows. */ +function drawTable(block: readonly string[]): string[] | null { + const rows = block.filter(line => ROW.test(line)).map(cellsOf) + + if (rows.length < 2) return null + + const columns = rows[0]?.length ?? 0 + + if (columns < 2 || rows.some(row => row.length !== columns)) return null + + const widths = Array.from({ length: columns }, (_, column) => Math.max(1, ...rows.map(row => cut(row[column] ?? '').length))) + const rule = (left: string, mid: string, right: string): string => `${left}${widths.map(width => '─'.repeat(width + 2)).join(mid)}${right}` + const draw = (row: readonly string[]): string => `│${row.map((cell, column) => ` ${cut(cell).padEnd(widths[column] ?? 0)} `).join('│')}│` + // The first row is the header when a rule sits right under it (the CLI's table shape). + const hasHeader = block.findIndex(line => ROW.test(line)) + 1 < block.length && RULE.test(block[block.findIndex(line => ROW.test(line)) + 1] ?? '') + const [head, ...rest] = rows + + return [rule('┌', '┬', '┐'), ...(hasHeader && head !== undefined ? [draw(head), rule('├', '┼', '┤')] : head !== undefined ? [draw(head)] : []), ...rest.map(draw), rule('└', '┴', '┘')] +} + +export function prettyLines(lines: readonly string[]): string[] { + const out: string[] = [] + let block: string[] = [] + let blank = false + + const flush = (): void => { + if (block.length === 0) return + + const drawn = block.length <= MAX_BLOCK ? drawTable(block) : null + + out.push(...(drawn ?? block.map(line => line.trimEnd()))) + block = [] + } + + for (const raw of lines) { + if (RULE.test(raw) || ROW.test(raw)) { + blank = false + block.push(raw) + continue + } + + flush() + + const line = raw.trimEnd() + + if (line.trim() === '') { + if (!blank && out.length > 0) out.push('') + blank = true + continue + } + + blank = false + out.push(line) + } + + flush() + + while (out.length > 0 && out[out.length - 1] === '') out.pop() + + return out +} diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts index 0455b16710..e8eb0f5824 100644 --- a/plugins/ruflo-console/hooks/runner.ts +++ b/plugins/ruflo-console/hooks/runner.ts @@ -12,6 +12,7 @@ import { labLines } from './mh-lab' import { outputLines } from './ops' import { filterPalette, paletteEntries, textOfQuery, type PaletteEntry } from './palette' import { CLI_PREFIXES, type State } from './state' +import { prettyLines } from './result-lines' export const PENDING_TTL_MS = 30_000 @@ -75,7 +76,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) { - panel.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) ?? (spec.lines ?? ((out, err) => labLines(spec.lab ?? '', out, err)))(result.stdout, result.stderr), atMs: Date.now() } + panel.result = { id: spec.lab, label: spec.label, ok, exitCode: result.exitCode, ...(spec.note !== undefined && { note: spec.note }), lines: prettyLines(spec.read?.(result.stdout, result.stderr, ok) ?? (spec.lines ?? ((out, err) => labLines(spec.lab ?? '', out, err)))(result.stdout, result.stderr)), atMs: Date.now() } state.select.item = 0 } // Keyed on the exit, not on `ok`: relay text in a read may carry an "error" key of its own. diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts index a2b7983d6b..a3bc7ffd2d 100644 --- a/plugins/ruflo-console/hooks/version.ts +++ b/plugins/ruflo-console/hooks/version.ts @@ -2,4 +2,4 @@ * The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest * (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift. */ -export const CONSOLE_VERSION = '0.33.20' +export const CONSOLE_VERSION = '0.33.21' diff --git a/plugins/ruflo-console/hooks/views/automate.ts b/plugins/ruflo-console/hooks/views/automate.ts index e82c55e634..2253cb7640 100644 --- a/plugins/ruflo-console/hooks/views/automate.ts +++ b/plugins/ruflo-console/hooks/views/automate.ts @@ -8,6 +8,7 @@ import { neuralEntries } from '../neural' import { slot } from './attention' import { loopRows } from './loops' import { ago, button, clip, col, type Ctx, row, rule, tagChip, text, THEME } from './common' +import { frameResult } from './status-card' import { selection } from './select' /** Result lines in view at once; j/k scroll the rest. */ @@ -60,7 +61,7 @@ export function resultRows(ctx: Ctx, prefixes: readonly string[]): RenderElement 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 + return [frameResult(ctx, rows, running !== null ? 'run' : 'idle')] } rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -73,7 +74,7 @@ export function resultRows(ctx: Ctx, prefixes: readonly string[]): RenderElement 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 slot(ctx, rows) + return slot(ctx, [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')]) } /** One worker's light: running now (◌), failing (◐), has run (●), or never run here (○). */ diff --git a/plugins/ruflo-console/hooks/views/devtools.ts b/plugins/ruflo-console/hooks/views/devtools.ts index 5f31d93dec..f796dcb70f 100644 --- a/plugins/ruflo-console/hooks/views/devtools.ts +++ b/plugins/ruflo-console/hooks/views/devtools.ts @@ -4,6 +4,7 @@ import type { DevField } from '../data/devtools' import { DEV, DEV_GROUPS, devSpec, type DevCost, type DevEntry, type DevGroup } from '../devtools' import { slot } from './attention' import { ago, button, clip, col, type Ctx, row, section, tagChip, text, THEME } from './common' +import { frameResult } from './status-card' import { SANDBOX_GROUPS } from '../sandbox' import { spinAt } from '../spinner' import { sendResultRow } from './secure' @@ -108,7 +109,7 @@ function resultRows(ctx: Ctx): RenderElement[] { if (result === null) { if (running === null) rows.push(text(ctx, ' ▸ press a row: a $0 read shows here at once; the rest ask first (y), their cost on the confirm row', { dimColor: true })) - return rows + return [frameResult(ctx, rows, running !== null ? 'run' : 'idle')] } rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -130,7 +131,7 @@ function resultRows(ctx: Ctx): RenderElement[] { rows.push(sendResultRow(ctx, 'dt-send')) - return slot(ctx, rows) + return slot(ctx, [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')]) } /** diff --git a/plugins/ruflo-console/hooks/views/evolve.ts b/plugins/ruflo-console/hooks/views/evolve.ts index 8bd4e8890d..405ff7b569 100644 --- a/plugins/ruflo-console/hooks/views/evolve.ts +++ b/plugins/ruflo-console/hooks/views/evolve.ts @@ -5,6 +5,7 @@ import { candidateReceipt, EVOLVE, evolveSpec, PROMOTE_COMMAND, REPOS, type Evol import { lineageOf, loopStagesOf, type LineageRow } from '../gfx/evolve' import { slot } from './attention' import { ago, button, clip, col, kv, picture, row, rule, text, THEME, type Ctx } from './common' +import { frameResult } from './status-card' /** Result lines in view at once; j/k scroll the rest. */ const RESULT_ROWS = 12 @@ -183,7 +184,7 @@ function resultRows(ctx: Ctx): RenderElement[] { if (result === null) { if (running === null) out.push(text(ctx, ' ▸ run a check: a $0 read answers here at once; ▸ ask shows its command and runs after you confirm (y)', { dimColor: true })) - return out + return [frameResult(ctx, out, running !== null ? 'run' : 'idle')] } out.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -194,7 +195,7 @@ function resultRows(ctx: Ctx): RenderElement[] { for (const line of result.lines.slice(top, top + RESULT_ROWS)) out.push(text(ctx, ` ${line}`)) if (result.lines.length > RESULT_ROWS) out.push(row(ctx, [text(ctx, ` lines ${top + 1}-${Math.min(result.lines.length, top + RESULT_ROWS)} of ${result.lines.length} `, { dimColor: true }), button(ctx, 'evolve-up', 'up', () => ctx.act.select(-1), { hotkey: 'k' }), button(ctx, 'evolve-down', 'down', () => ctx.act.select(1), { hotkey: 'j' })])) - return slot(ctx, out) + return slot(ctx, [frameResult(ctx, out, result.ok ? 'ok' : 'bad')]) } /** diff --git a/plugins/ruflo-console/hooks/views/memory-lab.ts b/plugins/ruflo-console/hooks/views/memory-lab.ts index 791396cb1b..20e81b4155 100644 --- a/plugins/ruflo-console/hooks/views/memory-lab.ts +++ b/plugins/ruflo-console/hooks/views/memory-lab.ts @@ -2,6 +2,7 @@ import type { RenderElement } from 'claude-code' import { MEM_GROUPS, MEM_LAB, memSpecOf, textOfFields, type MemCost, type MemEntry, type MemField } from '../memory-lab' import { ago, button, clip, confirmHere, type Ctx, row, rule, section, tagChip, text, THEME } from './common' +import { frameResult } from './status-card' /** Result lines in view at once; j/k scroll the rest. */ export const MEM_ROWS = 16 @@ -112,7 +113,7 @@ function resultRows(ctx: Ctx): RenderElement[] { if (result === null) { if (running === null) rows.push(text(ctx, ' ▸ open an entry above, search, or run a lab row: reads show here at once, the rest after you confirm (y)', { dimColor: true })) - return rows + return [frameResult(ctx, rows, running !== null ? 'run' : 'idle')] } rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -132,7 +133,7 @@ function resultRows(ctx: Ctx): RenderElement[] { ) } - return rows + return [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')] } /** diff --git a/plugins/ruflo-console/hooks/views/mh-lab.ts b/plugins/ruflo-console/hooks/views/mh-lab.ts index 0be18e348f..8daa45fbdb 100644 --- a/plugins/ruflo-console/hooks/views/mh-lab.ts +++ b/plugins/ruflo-console/hooks/views/mh-lab.ts @@ -4,6 +4,7 @@ import { LAB, LAB_GROUPS, labSpec, PROMOTE_COMMAND, type LabCost, type LabEntry import { slot } from './attention' import { sendResultRow } from './secure' import { ago, button, clip, type Ctx, row, rule, section, tagChip, text, THEME } from './common' +import { frameResult } from './status-card' /** Result lines in view at once; j/k scroll the rest. */ export const LAB_ROWS = 14 @@ -53,7 +54,7 @@ function resultRows(ctx: Ctx): RenderElement[] { if (result === null) { if (running === null) rows.push(text(ctx, ' ▸ run an entry: a $0 read shows here at once; the rest show here after you confirm (y)', { dimColor: true })) - return rows + return [frameResult(ctx, rows, running !== null ? 'run' : 'idle')] } rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -75,7 +76,7 @@ function resultRows(ctx: Ctx): RenderElement[] { rows.push(sendResultRow(ctx, 'lab-send')) - return slot(ctx, rows) + return slot(ctx, [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')]) } /** diff --git a/plugins/ruflo-console/hooks/views/plugin-catalog.ts b/plugins/ruflo-console/hooks/views/plugin-catalog.ts index 71199b3abb..0ae57c0565 100644 --- a/plugins/ruflo-console/hooks/views/plugin-catalog.ts +++ b/plugins/ruflo-console/hooks/views/plugin-catalog.ts @@ -4,6 +4,7 @@ import { catalogOf, installedOf, listOf, MODES, PAGE, type Verb } from '../plugi import type { CatalogPlugin } from '../data/plugin-catalog' import { RUFLO_MARKET } from '../data/snapshot' import { ago, button, clip, col, kv, row, rule, section, text, THEME, type Ctx } from './common' +import { frameResult } from './status-card' import { homeLink } from './links' /** The ▸ verb a row ends with: install when absent, else enable or disable. */ @@ -92,7 +93,7 @@ function lastRows(ctx: Ctx): RenderElement[] { if (last === null) return [] - return [rule(ctx, 'Result', last.ok ? '✓' : '✗'), text(ctx, ` ${last.label}`, { bold: true, color: last.ok ? THEME.ok : THEME.bad }), ...last.lines.slice(0, 40).map(line => text(ctx, ` ${line}`))] + return [frameResult(ctx, [rule(ctx, 'Result', last.ok ? '✓' : '✗'), text(ctx, ` ${last.label}`, { bold: true, color: last.ok ? THEME.ok : THEME.bad }), ...last.lines.slice(0, 40).map(line => text(ctx, ` ${line}`))], last.ok ? 'ok' : 'bad')] } /** diff --git a/plugins/ruflo-console/hooks/views/secure.ts b/plugins/ruflo-console/hooks/views/secure.ts index d1456f9ef0..fb1c5fb1af 100644 --- a/plugins/ruflo-console/hooks/views/secure.ts +++ b/plugins/ruflo-console/hooks/views/secure.ts @@ -5,6 +5,7 @@ import { slot } from './attention' import { spinAt } from '../spinner' import { sentryRows } from './sentries' import { ago, button, clip, col, type Ctx, row, rule, section, tagChip, text, THEME } from './common' +import { frameResult } from './status-card' /** Result lines in view at once; j/k scroll the rest. */ export const RESULT_ROWS = 14 @@ -87,7 +88,7 @@ export function resultRows(ctx: Ctx, isMine: (id: string) => boolean): RenderEle if (result === null) { if (running === null) rows.push(text(ctx, ' ▸ run an entry: a $0 read shows here at once; the rest show here after you confirm (y)', { dimColor: true })) - return rows + return [frameResult(ctx, rows, running !== null ? 'run' : 'idle')] } rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -114,7 +115,7 @@ export function resultRows(ctx: Ctx, isMine: (id: string) => boolean): RenderEle rows.push(sendResultRow(ctx, 'result-send')) - return slot(ctx, rows) + return slot(ctx, [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')]) } const SEVERITY_COLOR: Record string> = { critical: () => THEME.bad, high: () => THEME.bad, medium: () => THEME.warn, low: () => THEME.info } diff --git a/plugins/ruflo-console/hooks/views/sentries.ts b/plugins/ruflo-console/hooks/views/sentries.ts index 49fb1fdb91..626c599e5e 100644 --- a/plugins/ruflo-console/hooks/views/sentries.ts +++ b/plugins/ruflo-console/hooks/views/sentries.ts @@ -1,8 +1,13 @@ import type { RenderElement } from 'claude-code' import { PRESETS } from '../loops' +import { mcOf } from '../mission-control' +import { outcomeCard } from './status-card' import { button, clip, row, section, text, THEME, type Ctx } from './common' +/** The outcomes a loop launch reports (loops.ts `say`): the Security page shows the last one right under the sentries, so a click is never silent. */ +const LAUNCH_LABELS: ReadonlySet = new Set(['loop command sent', 'waiting in your prompt box', 'could not fill the prompt box', 'Claude did not take it', 'loop not started', 'AIDefence blocked the task']) + /** When a sentry runs, in words: on change (an event watch), or every interval. */ const whenOf = (interval: string): string => (interval === 'self-paced' ? 'on change' : `every ${interval}`) @@ -47,6 +52,11 @@ export function sentryRows(ctx: Ctx): RenderElement[] { 'sentry-manage-row', ), ) + const last = mcOf(ctx.state).last + + if (last !== null && LAUNCH_LABELS.has(last.label)) { + rows.push(outcomeCard(ctx, 'sentry-outcome', last)) + } rows.push(text(ctx, ' watch: reads and reports, edits nothing · fix: edits only in a new branch and never pushes · each tick is a billed turn; it asks first', { dimColor: true })) return section(ctx, 'sec-sentries', 'Sentries', `${sentries.filter(entry => entry.sentry === 'watch').length} watch · ${sentries.filter(entry => entry.sentry === 'fix').length} find and fix · real time, or on a schedule`, rows, true) diff --git a/plugins/ruflo-console/hooks/views/status-card.ts b/plugins/ruflo-console/hooks/views/status-card.ts new file mode 100644 index 0000000000..e63bce88ad --- /dev/null +++ b/plugins/ruflo-console/hooks/views/status-card.ts @@ -0,0 +1,49 @@ +/** + * A result as a card: a round border in the result's colour, a header that says what it is and how it went (✓ or ✗, the title, how long + * ago), then the body. A status that is one grey line is easy to miss, and a silent click looks like a click that did nothing. + */ +import type { RenderChildren, RenderElement } from 'claude-code' + +import { ago, row, THEME, type Ctx } from './common' + +export type StatusTone = 'ok' | 'bad' | 'warn' | 'run' + +const COLOR: Record string> = { ok: () => THEME.ok, bad: () => THEME.bad, warn: () => THEME.warn, run: () => THEME.info } +const MARK: Record = { ok: '✓', bad: '✗', warn: '⚠', run: '…' } + +/** The card: `title` bold beside the mark, `right` dim at the end of the header (a time, an exit code), then `body`. */ +export function statusCard(ctx: Ctx, key: string, tone: StatusTone, title: string, right: string, body: readonly RenderChildren[]): RenderElement { + return ctx.kit.Box({ + key, + flexDirection: 'column', + borderStyle: 'round', + borderColor: COLOR[tone](), + paddingX: 1, + children: [row(ctx, [ctx.kit.Text({ bold: true, color: COLOR[tone](), wrap: 'truncate-end', children: `${MARK[tone]} ${title}` }), ...(right === '' ? [] : [ctx.kit.Text({ dimColor: true, children: ` ${right}` })])]), ...body], + }) +} + +/** A launch or action outcome as a card: the detail wrapped (never clipped), then what to do next. `atMs` shows as "3s ago". */ +export function outcomeCard(ctx: Ctx, key: string, outcome: { ok: boolean; label: string; detail: string; atMs?: number; next?: string }): RenderElement { + return statusCard(ctx, key, outcome.ok ? 'ok' : 'bad', outcome.label, outcome.atMs === undefined ? '' : ago(outcome.atMs, ctx.nowMs), [ + ...(outcome.detail === '' ? [] : [ctx.kit.Text({ wrap: 'wrap', children: outcome.detail })]), + ...(outcome.next === undefined ? [] : [ctx.kit.Text({ wrap: 'wrap', dimColor: true, children: `→ ${outcome.next}` })]), + ]) +} + +export type ResultTone = 'ok' | 'bad' | 'run' | 'idle' + +/** + * Every view's Result panel inside one round border, coloured by how the run went: green for ok, red for failed, amber while it runs, and + * dim when nothing has run yet. The rows (the `▓▒░ RESULT ░▒▓ … ✓ exit 0 · 3s ago` header, the label, the lines) are drawn exactly as before. + */ +export function frameResult(ctx: Ctx, rows: readonly RenderElement[], tone: ResultTone): RenderElement { + return ctx.kit.Box({ + key: 'result-frame', + flexDirection: 'column', + borderStyle: 'round', + borderColor: tone === 'ok' ? THEME.ok : tone === 'bad' ? THEME.bad : tone === 'run' ? THEME.warn : 'inactive', + paddingX: 1, + children: [...rows], + }) +} diff --git a/plugins/ruflo-console/hooks/views/vector.ts b/plugins/ruflo-console/hooks/views/vector.ts index d68b24fd9f..d34f79472c 100644 --- a/plugins/ruflo-console/hooks/views/vector.ts +++ b/plugins/ruflo-console/hooks/views/vector.ts @@ -4,6 +4,7 @@ import { targetOf, type VectorField } from '../data/vector' import { VEC, VEC_SECTIONS, vecSpec, type VecCost, type VecEntry, type VecSection } from '../vector' import { slot } from './attention' import { ago, button, clip, type Ctx, row, rule, tagChip, text, THEME } from './common' +import { frameResult } from './status-card' /** Result lines in view at once; j/k scroll the rest. */ export const VEC_ROWS = 12 @@ -106,7 +107,7 @@ function resultRows(ctx: Ctx): RenderElement[] { if (result === null) { if (running === null) rows.push(text(ctx, ' ▸ run shows a local read here at once; ▸ asks shows the exact command first (y runs it, n cancels)', { dimColor: true })) - return rows + return [frameResult(ctx, rows, running !== null ? 'run' : 'idle')] } rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -126,7 +127,7 @@ function resultRows(ctx: Ctx): RenderElement[] { ) } - return slot(ctx, rows) + return slot(ctx, [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')]) } /** diff --git a/plugins/ruflo-console/hooks/views/xruv.ts b/plugins/ruflo-console/hooks/views/xruv.ts index 7d3ae407c2..84f2069b9b 100644 --- a/plugins/ruflo-console/hooks/views/xruv.ts +++ b/plugins/ruflo-console/hooks/views/xruv.ts @@ -4,6 +4,7 @@ import type { Channels, Registry, Roster } from '../data/cli' import type { SwarmMessages, WorkClaims } from '../data/xruv' import { BBS_SERVE_COMMAND, INVITE_COMMAND, UNREGISTER_WHY, XRUV, type XEntry, type XGroup } from '../xruv' import { ago, button, clip, col, type Ctx, kv, live, row, rule, sourceLine, tagChip, text, THEME } from './common' +import { frameResult } from './status-card' /** Result lines in view at once; j/k scroll the rest. */ export const XRUV_ROWS = 8 @@ -243,7 +244,7 @@ function resultRows(ctx: Ctx): RenderElement[] { if (result === null) { if (running === null) rows.push(text(ctx, ' ▸ fetch shows its answer here at once; a write shows here after you confirm (y)', { dimColor: true })) - return rows + return [frameResult(ctx, rows, running !== null ? 'run' : 'idle')] } rows.push(text(ctx, ` ${result.label}`, { bold: true, color: result.ok ? THEME.ok : THEME.bad })) @@ -263,7 +264,7 @@ function resultRows(ctx: Ctx): RenderElement[] { ) } - return rows + return [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')] } /** diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh index 4940f0d5ba..15f6b9799a 100755 --- a/plugins/ruflo-console/scripts/smoke.sh +++ b/plugins/ruflo-console/scripts/smoke.sh @@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json declares ruflo-console 0.33.20" +step "1. plugin.json declares ruflo-console 0.33.21" grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \ - && grep -q '"version": "0.33.20"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" + && grep -q '"version": "0.33.21"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" step "2. hooks.json names exactly one module and no classic hook commands" grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \ diff --git a/plugins/ruflo-console/tests/loops.spec.ts b/plugins/ruflo-console/tests/loops.spec.ts index 7cd75bed9b..e759fcbff5 100644 --- a/plugins/ruflo-console/tests/loops.spec.ts +++ b/plugins/ruflo-console/tests/loops.spec.ts @@ -8,20 +8,27 @@ import type { ActionSpec } from '../hooks/actions' import type { Host } from '../hooks/host' import { INTERVALS, loopActions, loopInput, loopsOf, PRESETS, stopClause, TIERS } from '../hooks/loops' import type { Runner } from '../hooks/runner' +import { mcOf } from '../hooks/mission-control' +import { sentryRows } from '../hooks/views/sentries' +import type { Ctx } from '../hooks/views/common' import { newState } from '../hooks/state' const out = (data: unknown) => `[INFO] Executing tool\nResult:\n${JSON.stringify(data, null, 2)}` const tick = () => new Promise(resolve => setTimeout(resolve, 5)) -function setup(answer: (tool: string) => unknown = () => ({ safe: true, threats: [], hasPII: false })) { +function setup(answer: (tool: string) => unknown = () => ({ safe: true, threats: [], hasPII: false }), slash?: (command: string, args: string) => Promise) { const state = newState({}) - const calls = { prompts: [] as string[], fills: [] as string[], asked: [] as ActionSpec[] } + const calls = { prompts: [] as string[], fills: [] as string[], slashes: [] as { command: string; args: string }[], asked: [] as ActionSpec[] } const host = { run: async (argv: readonly string[]) => ({ exitCode: 0, stdout: out(answer(argv[argv.indexOf('-t') + 1] as string)), stderr: '' }), invalidate: () => undefined, after: () => ({ cancel: () => undefined }), submitPrompt: async (text: string) => void calls.prompts.push(text), fillPrompt: async (text: string) => (calls.fills.push(text), true), + runSlash: async (command: string, args: string) => { + calls.slashes.push({ command, args }) + await slash?.(command, args) + }, } as unknown as Host const runner = { ask: (spec: ActionSpec | null) => void (spec !== null && calls.asked.push(spec)) } as unknown as Runner @@ -92,7 +99,7 @@ describe('loop manager', () => { expect(loopsOf(state).interval).toBe('5m') }) - it('launch asks first with the exact /loop and a cost note; yes submits one visible prompt, mid-turn it only fills the box', async () => { + it('launch asks first with the exact /loop and a cost note; yes runs it as the /loop command (not a prompt), mid-turn it only fills the box and says so', async () => { const { state, calls, actions } = setup() actions.pick('ci-watch') @@ -104,15 +111,44 @@ describe('loop manager', () => { expect(calls.asked[0]?.note).toContain('billed') expect(calls.asked[0]?.note).toContain('No stop condition') await calls.asked[0]?.run?.() - expect(calls.prompts).toHaveLength(1) - expect(calls.prompts[0]).toBe(calls.asked[0]?.shows) + // A command, as if typed: a prompt that only looks like "/loop …" is a message to the model and creates no loop (the bug this pins). + expect(calls.prompts).toEqual([]) + expect(calls.slashes).toHaveLength(1) + expect(`/${calls.slashes[0]?.command} ${calls.slashes[0]?.args}`).toBe(calls.asked[0]?.shows) + expect(mcOf(state).last).toMatchObject({ label: 'loop command sent', ok: true }) state.turnActive = true actions.launch() await tick() await calls.asked[1]?.run?.() - expect(calls.fills).toHaveLength(1) - expect(calls.prompts).toHaveLength(1) + expect(calls.fills).toEqual([calls.asked[1]?.shows]) + expect(calls.slashes).toHaveLength(1) + expect(calls.prompts).toEqual([]) + expect(mcOf(state).last).toMatchObject({ label: 'waiting in your prompt box', ok: true }) + expect(mcOf(state).last?.next).toContain('press Enter') + }) + + it('the sentry presets run as /loop with their own task, and a command the engine refuses is reported, not swallowed', async () => { + const { calls, actions } = setup() + + actions.pick('sentry-live') + actions.launch() + await tick() + expect(calls.asked[0]?.shows).toMatch(/^\/loop Read-only/) + await calls.asked[0]?.run?.() + expect(calls.slashes[0]).toMatchObject({ command: 'loop' }) + expect(calls.slashes[0]?.args).toMatch(/^Read-only/) + + const refusing = setup(undefined, async () => { + throw new Error('unknown command: loop') + }) + + refusing.actions.pick('ci-watch') + refusing.actions.launch() + await tick() + await refusing.calls.asked[0]?.run?.() + expect(mcOf(refusing.state).last).toMatchObject({ label: 'Claude did not take it', ok: false }) + expect(mcOf(refusing.state).last?.detail).toContain('unknown command') }) it('a hand-typed task is screened: an injection is blocked and never asked; a preset is not screened', async () => { @@ -142,3 +178,37 @@ describe('loop manager', () => { expect(calls.asked[0]?.shows).toContain('ask me which to stop before stopping any') }) }) + +describe('the Security page says what a sentry start did', () => { + type El = { kind: string; props: Record } + const make = (kind: string) => (props: Record): El => ({ kind, props }) + const kit = { Box: make('Box'), Text: make('Text'), Button: make('Button'), Input: make('Input') } + const flat = (node: unknown): El[] => { + if (Array.isArray(node)) return node.flatMap(flat) + if (typeof node !== 'object' || node === null) return [] + const el = node as El + const children = el.props.children + + return [el, ...(Array.isArray(children) ? children.flatMap(flat) : flat(children))] + } + const lines = (state: ReturnType): string[] => + flat(sentryRows({ kit, state, act: { loops: {} }, columns: 100, nowMs: 1_000, pictures: new Map() } as unknown as Ctx)).filter(el => el.kind === 'Text').map(el => String(el.props.children)) + + it('shows nothing before a start, then the outcome (ok or not) under the rows', () => { + const state = newState({}) + + expect(lines(state).some(line => /loop command sent|prompt box|did not take/.test(line))).toBe(false) + mcOf(state).last = { label: 'loop command sent', ok: true, detail: 'Sent as /loop.' } + expect(lines(state)).toEqual(expect.arrayContaining(['✓ loop command sent', 'Sent as /loop.'])) + mcOf(state).last = { label: 'Claude did not take it', ok: false, detail: 'unknown command: loop', next: 'try again', atMs: 1_000 } + expect(lines(state)).toEqual(expect.arrayContaining(['✗ Claude did not take it', 'unknown command: loop', '→ try again'])) + expect(lines(state).some(line => /0s ago/.test(line))).toBe(true) + }) + + it('does not show an unrelated mission result there', () => { + const state = newState({}) + + mcOf(state).last = { label: 'mission created', ok: true, detail: 'x' } + expect(lines(state).some(line => line.includes('mission created'))).toBe(false) + }) +}) diff --git a/plugins/ruflo-console/tests/result-lines.spec.ts b/plugins/ruflo-console/tests/result-lines.spec.ts new file mode 100644 index 0000000000..78cbfb43b6 --- /dev/null +++ b/plugins/ruflo-console/tests/result-lines.spec.ts @@ -0,0 +1,63 @@ +/** The result lines are tidied before a view draws them: ASCII tables are drawn again with aligned columns, nothing else is rewritten. */ +import { describe, expect, it } from 'vitest' + +import { prettyLines } from '../hooks/result-lines' + +const PASTED = [ + 'Pattern Optimization (Real)', + 'Quantized 349 pattern embeddings to Int8', + '+-----------------+-----------+--------------+', + '| Metric | Before | After |', + '+-----------------+-----------+--------------+', + '| Pattern Count | 349 | 349 |', + '| Quantized | - | 349 |', + '| Storage Size | 3751.9 KB | 3751.9 KB |', + '| Reduction Ratio | - | 1.00x |', + '| Precision | Float32 | Int8 (±0.5%) |', + '+-----------------+-----------+--------------+', +] + +describe('prettyLines', () => { + it('draws the pasted CLI table with aligned columns and a header rule', () => { + const out = prettyLines(PASTED) + + expect(out.slice(0, 2)).toEqual(['Pattern Optimization (Real)', 'Quantized 349 pattern embeddings to Int8']) + expect(out[2]).toBe('┌─────────────────┬───────────┬──────────────┐') + expect(out[3]).toBe('│ Metric │ Before │ After │') + expect(out[4]).toBe('├─────────────────┼───────────┼──────────────┤') + expect(out[5]).toBe('│ Pattern Count │ 349 │ 349 │') + expect(out.at(-1)).toBe('└─────────────────┴───────────┴──────────────┘') + expect(new Set(out.slice(2).map(line => line.length)).size).toBe(1) + }) + + it('leaves ordinary lines alone, trims trailing space and collapses runs of blank lines', () => { + expect(prettyLines(['a ', '', '', '', 'b', ''])).toEqual(['a', '', 'b']) + expect(prettyLines([])).toEqual([]) + }) + + it('does not touch a block it cannot read as a table (one row, ragged, or no columns)', () => { + const ragged = ['| a | b |', '| c |'] + const single = ['| only | one |'] + + expect(prettyLines(ragged)).toEqual(ragged) + expect(prettyLines(single)).toEqual(single) + }) + + it('cuts a very long cell, keeps two tables apart, and bounds a runaway block', () => { + const long = prettyLines(['| h | v |', '| a | ' + 'x'.repeat(80) + ' |']) + + expect(long.every(line => line.length <= 8 + 48)).toBe(true) + expect(long.some(line => line.includes('…'))).toBe(true) + + const two = prettyLines(['| a | b |', '| 1 | 2 |', 'text', '| c | d |', '| 3 | 4 |']) + + expect(two.filter(line => line.startsWith('┌'))).toHaveLength(2) + expect(prettyLines(Array.from({ length: 300 }, () => '| a | b |'))).toHaveLength(300) + }) + + it('never invents text: every cell of the output was in the input', () => { + const cells = new Set(PASTED.filter(line => line.startsWith('|')).flatMap(line => line.slice(1, -1).split('|').map(cell => cell.trim()))) + + for (const line of prettyLines(PASTED).filter(row => row.startsWith('│'))) for (const cell of line.slice(1, -1).split('│').map(part => part.trim())) expect(cells.has(cell), cell).toBe(true) + }) +}) diff --git a/plugins/ruflo-console/tests/status-card.spec.ts b/plugins/ruflo-console/tests/status-card.spec.ts new file mode 100644 index 0000000000..16c5e798e4 --- /dev/null +++ b/plugins/ruflo-console/tests/status-card.spec.ts @@ -0,0 +1,69 @@ +/** The result frame and the outcome card: a border in the outcome's colour, a header that says how it went, the body as it was. */ +import { describe, expect, it } from 'vitest' + +import { newState } from '../hooks/state' +import { THEME, type Ctx } from '../hooks/views/common' +import { secureResult } from '../hooks/views/secure' +import { frameResult, outcomeCard, statusCard } from '../hooks/views/status-card' + +type El = { kind: string; props: Record } +const make = (kind: string) => (props: Record): El => ({ kind, props }) +const kit = { Box: make('Box'), Text: make('Text'), Button: make('Button'), Input: make('Input') } +const act = new Proxy({}, { get: () => () => undefined }) as unknown as Ctx['act'] +const flat = (node: unknown): El[] => { + if (Array.isArray(node)) return node.flatMap(flat) + if (typeof node !== 'object' || node === null) return [] + const el = node as El + const children = el.props.children + + return [el, ...(Array.isArray(children) ? children.flatMap(flat) : flat(children))] +} +const ctxOf = (state = newState({ boot: false })): Ctx => ({ kit, state, act, columns: 100, nowMs: 10_000, pictures: new Map() }) as unknown as Ctx +const textsOf = (node: unknown): string[] => flat(node).filter(el => el.kind === 'Text').map(el => String(el.props.children)) + +describe('frameResult', () => { + it('is a round border coloured by the outcome: ok, failed, running, nothing run', () => { + const ctx = ctxOf() + const color = (tone: 'ok' | 'bad' | 'run' | 'idle') => (frameResult(ctx, [], tone) as unknown as El).props.borderColor + + expect(color('ok')).toBe(THEME.ok) + expect(color('bad')).toBe(THEME.bad) + expect(color('run')).toBe(THEME.warn) + expect(color('idle')).toBe('inactive') + expect((frameResult(ctx, [], 'ok') as unknown as El).props).toMatchObject({ key: 'result-frame', borderStyle: 'round' }) + }) +}) + +describe('the Security result panel', () => { + it('is drawn inside the frame, green when the run passed and red when it failed, with its lines unchanged', () => { + const state = newState({ boot: false }) + + state.lab.result = { id: 'sec-scan-quick', label: 'security scan, quick', ok: true, exitCode: 0, lines: ['CLEAN · 0 findings', '┌─┐'], atMs: 9_000 } + const ok = secureResult(ctxOf(state))[0] as unknown as El + + expect(ok.props).toMatchObject({ key: 'result-frame', borderColor: THEME.ok }) + expect(textsOf(ok).join('\n')).toContain('CLEAN · 0 findings') + + state.lab.result = { ...state.lab.result, ok: false, exitCode: 1 } + expect((secureResult(ctxOf(state))[0] as unknown as El).props.borderColor).toBe(THEME.bad) + }) + + it('shows an idle frame with a hint before anything has run', () => { + const card = secureResult(ctxOf())[0] as unknown as El + + expect(card.props).toMatchObject({ key: 'result-frame', borderColor: 'inactive' }) + expect(textsOf(card).join(' ')).toContain('nothing run yet') + }) +}) + +describe('statusCard and outcomeCard', () => { + it('put the mark, title and age in the header, then the body wrapped, then the next step', () => { + const ctx = ctxOf() + const card = outcomeCard(ctx, 'k', { ok: false, label: 'Claude did not take it', detail: 'unknown command', atMs: 4_000, next: 'try again' }) + + expect(card).toMatchObject({ props: { key: 'k', borderStyle: 'round', borderColor: THEME.bad } }) + expect(textsOf(card)).toEqual(['✗ Claude did not take it', ' 6s ago', 'unknown command', '→ try again']) + expect(flat(card).filter(el => el.kind === 'Text' && el.props.wrap === 'wrap')).toHaveLength(2) + expect(textsOf(statusCard(ctx, 'k', 'ok', 'done', '', []))).toEqual(['✓ done']) + }) +}) From 6fd0a78c231f38df92e58439e96d5e0c5c043ab6 Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 15:14:26 -0400 Subject: [PATCH 2/6] fix(ruflo-console): results read markdown as text: pipe tables drawn aligned, headings, bullets, bold, code and links tidied MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The result lines carried raw markdown (| --- | separator rows, **bold**, `code`, ## headings, - bullets, ``` fences) that the console printed literally. prettyLines now draws markdown pipe tables with the same aligned box as the CLI's ASCII tables (markers inside cells removed), reads headings as "▸ Title", bullets as "•", quotes as "│", drops bold/code markers and turns [text](url) into "text (url)", and shows a fenced block as it is without the fence lines. Single asterisks, snake_case and unpaired markers are left alone. Co-Authored-By: RuFlo --- plugins/ruflo-console/hooks/result-lines.ts | 52 +++++++++++++++++-- .../ruflo-console/tests/result-lines.spec.ts | 39 +++++++++++++- 2 files changed, 85 insertions(+), 6 deletions(-) diff --git a/plugins/ruflo-console/hooks/result-lines.ts b/plugins/ruflo-console/hooks/result-lines.ts index 314f75e7c8..d3e665973b 100644 --- a/plugins/ruflo-console/hooks/result-lines.ts +++ b/plugins/ruflo-console/hooks/result-lines.ts @@ -5,19 +5,32 @@ * removed and runs of blank lines collapsed to one. Pure, bounded, and it never invents text: a block it cannot read as a table stays as it was. */ -const RULE = /^\s*\+[-=+]{2,}\+\s*$/ +/** A table rule: the CLI's `+----+----+`, or a markdown separator row `| --- | :---: |`. */ +const RULE = /^\s*(?:\+[-=+]{2,}\+|\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?)\s*$/ const ROW = /^\s*\|.*\|\s*$/ /** The widest a column is drawn; a longer cell is cut with an ellipsis. */ const MAX_CELL = 48 /** The most table lines read as one block (a runaway block stays as plain lines). */ const MAX_BLOCK = 200 -const cellsOf = (line: string): string[] => line.trim().slice(1, -1).split('|').map(cell => cell.trim()) +/** + * Markdown inside a line, read as text: `**bold**`, `__bold__` and `code` lose their markers, `[text](url)` reads `text (url)`. Single `*` and `_` are + * left alone (a product like 5 * 3, snake_case), and a marker with no partner is left as it is. + */ +export function plainMarkdown(line: string): string { + return line + .replace(/\*\*([^*\n]+?)\*\*/g, '$1') + .replace(/__([^_\n]+?)__/g, '$1') + .replace(/`([^`\n]+?)`/g, '$1') + .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '$1 ($2)') +} + +const cellsOf = (line: string): string[] => line.trim().slice(1, -1).split('|').map(cell => plainMarkdown(cell.trim())) const cut = (cell: string): string => (cell.length > MAX_CELL ? `${cell.slice(0, MAX_CELL - 1)}…` : cell) /** One table block (rules and rows, in order) as box-drawn lines, or null when it is not a rectangular table of at least two rows. */ function drawTable(block: readonly string[]): string[] | null { - const rows = block.filter(line => ROW.test(line)).map(cellsOf) + const rows = block.filter(line => ROW.test(line) && !RULE.test(line)).map(cellsOf) if (rows.length < 2) return null @@ -29,16 +42,33 @@ function drawTable(block: readonly string[]): string[] | null { const rule = (left: string, mid: string, right: string): string => `${left}${widths.map(width => '─'.repeat(width + 2)).join(mid)}${right}` const draw = (row: readonly string[]): string => `│${row.map((cell, column) => ` ${cut(cell).padEnd(widths[column] ?? 0)} `).join('│')}│` // The first row is the header when a rule sits right under it (the CLI's table shape). - const hasHeader = block.findIndex(line => ROW.test(line)) + 1 < block.length && RULE.test(block[block.findIndex(line => ROW.test(line)) + 1] ?? '') + const first = block.findIndex(line => ROW.test(line) && !RULE.test(line)) + const hasHeader = first >= 0 && RULE.test(block[first + 1] ?? '') const [head, ...rest] = rows return [rule('┌', '┬', '┐'), ...(hasHeader && head !== undefined ? [draw(head), rule('├', '┼', '┤')] : head !== undefined ? [draw(head)] : []), ...rest.map(draw), rule('└', '┴', '┘')] } +/** One non-table line: headings read `▸ Title`, bullets `•`, quotes `│`, and the inline markers are dropped. */ +function textLine(raw: string): string { + const heading = /^\s{0,3}#{1,6}\s+(.*?)\s*#*\s*$/.exec(raw) + + if (heading !== null) return `▸ ${plainMarkdown(heading[1] ?? '')}` + + const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(raw) + + if (bullet !== null) return `${bullet[1] ?? ''}• ${plainMarkdown(bullet[2] ?? '')}` + + const quote = /^\s*>\s?(.*)$/.exec(raw) + + return quote !== null ? `│ ${plainMarkdown(quote[1] ?? '')}` : plainMarkdown(raw) +} + export function prettyLines(lines: readonly string[]): string[] { const out: string[] = [] let block: string[] = [] let blank = false + let fenced = false const flush = (): void => { if (block.length === 0) return @@ -50,6 +80,18 @@ export function prettyLines(lines: readonly string[]): string[] { } for (const raw of lines) { + // A fenced code block is shown as it is, minus the fence lines themselves. + if (/^\s*(```|~~~)/.test(raw)) { + flush() + fenced = !fenced + continue + } + + if (fenced) { + out.push(raw.trimEnd()) + continue + } + if (RULE.test(raw) || ROW.test(raw)) { blank = false block.push(raw) @@ -67,7 +109,7 @@ export function prettyLines(lines: readonly string[]): string[] { } blank = false - out.push(line) + out.push(textLine(line)) } flush() diff --git a/plugins/ruflo-console/tests/result-lines.spec.ts b/plugins/ruflo-console/tests/result-lines.spec.ts index 78cbfb43b6..925014434b 100644 --- a/plugins/ruflo-console/tests/result-lines.spec.ts +++ b/plugins/ruflo-console/tests/result-lines.spec.ts @@ -1,7 +1,7 @@ /** The result lines are tidied before a view draws them: ASCII tables are drawn again with aligned columns, nothing else is rewritten. */ import { describe, expect, it } from 'vitest' -import { prettyLines } from '../hooks/result-lines' +import { plainMarkdown, prettyLines } from '../hooks/result-lines' const PASTED = [ 'Pattern Optimization (Real)', @@ -61,3 +61,40 @@ describe('prettyLines', () => { for (const line of prettyLines(PASTED).filter(row => row.startsWith('│'))) for (const cell of line.slice(1, -1).split('│').map(part => part.trim())) expect(cells.has(cell), cell).toBe(true) }) }) + +describe('markdown in a result', () => { + it('draws a markdown pipe table like the CLI one, and reads the markers inside its cells', () => { + const out = prettyLines(['| Component | Status |', '|---|:---:|', '| **SONA** | `Active` |', '| HNSW | Available |']) + + expect(out[0]).toBe('┌───────────┬───────────┐') + expect(out[1]).toBe('│ Component │ Status │') + expect(out[2]).toBe('├───────────┼───────────┤') + expect(out[3]).toBe('│ SONA │ Active │') + expect(out.at(-1)).toBe('└───────────┴───────────┘') + expect(out.join('\n')).not.toMatch(/\*\*|`|:---/) + }) + + it('reads headings, bullets, quotes, bold, code and links as plain text', () => { + expect(prettyLines(['## Neural status', '', '- **SONA** is `active`', ' * nested [docs](https://example.com/a)', '> a note'])).toEqual([ + '▸ Neural status', + '', + '• SONA is active', + ' • nested docs (https://example.com/a)', + '│ a note', + ]) + }) + + it('shows a fenced block as it is, without the fences, and leaves single asterisks and unpaired markers alone', () => { + expect(prettyLines(['```json', '{ "a": **1** }', '```', 'after'])).toEqual(['{ "a": **1** }', 'after']) + expect(plainMarkdown('5 * 3 = 15, snake_case, a **dangling')).toBe('5 * 3 = 15, snake_case, a **dangling') + expect(plainMarkdown('use `npm test` and **always** [x](https://a.b)')).toBe('use npm test and always x (https://a.b)') + }) + + it('keeps a table that mixes both styles apart from the text around it', () => { + const out = prettyLines(['Result:', '+---+---+', '| a | b |', '+---+---+', '| 1 | 2 |', '+---+---+', '', '**done**']) + + expect(out[0]).toBe('Result:') + expect(out.filter(line => line.startsWith('┌'))).toHaveLength(1) + expect(out.at(-1)).toBe('done') + }) +}) From 345ad256f7ebddcc163389d2b1db8299c545deb7 Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 15:17:28 -0400 Subject: [PATCH 3/6] fix(ruflo-console): the Optimizer's answer panel is framed like every other result It built its own result rows and was missed by the shared frame. Same frame, coloured by the outcome. Co-Authored-By: RuFlo --- plugins/ruflo-console/hooks/views/optimizer.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugins/ruflo-console/hooks/views/optimizer.ts b/plugins/ruflo-console/hooks/views/optimizer.ts index 5ec7313736..fe4445a730 100644 --- a/plugins/ruflo-console/hooks/views/optimizer.ts +++ b/plugins/ruflo-console/hooks/views/optimizer.ts @@ -3,6 +3,7 @@ import type { RenderElement } from 'claude-code' import { diagnose, offered, optimizerOf, metricNow, SCOPES, type Finding } from '../optimizer' import { slot } from './attention' import { clip, row, section, text, THEME, type Ctx } from './common' +import { frameResult } from './status-card' const GLYPH = { bad: '✖', warn: '⚠', info: 'ℹ' } as const const COLOR = { bad: () => THEME.bad, warn: () => THEME.warn, info: () => THEME.info } as const @@ -47,7 +48,7 @@ function resultRows(ctx: Ctx): RenderElement[] { for (const line of result.lines.slice(0, 14)) rows.push(text(ctx, ` ${line}`, line.startsWith('⚠') ? { color: THEME.warn } : {})) if (result.lines.length > 14) rows.push(text(ctx, ` … ${result.lines.length - 14} more lines: open the section that owns this command`, { dimColor: true })) - return slot(ctx, rows) + return slot(ctx, [frameResult(ctx, rows, result.ok ? 'ok' : 'bad')]) } /** From ee772e73b6daf716f7173d467a7d61b98a58466e Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 15:23:48 -0400 Subject: [PATCH 4/6] test(ruflo-console): a result renders in the real engine as an aligned table with markdown read as text, inside a result frame Runs a Dev Tools read whose CLI answer is the pasted neural patterns table plus a markdown line, and checks the drawn text (box-drawn aligned table, no ASCII rules, markers gone) and the element tree (one round result-frame). Co-Authored-By: RuFlo --- .../tests/result-display.test.ts | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 plugins/ruflo-console/tests/result-display.test.ts diff --git a/plugins/ruflo-console/tests/result-display.test.ts b/plugins/ruflo-console/tests/result-display.test.ts new file mode 100644 index 0000000000..701a5851ec --- /dev/null +++ b/plugins/ruflo-console/tests/result-display.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, mock, test } from 'claude-code/testing' + +import { RUFLO_FILES } from './fixtures/ruflo-run' +import { cliAnswer, command, elementsOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world' + +/** The pasted `neural patterns` answer: the CLI's ASCII table, as the CLI prints it. */ +const TABLE = [ + 'Neural Patterns - list', + '+--------------------+--------+------------+-------+', + '| ID | Type | Confidence | Usage |', + '+--------------------+--------+------------+-------+', + '| pattern-1783881957 | action | 100.0% | 524 |', + '| pattern-1785100193 | result | 100.0% | 385 |', + '+--------------------+--------+------------+-------+', + '', + '**2 patterns** shown, see `neural train`', +].join('\n') + +describe('result display in the real engine', () => { + test('a result is one coloured frame, its CLI table is drawn with aligned columns, and markdown is read as text', { options: { boot: false } }, async ($, on) => { + const world = worldOf(on, RUFLO_FILES) + + world.respond = argv => (argv.includes('analyze_diff-stats') ? { exitCode: 0, stdout: TABLE, stderr: '' } : cliAnswer(argv)) + mock.clock(on) + await $.session.start(SESSION) + await $.command.run(command('devtools')) + + const pane = await $.ui.mount({ ...paneAt(110), plugin: PLUGIN }) + + await pane.press({ key: 'dt-diff-stats' }) + + const tree = await pane.drawn() + const text = textOf(tree) + + + // The table is read back as cells and drawn with box characters, every row the same width. + expect(text).toContain('┌────────────────────┬────────┬────────────┬───────┐') + expect(text).toContain('│ ID │ Type │ Confidence │ Usage │') + expect(text).toContain('│ pattern-1783881957 │ action │ 100.0% │ 524 │') + expect(text).not.toContain('| ID | Type |') + expect(text).not.toContain('+-------') + // Markdown markers are gone from the sentence under it. + expect(text).toContain('2 patterns shown, see neural train') + expect(text).not.toContain('**2 patterns**') + // And the result sits in one rounded frame, green because the run passed (the text surface does not draw borders, so the tree is checked). + const frames = elementsOf(tree, 'Box').filter(box => (box.props as { key?: string }).key === 'result-frame') + + expect(frames).toHaveLength(1) + expect(frames[0]?.props).toMatchObject({ borderStyle: 'round', borderColor: expect.stringMatching(/.+/) }) + }) +}) From 3fc617f0d3bbb415ba7903e2cd55600e492a96eb Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 15:48:53 -0400 Subject: [PATCH 5/6] ci: the new result-display kit test runs under claude plugin test, not root vitest It imports claude-code/testing, which only exists inside Claude Code, so the ratchet reported it as an unexpected failing file. It joins the excluded list (scripts/ci-test-excluded.txt) like every other plugin kit test. Co-Authored-By: RuFlo --- scripts/ci-test-excluded.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/ci-test-excluded.txt b/scripts/ci-test-excluded.txt index a9c0ce7d79..98ed571417 100644 --- a/scripts/ci-test-excluded.txt +++ b/scripts/ci-test-excluded.txt @@ -5,6 +5,7 @@ # - the .mjs files use node:test: `node --test` runs them (all-plugins-smoke.yml and the plugin smokes). # A listed file that no longer exists fails the ratchet, so this list cannot go stale silently. Never add a file here to make a real # regression green: a file that vitest CAN run belongs in scripts/ci-test-baseline.txt (and that file may only shrink). + plugins/ruflo-adr/tests/mod.test.ts plugins/ruflo-agentdb/tests/fold.test.ts plugins/ruflo-agentdb/tests/guard-scan.test.ts @@ -76,3 +77,4 @@ scripts/__tests__/guard-label.test.mjs scripts/__tests__/mod-capability-matrix.test.mjs tests/check-guard-tool-names.test.mjs tests/check-status-forwarding.test.mjs +plugins/ruflo-console/tests/result-display.test.ts From 1a2318f084a433f25f2a3133942ef0bf9520ebc0 Mon Sep 17 00:00:00 2001 From: ruv Date: Mon, 5 Oct 2026 16:05:48 -0400 Subject: [PATCH 6/6] fix(ruflo-console): smoke step 12 accepts the excluded list as well as the CI baseline for kit tests A new kit test belongs on scripts/ci-test-excluded.txt (the baseline only shrinks), which step 12 did not know about. Co-Authored-By: RuFlo --- plugins/ruflo-console/scripts/smoke.sh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh index 15f6b9799a..db1afd8660 100755 --- a/plugins/ruflo-console/scripts/smoke.sh +++ b/plugins/ruflo-console/scripts/smoke.sh @@ -70,12 +70,13 @@ step "11. every source file is under 500 lines" long=$(find "$HOOKS" "$ROOT/tests" "$ROOT/scripts" -name '*.ts' -not -path '*/fixtures/ruflo-run.ts' -exec awk 'END { if (NR > 500) print FILENAME }' {} \;) [[ -z "$long" ]] && ok || bad "$long" -step "12. kit tests are in the CI baseline (root vitest cannot resolve claude-code/testing)" +step "12. kit tests are off the root vitest run (it cannot resolve claude-code/testing): in the CI baseline or the excluded list" miss="" for f in "$ROOT"/tests/*.test.ts; do - grep -qx "plugins/ruflo-console/tests/$(basename "$f")" "$REPO/scripts/ci-test-baseline.txt" || miss="$miss $(basename "$f")" + name="plugins/ruflo-console/tests/$(basename "$f")" + grep -qx "$name" "$REPO/scripts/ci-test-baseline.txt" || grep -qx "$name" "$REPO/scripts/ci-test-excluded.txt" || miss="$miss $(basename "$f")" done -[[ -z "$miss" ]] && ok || bad "not in baseline:$miss" +[[ -z "$miss" ]] && ok || bad "in neither the CI baseline nor the excluded list:$miss" step "13. marketplace lists ruflo-console" grep -q '"name": "ruflo-console"' "$REPO/.claude-plugin/marketplace.json" && ok || bad "missing marketplace entry"