🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(cli,console): ruflo tui, the console in a terminal of its own (ADR-489, phase 1)
rc11b5461f528
diff --git a/plugins/ruflo-console/.gitignore b/plugins/ruflo-console/.gitignoreindex 04f42e62f5..21c6d6f695 100644--- a/plugins/ruflo-console/.gitignore+++ b/plugins/ruflo-console/.gitignore@@ -1,2 +1,3 @@# Claude Code writes its declarations here on load or validate (early access, regenerate per release).claude-plugin/types/+dist/diff --git a/plugins/ruflo-console/scripts/build-tui.mjs b/plugins/ruflo-console/scripts/build-tui.mjsnew file mode 100644index 0000000000..ab953e146a--- /dev/null+++ b/plugins/ruflo-console/scripts/build-tui.mjs@@ -0,0 +1,33 @@+#!/usr/bin/env node+// Bundles the standalone terminal console (ADR-489) into dist/tui.mjs: the plugin's own TypeScript, one file, no runtime+// dependencies. esbuild is a BUILD-time tool only (resolved from the repo's node_modules); nothing here ships as a dependency.+// node plugins/ruflo-console/scripts/build-tui.mjs [--outfile <path>] [--check]+import { statSync } from 'node:fs'+import { createRequire } from 'node:module'+import { dirname, join, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const flag = name => process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : undefined+const outfile = resolve(flag('--outfile') ?? join(root, 'dist', 'tui.mjs'))++let esbuild+try {+ esbuild = createRequire(join(root, '..', '..', 'package.json'))('esbuild')+} catch {+ console.error('build-tui: esbuild is not installed (run npm install at the repo root).')+ process.exit(1)+}++await esbuild.build({+ entryPoints: [join(root, 'tui', 'main.ts')],+ bundle: true,+ platform: 'node',+ format: 'esm',+ target: 'node20',+ minify: true,+ legalComments: 'none',+ outfile,+ logLevel: 'warning',+})+console.log(`build-tui: ${outfile} (${Math.round(statSync(outfile).size / 1024)} KiB)`)diff --git a/plugins/ruflo-console/tests/tui-boundary.spec.ts b/plugins/ruflo-console/tests/tui-boundary.spec.tsnew file mode 100644index 0000000000..66a61c5039--- /dev/null+++ b/plugins/ruflo-console/tests/tui-boundary.spec.ts@@ -0,0 +1,62 @@+/**+ * The host-adapter boundary (ADR-489), kept true by test: `hooks/` is the part of the console that is the same on every host. It has no+ * value import of the Claude Code engine, no Node module and no package, and only `register.ts` and `model-tools.ts` reach `$`. The+ * standalone shell (`tui/`) imports neither of those two. Run with+ * npx vitest run plugins/ruflo-console/tests/tui-boundary.spec.ts+ */+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { dirname, join, relative } from 'node:path'+import { fileURLToPath } from 'node:url'+import { describe, expect, it } from 'vitest'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const walk = (dir: string): string[] => readdirSync(dir).flatMap(name => (statSync(join(dir, name)).isDirectory() ? walk(join(dir, name)) : name.endsWith('.ts') ? [join(dir, name)] : []))+const bare = (file: string): string => readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '')+/** Every `import … from 'x'` / `export … from 'x'` statement as [is it type-only, the specifier]; a statement cannot cross a quote, so none runs into the next. */+const importsOf = (text: string): Array<[boolean, string]> => [...text.matchAll(/^(import|export)\b([^'";]*?)from\s+'([^']+)'/gm)].map(match => [/^\s*type\b/.test(match[2] ?? ''), match[3] as string])+const hooks = walk(join(root, 'hooks')).map(file => ({ file: relative(join(root, 'hooks'), file), text: bare(file) }))++/** The two modules that talk to the Claude Code engine directly. */+const ENGINE_ONLY = ['model-tools.ts', 'register.ts']+const ENGINE = /\$\.(ui|clock|store|fs|http|process|session|tool|settings|env|plugin|command|prompt|ruflo)\.[a-zA-Z]+\(|\bon\('|EngineInterface|\bRegister\b/++describe('hooks/ is host-neutral', () => {+ it('imports the Claude Code declarations as types only', () => {+ const offenders = hooks.filter(({ text }) => importsOf(text).some(([isType, from]) => !isType && /^claude-code/.test(from))).map(({ file }) => file)++ expect(offenders).toEqual([])+ })++ it('imports no Node module and no package: every import is a relative path or a type', () => {+ const offenders = hooks.filter(({ text }) => importsOf(text).some(([isType, from]) => !isType && !from.startsWith('.')) || /\bimport\(\s*'(?![./])/.test(text) || /\brequire\(/.test(text)).map(({ file }) => file)++ expect(offenders).toEqual([])+ })++ it('reaches the engine only from register.ts and model-tools.ts', () => {+ expect(hooks.filter(({ text }) => ENGINE.test(text)).map(({ file }) => file).sort()).toEqual(ENGINE_ONLY)+ })+})++describe('tui/ is the second adapter', () => {+ const tui = walk(join(root, 'tui')).map(file => ({ file: relative(root, file), text: bare(file), lines: readFileSync(file, 'utf8').split('\n').length }))++ it('exists, stays under 500 lines a file, and never imports the engine-only modules', () => {+ expect(tui.length).toBeGreaterThanOrEqual(5)+ expect(tui.filter(({ lines }) => lines > 500)).toEqual([])+ expect(tui.filter(({ text }) => /from\s+'\.\.\/hooks\/(register|model-tools)'/.test(text))).toEqual([])+ })++ it('has no runtime dependency: only node: modules, relative paths and types', () => {+ const offenders = tui.filter(({ text }) => importsOf(text).some(([isType, from]) => !isType && !from.startsWith('node:') && !from.startsWith('.'))).map(({ file }) => file)++ expect(offenders).toEqual([])+ })++ it('implements every member of Host the controller can call, and nothing in hooks/ changed shape', async () => {+ const { createNodeHost } = await import('../tui/node-host')+ const host = createNodeHost({ cwd: root })++ for (const member of ['fs', 'every', 'after', 'storeGet', 'storeSet', 'fetchText', 'askChoice', 'toast', 'invalidate', 'scrollTop', 'focus', 'blit', 'openPane', 'closePane', 'panes', 'registerCommand', 'run', 'spawn', 'usage', 'rufloTools', 'settings', 'home', 'configDir', 'pluginRoot', 'rufloSnapshot', 'rufloRoute', 'rufloSegment', 'submitPrompt', 'fillPrompt', 'listCommands', 'runSlash']) expect(host).toHaveProperty(member)+ })+})diff --git a/plugins/ruflo-console/tests/tui-host.spec.ts b/plugins/ruflo-console/tests/tui-host.spec.tsnew file mode 100644index 0000000000..94a6643d2f--- /dev/null+++ b/plugins/ruflo-console/tests/tui-host.spec.ts@@ -0,0 +1,117 @@+/**+ * The standalone Node host (ADR-489): reads stay inside the project, `~/.claude` and `~/.claude-flow` (links resolved first); the only+ * program that runs is the ruflo CLI by argv; everything that needs the Claude Code engine is refused. Run with+ * npx vitest run plugins/ruflo-console/tests/tui-host.spec.ts+ */+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { cliArgv, createNodeHost } from '../tui/node-host'++let root: string+let project: string+let home: string+let outside: string++beforeAll(() => {+ root = mkdtempSync(join(tmpdir(), 'tui-host-'))+ project = join(root, 'project')+ home = join(root, 'home')+ outside = join(root, 'outside')+ for (const dir of [join(project, '.claude-flow'), join(home, '.claude'), join(home, '.ssh'), outside]) mkdirSync(dir, { recursive: true })+ writeFileSync(join(project, '.claude-flow', 'a.json'), '{"ok":true}')+ writeFileSync(join(home, '.claude', 'settings.json'), '{}')+ writeFileSync(join(home, '.ssh', 'id_ed25519'), 'PRIVATE')+ writeFileSync(join(outside, 'secret.txt'), 'nope')+ symlinkSync(outside, join(project, 'escape'))+ symlinkSync(join(outside, 'secret.txt'), join(project, '.claude-flow', 'link.json'))+ // A CLI stand-in: prints its argv and whether a parent secret reached its environment.+ writeFileSync(join(root, 'cli.mjs'), 'console.log(JSON.stringify({ argv: process.argv.slice(2), leaked: process.env.OPENROUTER_API_KEY ?? null, cwd: process.cwd() }))')+})+afterAll(() => rmSync(root, { recursive: true, force: true }))++const hostOf = (extra = {}) => createNodeHost({ cwd: project, home, cliEntry: join(root, 'cli.mjs'), ...extra })++describe('reads', () => {+ it('reads inside the project and ~/.claude, relative or absolute', async () => {+ const host = hostOf()++ await expect(host.fs.read('.claude-flow/a.json')).resolves.toBe('{"ok":true}')+ await expect(host.fs.read(join(home, '.claude', 'settings.json'))).resolves.toBe('{}')+ await expect(host.fs.stat('.claude-flow/a.json')).resolves.toMatchObject({ kind: 'file', isLink: false })+ expect((await host.fs.list('.claude-flow')).map(entry => entry.name)).toContain('a.json')+ })++ it('refuses a path outside the roots, a ../ climb and ~/.ssh', async () => {+ const host = hostOf()++ await expect(host.fs.read(join(outside, 'secret.txt'))).rejects.toThrow()+ await expect(host.fs.read('../outside/secret.txt')).rejects.toThrow()+ await expect(host.fs.read(join(home, '.ssh', 'id_ed25519'))).rejects.toThrow()+ await expect(host.fs.list('/')).rejects.toThrow()+ })++ it('refuses a symlink that leaves the project, for a file and for a folder', async () => {+ const host = hostOf()++ await expect(host.fs.read('escape/secret.txt')).rejects.toThrow()+ await expect(host.fs.read('.claude-flow/link.json')).rejects.toThrow()+ await expect(host.fs.list('escape')).rejects.toThrow()+ })++ it('answers undefined for a stat it may not make', async () => {+ await expect(hostOf().fs.stat(join(outside, 'secret.txt'))).resolves.toBeUndefined()+ })+})++describe('programs', () => {+ it('rewrites a ruflo CLI prefix to this CLI, and nothing else', () => {+ expect(cliArgv(['npx', '--offline', '-y', '@claude-flow/cli@latest', 'hooks', 'model-stats'], '/x/cli.js')).toEqual([process.execPath, '/x/cli.js', 'hooks', 'model-stats'])+ expect(cliArgv(['ruflo', '--version'], '/x/cli.js')).toEqual([process.execPath, '/x/cli.js', '--version'])+ expect(cliArgv(['sh', '-c', 'echo hi'], '/x/cli.js')).toBeNull()+ expect(cliArgv(['claude', 'plugin', 'configure', '--help'], '/x/cli.js')).toBeNull()+ expect(cliArgv(['ruflo', '--version'], undefined)).toBeNull()+ })++ it('runs the CLI with no shell, in the project, without the parent secrets', async () => {+ process.env.OPENROUTER_API_KEY = 'sk-or-v1-should-not-reach-the-child'+ try {+ const done = await hostOf().run(['ruflo', 'memory', 'stats; echo pwned'], 10_000)+ const seen = JSON.parse(done.stdout) as { argv: string[]; leaked: string | null; cwd: string }++ expect(done.exitCode).toBe(0)+ expect(seen.argv).toEqual(['memory', 'stats; echo pwned'])+ expect(seen.leaked).toBeNull()+ expect(seen.cwd.endsWith('project')).toBe(true)+ } finally {+ delete process.env.OPENROUTER_API_KEY+ }+ })++ it('refuses any other program, and every run when no CLI entry is known', async () => {+ await expect(hostOf().run(['sh', '-c', 'echo hi'], 1000)).rejects.toThrow(/not available in the standalone terminal/)+ await expect(createNodeHost({ cwd: project, home }).run(['ruflo', '--version'], 1000)).rejects.toThrow()+ })+})++describe('the Claude Code engine is refused, not faked', () => {+ it('rejects panes, dialogs, network, the prompt box, slash commands and ruflo-mods; spawn throws', async () => {+ const host = hostOf()++ for (const refused of [host.fetchText('https://example.com'), host.askChoice('ok?', ['yes']), host.openPane({} as never), host.panes(), host.settings(), host.rufloSnapshot(), host.submitPrompt('hi'), host.runSlash('x', '')]) await expect(refused).rejects.toThrow(/not available in the standalone terminal/)+ expect(() => host.spawn(['ruflo'])).toThrow()+ expect(host.toolCall).toBeUndefined()+ expect(host.httpSend).toBeUndefined()+ await expect(host.fillPrompt('x')).resolves.toBe(false)+ })++ it('keeps the small store in memory only', async () => {+ const host = hostOf()++ await host.storeSet('k', { v: 1 })+ await expect(host.storeGet('k')).resolves.toEqual({ v: 1 })+ await expect(hostOf().storeGet('k')).resolves.toBeUndefined()+ })+})diff --git a/plugins/ruflo-console/tests/tui-render.spec.ts b/plugins/ruflo-console/tests/tui-render.spec.tsnew file mode 100644index 0000000000..3ff6b10028--- /dev/null+++ b/plugins/ruflo-console/tests/tui-render.spec.ts@@ -0,0 +1,90 @@+/**+ * The standalone renderer (ADR-489) is the chokepoint the Claude Code engine is in the mod: hostile text from ruflo files must+ * never reach the terminal as an escape sequence, and a secret never as text. Run with+ * npx vitest run plugins/ruflo-console/tests/tui-render.spec.ts+ */+import { describe, expect, it } from 'vitest'++import { clean, render, terminalKit, widthOf } from '../tui/ansi'++const kit = terminalKit()+const text = (children: unknown, props: Record<string, unknown> = {}) => kit.Text({ children, ...props } as never)+const box = (children: unknown[], props: Record<string, unknown> = {}) => kit.Box({ children, ...props } as never)+/** Every escape sequence the output holds, so a test can say "only ours". */+const escapes = (lines: string[]) => lines.join('\n').match(/\u001b[^m]*m?|\u009b/g) ?? []+const OURS = /^\u001b\[[0-9;]*m$/++describe('clean', () => {+ it('removes OSC, CSI, C1 and invisible characters, keeping the words', () => {+ expect(clean('swarm-\u001b]0;pwned\u0007one\u001b[31m red \u009b2J end')).toBe('swarm-one red end')+ expect(clean('a\nb\tc\r\nd')).toBe('a b c d')+ })++ it('withholds a whole line that holds a secret', () => {+ expect(clean('token ghp_abcdefghijklmnopqrstuvwxyz0123456789 here')).toMatch(/withheld/)+ expect(clean('key sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')).toMatch(/withheld/)+ })++ it('treats a non-string as empty and a number as its digits', () => {+ expect(clean(undefined)).toBe('')+ expect(clean({})).toBe('')+ expect(clean(42)).toBe('42')+ })+})++describe('render', () => {+ it('never lets content write an escape: only the renderer\'s own colour codes remain', () => {+ const hostile = box([text('\u001b]0;pwned\u0007\u001b[2J\u001b[?1049h name', { color: '#ff2a6d', bold: true }), kit.Button({ key: 'x', label: 'go\u001b[31m', hotkey: 'g' } as never)], { flexDirection: 'row' })++ for (const depth of ['none', '256', 'truecolor'] as const) {+ const out = render(hostile, 80, depth)++ expect(escapes(out).every(seq => OURS.test(seq))).toBe(true)+ expect(out.join('')).not.toContain('pwned')+ }+ expect(escapes(render(hostile, 80, 'none'))).toEqual([])+ })++ it('maps theme names and hex to 256 and truecolor sequences, and none to plain text', () => {+ expect(render(text('x', { color: 'success' }), 20, '256')[0]).toContain('38;5;71')+ expect(render(text('x', { color: '#ff0000' }), 20, 'truecolor')[0]).toContain('38;2;255;0;0')+ expect(render(text('x', { color: '#ff0000' }), 20, '256')[0]).toContain('38;5;196')+ expect(render(text('x', { color: 'error', bold: true }), 20, 'none')).toEqual(['x'])+ })++ it('lays a row out side by side and a column as lines', () => {+ expect(render(box([text('label '), text('value')], { flexDirection: 'row' }), 40, 'none')).toEqual(['label value'])+ expect(render(box([text('one'), text('two')], { flexDirection: 'column' }), 40, 'none')).toEqual(['one', 'two'])+ })++ it('wraps long text, truncates where asked, and never exceeds the width', () => {+ const wrapped = render(text('word '.repeat(30)), 24, 'none')+ const cut = render(text('x'.repeat(100), { wrap: 'truncate-end' }), 24, 'none')++ expect(wrapped.length).toBeGreaterThan(3)+ expect(wrapped.every(line => widthOf(line) <= 24)).toBe(true)+ expect(cut).toHaveLength(1)+ expect(widthOf(cut[0] as string)).toBeLessThanOrEqual(24)+ expect(cut[0]).toMatch(/…$/)+ })++ it('draws a rounded border exactly as wide as asked, around padded content', () => {+ const out = render(box([text('hi')], { borderStyle: 'round', paddingX: 1 }), 20, 'none')++ expect(out).toHaveLength(3)+ expect(out.every(line => widthOf(line) === 20)).toBe(true)+ expect(out[0]?.startsWith('╭')).toBe(true)+ expect(out[1]).toContain(' hi')+ })++ it('draws a button as an inert bracketed label and skips hidden boxes', () => {+ expect(render(kit.Button({ key: 'k', label: 'Refresh' } as never), 30, 'none')).toEqual(['[Refresh]'])+ expect(render(box([text('gone')], { hidden: true }), 30, 'none')).toEqual([])+ })++ it('survives garbage: null, booleans, unknown types, deep nesting', () => {+ expect(render(null, 10, 'none')).toEqual([])+ expect(render({ type: 'Raster', props: {} }, 10, 'none')).toEqual([])+ expect(render([false, undefined, [[text('ok')]]], 10, 'none')).toEqual(['ok'])+ })+})diff --git a/plugins/ruflo-console/tests/tui-session.spec.ts b/plugins/ruflo-console/tests/tui-session.spec.tsnew file mode 100644index 0000000000..0b29fc456b--- /dev/null+++ b/plugins/ruflo-console/tests/tui-session.spec.ts@@ -0,0 +1,182 @@+/**+ * `ruflo tui` end to end without a terminal (ADR-489): real ruflo files on disk, the mod's own controller and views over the Node+ * host, drawn by the mod's own paneView, headless and with an injected terminal. Run with+ * npx vitest run plugins/ruflo-console/tests/tui-session.spec.ts+ */+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import { depthOf, keyOf, runTui, type TuiIO } from '../tui/run'+import { openSession } from '../tui/session'+import { RUFLO_FILES } from './fixtures/ruflo-run'++let root: string+let project: string+let hostile: string++const ESC = '\u001b'+const put = (base: string, files: Record<string, string>) => {+ for (const [path, body] of Object.entries(files)) {+ mkdirSync(dirname(join(base, path)), { recursive: true })+ writeFileSync(join(base, path), body)+ }+}++beforeAll(() => {+ root = mkdtempSync(join(tmpdir(), 'tui-session-'))+ project = join(root, 'project')+ hostile = join(root, 'hostile')+ put(project, RUFLO_FILES)+ // The same project with an escape sequence and a token where a swarm id and topology are read from disk (both files that name it).+ put(hostile, { ...RUFLO_FILES, '.swarm/state.json': JSON.stringify({ id: `swarm-\u001b]0;pwned\u0007-1`, topology: 'ghp_abcdefghijklmnopqrstuvwxyz0123456789', status: 'running' }), '.claude-flow/swarm/swarm-state.json': JSON.stringify({ swarms: { 'swarm-1': { swarmId: `swarm-\u001b]0;pwned\u0007-1`, topology: 'ghp_abcdefghijklmnopqrstuvwxyz0123456789', status: 'running', agents: [] } } }) })+})+afterAll(() => rmSync(root, { recursive: true, force: true }))++function fakeIO(isTTY: boolean) {+ const out: string[] = []+ const err: string[] = []+ const listeners: Array<(chunk: string) => void> = []+ const raw: boolean[] = []+ const io: TuiIO = {+ stdin: { isTTY, setRawMode: isTTY ? on => void raw.push(on) : undefined, on: (_e, fn) => void listeners.push(fn as never), off: () => void listeners.splice(0), resume: () => undefined, pause: () => undefined },+ stdout: { isTTY, columns: 100, rows: 30, write: text => void out.push(text) },+ stderr: { write: text => void err.push(text) },+ env: { TERM: 'xterm-256color' },+ }++ return { io, out, err, raw, press: (key: string) => listeners.forEach(fn => fn(key)) }+}++describe('the same views over real ruflo files', () => {+ it('Overview shows the swarm, the daemon and the helpers read from disk', async () => {+ const session = openSession({ cwd: project, home: join(root, 'home') })++ await session.refresh()+ const text = session.frame(110, 'none').join('\n')++ expect(text).toContain('swarm-1790903031804-y9rnjr')+ expect(text).toContain('running per daemon-state.json')+ expect(text).toContain('manifest v3.32.24')+ expect(text).toContain('Overview')+ session.stop()+ })++ it('Cost shows its sections and says n/a for what only the Claude Code host can measure', async () => {+ const session = openSession({ cwd: project, home: join(root, 'home') })++ await session.refresh()+ session.show('cost')+ const text = session.frame(110, 'none').join('\n')++ expect(text).toContain('Where it goes')+ expect(text).toContain('Alert thresholds')+ expect(text).toMatch(/Claude Code\s+n\/a/)+ session.stop()+ })++ it('is the mod\'s own tree: the standalone frame carries the same pane header the mod draws', async () => {+ const session = openSession({ cwd: project, home: join(root, 'home') })++ await session.refresh()+ expect(session.frame(110, 'none').join('\n')).toContain('what ruflo is doing here')+ session.stop()+ })++ it('hostile ruflo files: no escape from content and no token reach the frame (the data layer refuses the id, the renderer strips the rest)', async () => {+ const session = openSession({ cwd: hostile, home: join(root, 'home') })++ await session.refresh()+ for (const depth of ['none', '256'] as const) {+ const text = session.frame(110, depth).join('\n')++ expect(text).toContain('Subsystems')+ expect(text).not.toContain('pwned')+ expect(text).not.toContain('ghp_abcdefghij')+ expect(text.match(/\u001b\[[0-9;]*m/g)?.length ?? 0).toBe(depth === 'none' ? 0 : text.match(/\u001b/g)?.length)+ }+ session.stop()+ })++ it('never calls the engine: every host call the controller made was a read or a refusal', async () => {+ const ran: string[][] = []+ const calls: string[] = []+ const base = openSession({ cwd: project, home: join(root, 'home') }).host+ const spy = new Proxy(base, { get: (target, key: string) => (typeof target[key as keyof typeof target] === 'function' ? (...args: never[]) => (calls.push(key), (target[key as keyof typeof target] as (...a: never[]) => unknown)(...args)) : target[key as keyof typeof target]) })+ const session = openSession({ cwd: project }, { ...spy, run: async argv => (ran.push([...argv]), Promise.reject(new Error('no program'))) })++ await session.refresh()+ expect(calls.filter(call => ['openPane', 'blit', 'toolCall', 'submitPrompt', 'spawn', 'askChoice'].includes(call))).toEqual([])+ expect(ran.length).toBeGreaterThan(0)+ expect(ran.every(argv => argv[0] === 'npx' || argv[0] === 'claude')).toBe(true)+ session.stop()+ })+})++describe('headless', () => {+ it('prints one plain frame to stdout, a note to stderr, and returns 0', async () => {+ const { io, out, err } = fakeIO(false)+ const code = await runTui({ cwd: project, home: join(root, 'home') }, io)++ expect(code).toBe(0)+ expect(out.join('')).toContain('swarm-1790903031804-y9rnjr')+ expect(out.join('')).not.toContain(ESC)+ expect(err.join('')).toMatch(/not an interactive terminal/)+ })++ it('opens the page asked for', async () => {+ const { io, out } = fakeIO(false)++ await runTui({ cwd: project, home: join(root, 'home'), view: 'cost' }, io)+ expect(out.join('')).toContain('Where it goes')+ })+})++describe('interactive', () => {+ it('enters the alternate screen, switches page on a key, and restores the terminal on q', async () => {+ const { io, out, raw, press } = fakeIO(true)+ const running = runTui({ cwd: project, home: join(root, 'home') }, io)++ await new Promise(resolve => setTimeout(resolve, 150))+ press('c')+ press('j')+ press('q')+ await expect(running).resolves.toBe(0)++ const screen = out.join('')++ expect(screen.startsWith(`${ESC}[?1049h`)).toBe(true)+ expect(screen).toContain('Where it goes')+ expect(screen).toContain('cost ·')+ expect(screen.endsWith(`${ESC}[?25h${ESC}[?1049l`)).toBe(true)+ expect(raw).toEqual([true, false])+ })++ it('restores the terminal when the signal aborts', async () => {+ const { io, out, raw } = fakeIO(true)+ const stop = new AbortController()+ const running = runTui({ cwd: project, home: join(root, 'home') }, { ...io, signal: stop.signal })++ await new Promise(resolve => setTimeout(resolve, 100))+ stop.abort()+ await expect(running).resolves.toBe(0)+ expect(out.join('').endsWith(`${ESC}[?1049l`)).toBe(true)+ expect(raw).toEqual([true, false])+ })+})++describe('keys and colour depth', () => {+ it('maps the documented keys and ignores the rest', () => {+ expect([keyOf('q'), keyOf('\u0003'), keyOf('o'), keyOf('c'), keyOf('r'), keyOf('j'), keyOf(`${ESC}[A`), keyOf(' ')]).toEqual(['quit', 'quit', 'overview', 'cost', 'refresh', 'down', 'up', 'pagedown'])+ expect([keyOf('x'), keyOf(`${ESC}]0;t\u0007`), keyOf('')]).toEqual([null, null, null])+ })++ it('picks the colour depth from the environment', () => {+ expect(depthOf({ NO_COLOR: '1', TERM: 'xterm' })).toBe('none')+ expect(depthOf({ TERM: 'dumb' })).toBe('none')+ expect(depthOf({})).toBe('none')+ expect(depthOf({ TERM: 'xterm-256color' })).toBe('256')+ expect(depthOf({ TERM: 'xterm', COLORTERM: 'truecolor' })).toBe('truecolor')+ })+})diff --git a/plugins/ruflo-console/tsconfig.json b/plugins/ruflo-console/tsconfig.jsonindex 3bb82d63d4..ecd4cb9c0a 100644--- a/plugins/ruflo-console/tsconfig.json+++ b/plugins/ruflo-console/tsconfig.json@@ -15,5 +15,5 @@"typeRoots": ["./.claude-plugin/types"],"types": ["claude-code", "claude-code-tools", "claude-code-mcp"]},- "include": ["hooks", "types", "tests"]+ "include": ["hooks", "tui", "types", "tests"]}diff --git a/plugins/ruflo-console/tui/ansi.ts b/plugins/ruflo-console/tui/ansi.tsnew file mode 100644index 0000000000..61a63a83ca--- /dev/null+++ b/plugins/ruflo-console/tui/ansi.ts@@ -0,0 +1,188 @@+/**+ * The standalone renderer (ADR-489): the element tree the console's views build (`Box`, `Text`, `Button`) drawn as terminal lines.+ * The Claude Code engine neutralises escape sequences in `Text`; here this file is that chokepoint, so every string that reaches+ * the screen has been through `clean` first (escapes, control and invisible characters removed, a line that holds a secret+ * withheld whole). Pure: no I/O, no Node.+ */+import { ESCAPES, INVISIBLE } from '../hooks/data/parse'+import { hasSecret } from '../hooks/screen'+import { hasInvite } from '../hooks/xruv'+import type { Kit } from '../hooks/views/common'++const SECRET_LINE = '(line withheld: it looks like a secret: not shown)'+const SPACING = /[\t\n\r\u000b\u000c\u2028\u2029]+/g+const CONTROLS = /[\u0000-\u001f\u007f-\u009f]/g++/** The one path a string takes to the screen. */+export function clean(raw: unknown): string {+ const line = typeof raw === 'string' ? raw : typeof raw === 'number' ? String(raw) : ''+ const joined = line.replace(ESCAPES, '').replace(SPACING, ' ').replace(INVISIBLE, '').replace(CONTROLS, '')++ return hasSecret(line) || hasSecret(joined) || hasInvite(joined) ? SECRET_LINE : joined+}++export type Depth = 'none' | '256' | 'truecolor'++type Node = { type: string; props: Record<string, unknown> }+type Style = { color?: unknown; backgroundColor?: unknown; bold?: unknown; dimColor?: unknown; italic?: unknown; inverse?: unknown }++/** Theme names the views use (hooks/views/common.ts PLAIN), as the 256-colour numbers Claude Code's own theme is closest to. */+const NAMED: Record<string, number> = { claude: 173, success: 71, error: 167, warning: 214, suggestion: 147 }+const BASIC: Record<string, number> = { black: 0, red: 1, green: 2, yellow: 3, blue: 4, magenta: 5, cyan: 6, white: 7, gray: 8, grey: 8 }++const hex = (value: string): [number, number, number] | null => (/^#[0-9a-fA-F]{6}$/.test(value) ? [parseInt(value.slice(1, 3), 16), parseInt(value.slice(3, 5), 16), parseInt(value.slice(5, 7), 16)] : null)++function cube(r: number, g: number, b: number): number {+ const level = (n: number) => (n < 48 ? 0 : n < 115 ? 1 : Math.min(5, Math.floor((n - 35) / 40)))++ return 16 + 36 * level(r) + 6 * level(g) + level(b)+}++function colorCode(value: unknown, ground: 38 | 48, depth: Depth): string | null {+ if (depth === 'none' || typeof value !== 'string') return null++ const rgb = hex(value)++ if (rgb !== null) return depth === 'truecolor' ? `${ground};2;${rgb[0]};${rgb[1]};${rgb[2]}` : `${ground};5;${cube(...rgb)}`++ const named = NAMED[value] ?? (BASIC[value] === undefined ? undefined : BASIC[value])++ return named === undefined ? null : `${ground};5;${named}`+}++function sgr(style: Style, depth: Depth): string {+ if (depth === 'none') return ''++ const codes = [style.bold === true ? '1' : '', style.dimColor === true ? '2' : '', style.italic === true ? '3' : '', style.inverse === true ? '7' : '', colorCode(style.color, 38, depth) ?? '', colorCode(style.backgroundColor, 48, depth) ?? ''].filter(code => code !== '')++ return codes.length === 0 ? '' : `\u001b[${codes.join(';')}m`+}++const RESET = '\u001b[0m'+/** Visible length of a line: SGR sequences cost nothing (only ours are ever in it), every code point is one cell. */+export const widthOf = (line: string): number => [...line.replace(/\u001b\[[0-9;]*m/g, '')].length++/** Cuts a styled line to `width` cells, keeping the sequences, and closes any style left open. */+function cut(line: string, width: number, mark = ''): string {+ if (widthOf(line) <= width) return line++ let out = ''+ let seen = 0+ const keep = Math.max(0, width - [...mark].length)++ for (const part of line.split(/(\u001b\[[0-9;]*m)/)) {+ if (part.startsWith('\u001b[')) out += part+ else+ for (const ch of part) {+ if (seen >= keep) break+ out += ch+ seen+++ }+ }++ return `${out}${mark}${out.includes('\u001b') ? RESET : ''}`+}++function wordWrap(text: string, width: number): string[] {+ const lines: string[] = []+ let current = ''++ for (const word of text.split(' ')) {+ let rest = word++ while ([...rest].length > width) {+ if (current !== '') lines.push(current), (current = '')+ lines.push([...rest].slice(0, width).join(''))+ rest = [...rest].slice(width).join('')+ }++ if (current !== '' && [...current].length + [...rest].length + 1 > width) {+ lines.push(current)+ current = rest+ } else current = current === '' ? rest : `${current} ${rest}`+ }++ return lines.length === 0 && current === '' ? [''] : [...lines, current]+}++const flat = (children: unknown): unknown[] => (Array.isArray(children) ? children.flatMap(flat) : children === null || children === undefined || typeof children === 'boolean' ? [] : [children])++/** The text of a Text element's children (strings and numbers; a nested Text contributes its own). */+function textOf(children: unknown): string {+ return flat(children)+ .map(child => (typeof child === 'object' ? textOf((child as Node).props?.children) : clean(child)))+ .join('')+}++function pad(line: string, width: number): string {+ return line + ' '.repeat(Math.max(0, width - widthOf(line)))+}++const BORDER = {+ round: ['╭', '╮', '╰', '╯', '─', '│'],+ single: ['┌', '┐', '└', '┘', '─', '│'],+} as const++/** One element as lines no wider than `width`. */+export function render(node: unknown, width: number, depth: Depth): string[] {+ if (node === null || node === undefined || typeof node === 'boolean') return []+ if (typeof node === 'string' || typeof node === 'number') return [cut(clean(node), width)]+ if (Array.isArray(node)) return node.flatMap(child => render(child, width, depth))++ const { type, props } = node as Node++ if (props.hidden === true || props.display === 'none') return []++ if (type === 'Text') {+ const text = textOf(props.children)+ const open = sgr(props as Style, depth)+ const lines = props.wrap === 'truncate-end' ? [cut(text, width, '…')] : wordWrap(text, Math.max(1, width))++ return lines.map(line => (open === '' ? line : `${open}${line}${RESET}`))+ }++ if (type === 'Button') {+ const label = clean(props.label)++ return [cut(`${sgr({ dimColor: true }, depth)}[${props.hotkey === undefined ? '' : `${clean(props.hotkey)} `}${label}]${depth === 'none' ? '' : RESET}`, width)]+ }++ if (type !== 'Box') return []++ const frame = props.borderStyle === 'round' || props.borderStyle === 'single' ? BORDER[props.borderStyle] : null+ const padX = typeof props.paddingX === 'number' && props.paddingX > 0 ? Math.min(4, Math.floor(props.paddingX)) : 0+ const inner = Math.max(1, width - (frame === null ? 0 : 2) - padX * 2)+ const children = flat(props.children)+ let body: string[]++ if (props.flexDirection === 'row') {+ const gap = typeof props.gap === 'number' ? Math.min(4, Math.max(0, Math.floor(props.gap))) : 0+ const parts = children.map(child => render(child, inner, depth))+ // Every part but the last keeps its own width; the last takes what is left, so a value never wraps under its label.+ const widths = parts.map(lines => lines.reduce((most, line) => Math.max(most, widthOf(line)), 0))+ const used = widths.slice(0, -1).reduce((sum, w) => sum + w + gap, 0)+ const redo = children.map((child, i) => (i === children.length - 1 ? render(child, Math.max(1, inner - used), depth) : (parts[i] as string[])))+ const height = redo.reduce((most, lines) => Math.max(most, lines.length), 0)++ body = Array.from({ length: height }, (_, y) => redo.map((lines, i) => (i === redo.length - 1 ? (lines[y] ?? '') : pad(lines[y] ?? '', widths[i] as number))).join(' '.repeat(gap)))+ body = body.map(line => cut(line, inner))+ } else {+ body = children.flatMap(child => render(child, inner, depth))+ }++ if (padX > 0) body = body.map(line => ' '.repeat(padX) + line)+ if (frame === null) return body++ const edge = sgr({ color: props.borderColor }, depth)+ const close = edge === '' ? '' : RESET+ const across = inner + padX * 2++ return [`${edge}${frame[0]}${frame[4].repeat(across)}${frame[1]}${close}`, ...body.map(line => `${edge}${frame[5]}${close}${pad(line, across)}${edge}${frame[5]}${close}`), `${edge}${frame[2]}${frame[4].repeat(across)}${frame[3]}${close}`]+}++/** The kit the views build with: plain element records for `render`. No Raster and no Input, so a picture takes its words and a text field its command fallback. */+export function terminalKit(): Kit {+ const make = (type: string) => (props: Record<string, unknown>) => ({ type, props }) as never++ return { Box: make('Box'), Text: make('Text'), Button: make('Button') }+}diff --git a/plugins/ruflo-console/tui/main.ts b/plugins/ruflo-console/tui/main.tsnew file mode 100644index 0000000000..df4c29f922--- /dev/null+++ b/plugins/ruflo-console/tui/main.ts@@ -0,0 +1,4 @@+/** The bundle entry (ADR-489): what `ruflo tui` loads. Built to dist/tui.mjs by scripts/build-tui.mjs. */+export { runTui, isTuiView, keyOf, depthOf } from './run'+export type { TuiIO, TuiOptions } from './run'+export { TUI_VIEWS } from './session'diff --git a/plugins/ruflo-console/tui/node-host.ts b/plugins/ruflo-console/tui/node-host.tsnew file mode 100644index 0000000000..f338ae90c9--- /dev/null+++ b/plugins/ruflo-console/tui/node-host.ts@@ -0,0 +1,182 @@+/// <reference types="node" />+/**+ * The standalone adapter (ADR-489): a `Host` (hooks/host.ts) backed by Node, for `ruflo tui`. The views and the controller+ * are the ones the Claude Code mod runs; only this file and the terminal renderer differ.+ *+ * Read-only by construction. Reads stay inside the project, `~/.claude` and `~/.claude-flow` (symlinks resolved first); the only+ * program that runs is the ruflo CLI itself, by argv with no shell; every member that needs the Claude Code engine (panes, prompt+ * box, tool calls, network, a spawned process, a dialog) is refused, which the Host contract already allows: a refusal is a+ * missing fact, never a crash. A write phase must port the confirm gate (#3983) before it lifts any of these.+ */+import { execFile } from 'node:child_process'+import { readdir, readFile, realpath, stat } from 'node:fs/promises'+import { homedir } from 'node:os'+import { dirname, isAbsolute, join, resolve, sep } from 'node:path'+import type { ProcessRunResult, Timer } from 'claude-code'++import type { Host } from '../hooks/host'++export type NodeHostOptions = {+ cwd: string+ /** Defaults to the user's home directory. */+ home?: string+ /** `CLAUDE_CONFIG_DIR`, when set. */+ configDir?: string+ /** The running ruflo CLI's entry file: probes run `node <entry> ...`, never a fresh `npx` download. Absent: every run is refused. */+ cliEntry?: string+ /** Where the console's own files are (its catalog); informational in this host. */+ pluginRoot?: string+}++const MAX_OUT = 1_000_000+/** Variables a child may see: enough to run node and find the project, none of the API keys in the parent's environment. */+const CHILD_ENV = /^(PATH|HOME|USERPROFILE|SystemRoot|TMPDIR|TEMP|TMP|LANG|LC_[A-Z]+|TERM|NO_COLOR|CLAUDE_FLOW_[A-Z_]+|RUFLO_[A-Z_]+)$/++const refuse = (what: string): Promise<never> => Promise.reject(new Error(`${what}: not available in the standalone terminal`))++/** The fixed argv prefixes the console builds for the ruflo CLI (state.ts CLI_PREFIXES); the rest of the argv is the command. */+const CLI_HEADS: readonly (readonly string[])[] = [+ ['npx', '--offline', '-y', '@claude-flow/cli@latest'],+ ['npx', '-y', '@claude-flow/cli@latest'],+ ['ruflo'],+ ['claude-flow'],+]++/** `[node, cli.js, ...command]` for an argv that starts with a ruflo CLI prefix; null for anything else. */+export function cliArgv(argv: readonly string[], entry: string | undefined): string[] | null {+ if (entry === undefined) return null++ const head = CLI_HEADS.find(prefix => prefix.every((part, i) => argv[i] === part))++ return head === undefined ? null : [process.execPath, entry, ...argv.slice(head.length)]+}++export function createNodeHost(options: NodeHostOptions): Host {+ const cwd = resolve(options.cwd)+ const home = options.home ?? homedir()+ const roots = [cwd, resolve(options.configDir ?? join(home, '.claude')), resolve(join(home, '.claude-flow'))]+ const store = new Map<string, unknown>()+ const timers = new Set<NodeJS.Timeout>()++ const rooted = (path: string): string => (isAbsolute(path) ? resolve(path) : resolve(cwd, path))+ const within = (path: string, root: string): boolean => path === root || path.startsWith(root + sep)++ /** The path as the disk really has it (links followed, the nearest existing parent for a file not there), and only if it is inside a root. */+ async function allowed(path: string): Promise<string> {+ const wanted = rooted(path)++ if (!roots.some(root => within(wanted, root))) throw new Error('outside the project')++ let real = wanted+ const tail: string[] = []++ for (;;) {+ try {+ real = join(await realpath(real), ...tail.reverse())+ break+ } catch {+ const up = dirname(real)++ if (up === real) throw new Error('outside the project')+ tail.push(real.slice(up.length + 1))+ real = up+ }+ }++ const realRoots = await Promise.all(roots.map(root => realpath(root).catch(() => root)))++ if (!realRoots.some(root => within(real, root))) throw new Error('outside the project')++ return wanted+ }++ const timer = (handle: NodeJS.Timeout): Timer => {+ handle.unref()+ timers.add(handle)++ return { cancel: () => void (clearTimeout(handle), clearInterval(handle), timers.delete(handle)) }+ }++ const env = (): NodeJS.ProcessEnv => Object.fromEntries(Object.entries(process.env).filter(([key]) => CHILD_ENV.test(key)))++ return {+ fs: {+ read: async path => {+ const target = await allowed(path)++ return readFile(target, 'utf8')+ },+ stat: async path => {+ try {+ const target = await allowed(path)+ const link = await import('node:fs/promises').then(fs => fs.lstat(target))+ const info = await stat(target)++ return { mtimeMs: info.mtimeMs, size: info.size, kind: info.isDirectory() ? 'directory' : info.isFile() ? 'file' : 'other', isLink: link.isSymbolicLink() }+ } catch {+ return undefined+ }+ },+ list: async path => {+ const target = await allowed(path)+ const entries = await readdir(target, { withFileTypes: true })++ return Promise.all(+ entries.map(async entry => {+ const info = await stat(join(target, entry.name)).catch(() => undefined)++ return { name: entry.name, kind: entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : 'other', ...(info !== undefined && { size: info.size, mtimeMs: info.mtimeMs }) }+ }),+ )+ },+ },+ every: (ms, fn) => timer(setInterval(fn, ms)),+ after: (ms, fn) => timer(setTimeout(fn, ms)),+ // Kept for this run only: nothing is written to disk by the standalone host.+ storeGet: async key => store.get(key),+ storeSet: async (key, value) => void store.set(key, value),+ fetchText: () => refuse('network'),+ askChoice: () => refuse('a dialog'),+ toast: () => undefined,+ invalidate: () => undefined,+ scrollTop: () => undefined,+ focus: () => refuse('focus'),+ blit: () => undefined,+ openPane: () => refuse('panes'),+ closePane: () => refuse('panes'),+ panes: () => refuse('panes'),+ registerCommand: () => refuse('slash commands'),+ run: (argv, timeoutMs, stdin) => {+ const command = cliArgv(argv, options.cliEntry)++ if (command === null) return refuse('running a program other than the ruflo CLI')++ return new Promise<ProcessRunResult>(done => {+ const child = execFile(command[0] as string, command.slice(1), { cwd, env: env(), timeout: timeoutMs, maxBuffer: MAX_OUT, windowsHide: true }, (error, stdout, stderr) => {+ const code = (error as { code?: unknown } | null)?.code++ done({ exitCode: error === null ? 0 : typeof code === 'number' ? code : 1, stdout: String(stdout).slice(0, MAX_OUT), stderr: String(stderr).slice(0, MAX_OUT), isStdoutTruncated: String(stdout).length > MAX_OUT, isStderrTruncated: String(stderr).length > MAX_OUT })+ })++ child.stdin?.on('error', () => undefined)+ child.stdin?.end(stdin ?? '')+ })+ },+ spawn: () => {+ throw new Error('spawning a process: not available in the standalone terminal')+ },+ usage: async () => ({}),+ rufloTools: async () => ({ tools: 0, servers: [] }),+ settings: () => refuse('Claude Code settings'),+ home: async () => home,+ configDir: async () => options.configDir,+ pluginRoot: options.pluginRoot ?? '',+ rufloSnapshot: () => refuse('ruflo-mods'),+ rufloRoute: () => refuse('ruflo-mods'),+ rufloSegment: () => refuse('ruflo-mods'),+ submitPrompt: () => refuse('a prompt box'),+ fillPrompt: async () => false,+ listCommands: async () => [],+ runSlash: () => refuse('slash commands'),+ }+}diff --git a/plugins/ruflo-console/tui/run.ts b/plugins/ruflo-console/tui/run.tsnew file mode 100644index 0000000000..48021cdfbf--- /dev/null+++ b/plugins/ruflo-console/tui/run.ts@@ -0,0 +1,176 @@+/**+ * `ruflo tui` (ADR-489): the terminal loop. Everything it draws comes from the console's own views through `session.ts`; this file+ * owns only the screen (alternate buffer, raw keys, a footer, scrolling) and the headless path. Input and output are injected so+ * a test drives it without a terminal.+ */+import type { Depth } from './ansi'+import { openSession, TUI_VIEWS, type Session, type TuiView } from './session'++export type TuiInput = {+ isTTY?: boolean+ setRawMode?: (on: boolean) => unknown+ on: (event: 'data', fn: (chunk: Buffer | string) => void) => unknown+ off: (event: 'data', fn: (chunk: Buffer | string) => void) => unknown+ resume: () => unknown+ pause: () => unknown+}+export type TuiOutput = {+ isTTY?: boolean+ columns?: number+ rows?: number+ write: (text: string) => unknown+ on?: (event: 'resize', fn: () => void) => unknown+ off?: (event: 'resize', fn: () => void) => unknown+}+export type TuiIO = { stdin: TuiInput; stdout: TuiOutput; stderr: { write: (text: string) => unknown }; env: Record<string, string | undefined>; signal?: AbortSignal }+export type TuiOptions = { cwd: string; view?: TuiView; cliEntry?: string; configDir?: string; home?: string; pluginRoot?: string; refreshMs?: number }++export const isTuiView = (value: unknown): value is TuiView => typeof value === 'string' && (TUI_VIEWS as readonly string[]).includes(value)++/** Colour depth from the environment: NO_COLOR and a dumb terminal get none, COLORTERM truecolor/24bit gets 24-bit, the rest 256. */+export function depthOf(env: Record<string, string | undefined>): Depth {+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== '') return 'none'+ if (env.TERM === 'dumb' || env.TERM === undefined || env.TERM === '') return 'none'++ return env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit' ? 'truecolor' : '256'+}++const KEYS = 'o overview · c cost · r refresh · j/k scroll · q quit'+const ESC = '\u001b'++/** One keypress as an action, from the bytes a terminal sends. Anything else is ignored. */+export type Key = 'quit' | 'overview' | 'cost' | 'next' | 'refresh' | 'down' | 'up' | 'pagedown' | 'pageup' | 'top' | 'bottom' | null++export function keyOf(chunk: string): Key {+ switch (chunk) {+ case 'q':+ case '\u0003':+ case '\u0004':+ return 'quit'+ case 'o':+ return 'overview'+ case 'c':+ return 'cost'+ case '\t':+ return 'next'+ case 'r':+ return 'refresh'+ case 'j':+ case `${ESC}[B`:+ return 'down'+ case 'k':+ case `${ESC}[A`:+ return 'up'+ case ' ':+ case `${ESC}[6~`:+ return 'pagedown'+ case 'b':+ case `${ESC}[5~`:+ return 'pageup'+ case 'g':+ case `${ESC}[H`:+ return 'top'+ case 'G':+ case `${ESC}[F`:+ return 'bottom'+ default:+ return null+ }+}++function paint(session: Session, io: TuiIO, depth: Depth, scroll: number): number {+ const columns = Math.max(40, Math.min(200, io.stdout.columns ?? 100))+ const rows = Math.max(5, io.stdout.rows ?? 30)+ const room = rows - 1+ let lines: string[]++ try {+ lines = session.frame(columns, depth)+ } catch {+ lines = ['The page could not be drawn. Press r to read again, q to quit.']+ }++ const top = Math.max(0, Math.min(scroll, Math.max(0, lines.length - room)))+ const footer = `${depth === 'none' ? '' : `${ESC}[7m`} ${session.state.view} · ${top + 1}-${Math.min(lines.length, top + room)}/${lines.length} · ${KEYS} · read-only ${depth === 'none' ? '' : `${ESC}[0m`}`++ io.stdout.write(`${ESC}[H${lines.slice(top, top + room).map(line => `${line}${ESC}[K`).join('\r\n')}${ESC}[J\r\n${footer.slice(0, columns + 12)}`)++ return top+}++/** Headless: one frame as plain text on stdout (the same views, read-only), a note on stderr. Returns the exit code. */+async function once(session: Session, io: TuiIO, view: TuiView): Promise<number> {+ session.show(view)+ await session.refresh()+ io.stdout.write(`${session.frame(Math.max(40, Math.min(200, io.stdout.columns ?? 100)), 'none').join('\n')}\n`)+ io.stderr.write('ruflo tui: not an interactive terminal, so one plain frame was printed. Run it in a terminal for the live view.\n')++ return 0+}++export async function runTui(options: TuiOptions, io: TuiIO): Promise<number> {+ const session = openSession({ cwd: options.cwd, ...(options.cliEntry !== undefined && { cliEntry: options.cliEntry }), ...(options.configDir !== undefined && { configDir: options.configDir }), ...(options.home !== undefined && { home: options.home }), ...(options.pluginRoot !== undefined && { pluginRoot: options.pluginRoot }) })+ let view: TuiView = options.view ?? 'overview'++ try {+ if (io.stdin.isTTY !== true || io.stdout.isTTY !== true || io.stdin.setRawMode === undefined) return await once(session, io, view)++ const depth = depthOf(io.env)+ let scroll = 0+ let isDone = false+ let finish: () => void = () => undefined+ const done = new Promise<void>(resolve => void (finish = resolve))+ const draw = () => void (scroll = paint(session, io, depth, scroll))+ const reread = async () => {+ await session.refresh()+ if (!isDone) draw()+ }+ const onKey = (chunk: Buffer | string) => {+ const key = keyOf(chunk.toString())+ const page = Math.max(1, (io.stdout.rows ?? 30) - 2)++ if (key === 'quit') return finish()+ if (key === 'overview' || key === 'cost') (view = key), (scroll = 0), session.show(view)+ else if (key === 'next') (view = TUI_VIEWS[(TUI_VIEWS.indexOf(view) + 1) % TUI_VIEWS.length] as TuiView), (scroll = 0), session.show(view)+ else if (key === 'down') scroll += 1+ else if (key === 'up') scroll = Math.max(0, scroll - 1)+ else if (key === 'pagedown') scroll += page+ else if (key === 'pageup') scroll = Math.max(0, scroll - page)+ else if (key === 'top') scroll = 0+ else if (key === 'bottom') scroll = Number.MAX_SAFE_INTEGER+ else if (key === 'refresh') void reread()+ else return++ draw()+ }++ session.show(view)+ io.stdout.write(`${ESC}[?1049h${ESC}[?25l`)+ io.stdin.setRawMode(true)+ io.stdin.resume()+ io.stdin.on('data', onKey)+ io.stdout.on?.('resize', draw)+ io.signal?.addEventListener('abort', finish, { once: true })+ draw()++ const timer = setInterval(() => void reread(), Math.max(3000, options.refreshMs ?? 3000))++ void reread()++ try {+ await done+ } finally {+ isDone = true+ clearInterval(timer)+ io.stdin.off('data', onKey)+ io.stdout.off?.('resize', draw)+ io.stdin.setRawMode(false)+ io.stdin.pause()+ io.stdout.write(`${ESC}[?25h${ESC}[?1049l`)+ }++ return 0+ } finally {+ session.stop()+ }+}diff --git a/plugins/ruflo-console/tui/session.ts b/plugins/ruflo-console/tui/session.tsnew file mode 100644index 0000000000..c31d7193e6--- /dev/null+++ b/plugins/ruflo-console/tui/session.ts@@ -0,0 +1,68 @@+/**+ * One standalone console session (ADR-489): the mod's own state and controller over the Node host, drawn by the mod's own+ * `paneView` into terminal lines. This is the "same code path": nothing below `paneView` is forked; only the Host and the Kit differ.+ */+import { createController, type Controller } from '../hooks/controller'+import type { Host } from '../hooks/host'+import { newState, type State, type ViewId } from '../hooks/state'+import { paneView } from '../hooks/views/pane'+import { render, terminalKit, type Depth } from './ansi'+import { createNodeHost, type NodeHostOptions } from './node-host'++/** The pages the standalone shell opens in this phase: the rest need the Claude Code host's panes, prompt or dialogs. */+export const TUI_VIEWS = ['overview', 'cost'] as const satisfies readonly ViewId[]+export type TuiView = (typeof TUI_VIEWS)[number]++export type Session = {+ state: State+ controller: Controller+ host: Host+ /** Reads the disk again and runs the page's read-only probes, then returns. Never throws. */+ refresh: () => Promise<void>+ show: (view: TuiView) => void+ /** The page as terminal lines, `columns` wide. */+ frame: (columns: number, depth: Depth) => string[]+ stop: () => void+}++export function openSession(options: NodeHostOptions, host: Host = createNodeHost(options)): Session {+ const state = newState({ look: 'plain', fps: 0, boot: false, panel: 'off', eventsPersist: false } as never)++ state.cwd = options.cwd+ state.isInteractive = true+ // The controller draws and probes only for a pane that is open and shown; here the whole terminal is that pane.+ state.pane.isOpen = true+ state.pane.isShown = true+ state.pane.isFocused = true+ state.pane.bootAtMs = 0++ const controller = createController(state, host)++ const ready = Promise.all([host.home().then(home => void (state.home = home ?? null), () => undefined), host.configDir().then(dir => void (state.configDir = dir ?? null), () => undefined)])++ return {+ state,+ controller,+ host,+ refresh: async () => {+ try {+ await ready+ await controller.refresh()+ await controller.probe(false)+ } catch {+ // A read that fails is a page that says n/a, never a crashed terminal.+ }+ },+ show: view => {+ state.view = view+ state.back = view+ },+ frame: (columns, depth) => {+ state.pane.columns = columns+ const tree = paneView({ kit: terminalKit(), state, nowMs: Date.now(), columns, pictures: new Map(), act: controller.actions })++ return render(tree, columns, depth)+ },+ stop: () => controller.stop(),+ }+}diff --git a/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts b/v3/@claude-flow/cli/__tests__/guidance-brain.test.tsindex 05ec0f119b..77aa913590 100644--- a/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts+++ b/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts@@ -50,7 +50,7 @@ describe('Ruflo capability brain', () => {expect(auth.riskFlags).toEqual(expect.arrayContaining(['network', 'credential-pii', 'approval']),);- expect(brain.cliCommands).toHaveLength(52);+ expect(brain.cliCommands).toHaveLength(53);});it('does not confuse registration with runtime health or authorization', () => {diff --git a/v3/@claude-flow/cli/__tests__/tui-command.test.ts b/v3/@claude-flow/cli/__tests__/tui-command.test.tsnew file mode 100644index 0000000000..24178f970c--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/tui-command.test.ts@@ -0,0 +1,81 @@+/**+ * `ruflo tui` (ADR-489): the command loads its bundle from this CLI's own install only, degrades to a message when there is none,+ * and refuses an unknown page. The headless run against a real bundle is skipped when the bundle has not been built.+ */+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, describe, expect, it } from 'vitest';++import { locateTuiBundle, tuiCommand } from '../src/commands/tui.js';++/** The command names capability-brain.ts lists, read from the source so the test fails if `tui` is dropped. */+const COMMANDS_FOR_BRAIN = [...readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'mcp-tools', 'capability-brain.ts'), 'utf8').matchAll(/'([a-z][a-z-]*)'/g)].map(match => match[1]);++const made: string[] = [];+const tmp = () => {+ const dir = mkdtempSync(join(tmpdir(), 'tui-cmd-'));+ made.push(dir);+ return dir;+};+afterEach(() => {+ for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe('locateTuiBundle', () => {+ it('finds plugins/ruflo-console/dist/tui.mjs inside the package install', () => {+ const pkg = tmp();+ mkdirSync(join(pkg, 'plugins', 'ruflo-console', 'dist'), { recursive: true });+ mkdirSync(join(pkg, 'dist', 'src', 'commands'), { recursive: true });+ writeFileSync(join(pkg, 'plugins', 'ruflo-console', 'dist', 'tui.mjs'), 'export {}');++ expect(locateTuiBundle(join(pkg, 'dist', 'src', 'commands'))).toBe(join(pkg, 'plugins', 'ruflo-console', 'dist', 'tui.mjs'));+ });++ it('never looks above node_modules: a repository that ships its own bundle is not run', () => {+ const project = tmp();+ const here = join(project, 'node_modules', '@claude-flow', 'cli', 'dist', 'src', 'commands');+ mkdirSync(here, { recursive: true });+ mkdirSync(join(project, 'plugins', 'ruflo-console', 'dist'), { recursive: true });+ writeFileSync(join(project, 'plugins', 'ruflo-console', 'dist', 'tui.mjs'), 'throw new Error("hostile")');++ expect(locateTuiBundle(here)).toBeNull();+ });+});++describe('tui command', () => {+ it('is registered by name and listed for the capability brain', () => {+ expect(tuiCommand.name).toBe('tui');+ expect(COMMANDS_FOR_BRAIN).toContain('tui');+ });++ it('refuses an unknown page with exit 2 and runs nothing', async () => {+ const result = await tuiCommand.action!({ args: [], flags: { view: 'swarm; rm -rf /' }, cwd: tmp() } as never);++ expect(result).toMatchObject({ success: false, exitCode: 2 });+ });++ it('degrades to a message and exit 1 when the bundle is not in this install', async () => {+ // From a build output with no plugin beside it; skipped where the repo checkout has built one.+ if (locateTuiBundle() !== null) return;+ const result = await tuiCommand.action!({ args: [], flags: {}, cwd: tmp() } as never);++ expect(result).toMatchObject({ success: false, exitCode: 1 });+ });++ it.skipIf(locateTuiBundle() === null)('prints one plain frame headless and exits 0 (real bundle)', async () => {+ const lines: string[] = [];+ const real = process.stdout.write.bind(process.stdout);+ process.stdout.write = ((chunk: string | Uint8Array) => (lines.push(String(chunk)), true)) as typeof process.stdout.write;+ try {+ const result = await tuiCommand.action!({ args: [], flags: { view: 'overview' }, cwd: tmp() } as never);++ expect(result).toMatchObject({ success: true, exitCode: 0 });+ } finally {+ process.stdout.write = real;+ }+ expect(lines.join('')).toContain('what ruflo is doing here');+ expect(existsSync(locateTuiBundle()!)).toBe(true);+ });+});diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.tsindex 439b5ca835..aa375c3a07 100644--- a/v3/@claude-flow/cli/src/commands/index.ts+++ b/v3/@claude-flow/cli/src/commands/index.ts@@ -99,6 +99,8 @@ const commandLoaders: Record<string, CommandLoader> = {spinner: () => import('./spinner.js'),// ruflo as a Claude Code mod: function hooks, early access (ADR-404)mods: () => import('./mods.js'),+ // ADR-489: the console in a terminal of its own (read-only Overview and Cost); loads a bundle from this CLI's own install.+ tui: () => import('./tui.js'),// ADR-406 command catalog and mission control (interim homes until mods.ts follow-up)catalog: () => import('./catalog.js'),mission: () => import('./mission.js'),diff --git a/v3/@claude-flow/cli/src/commands/tui.ts b/v3/@claude-flow/cli/src/commands/tui.tsnew file mode 100644index 0000000000..318e95a399--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/tui.ts@@ -0,0 +1,92 @@+/**+ * `ruflo tui` — the ruflo console in a terminal of its own (ADR-489).+ *+ * Runs the same views the Claude Code mod (plugins/ruflo-console) draws, over a Node host instead of the mod host. Read-only in+ * this phase: Overview and Cost. The bundle is built from the plugin's source (scripts/build-tui.mjs) and loaded from this+ * CLI's OWN install only (never from the working directory: opening a repository must not run code that repository supplies).+ * No bundle, or no terminal, is a message and a clean exit, never a crash; ruflo stays operational without it.+ *+ * npx ruflo tui # interactive, in a terminal+ * npx ruflo tui --view cost # start on the Cost page+ * npx ruflo tui | cat # not a terminal: one plain frame, then exit+ */+import { existsSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++import type { Command, CommandContext, CommandResult } from '../types.js';+import { output } from '../output.js';+import { ownPluginDirs } from '../plugins/own-install.js';++const __dirname = dirname(fileURLToPath(import.meta.url));++const VIEWS = ['overview', 'cost'] as const;++type TuiModule = { runTui: (options: Record<string, unknown>, io: Record<string, unknown>) => Promise<number>; isTuiView: (value: unknown) => boolean };++/** `<own install>/plugins/ruflo-console/dist/tui.mjs`, the first that exists. */+export function locateTuiBundle(startDir: string = __dirname): string | null {+ for (const dir of ownPluginDirs(startDir, 'ruflo-console', 'dist')) {+ const file = join(dir, 'tui.mjs');+ if (existsSync(file)) return file;+ }+ return null;+}++/** The running CLI's entry file, so the console's read-only probes run this CLI and never download another. */+function cliEntry(): string | undefined {+ const entry = join(__dirname, '..', '..', '..', 'bin', 'cli.js');+ return existsSync(entry) ? entry : undefined;+}++export const tuiCommand: Command = {+ name: 'tui',+ description: 'The ruflo console in your terminal (Overview and Cost, read-only). Same views as the Claude Code mod.',+ options: [{ name: 'view', description: `Page to open: ${VIEWS.join(' | ')}`, type: 'string' as const, default: 'overview' }],+ examples: [+ { command: 'npx ruflo tui', description: 'Open the console in this terminal' },+ { command: 'npx ruflo tui --view cost', description: 'Start on the Cost page' },+ ],+ async action(context: CommandContext): Promise<CommandResult> {+ const ctx = context as { args?: string[]; flags?: Record<string, unknown>; cwd?: string };+ const wanted = (ctx.flags?.view as string | undefined) ?? ctx.args?.find(arg => !arg.startsWith('-')) ?? 'overview';++ if (!(VIEWS as readonly string[]).includes(wanted)) {+ output.writeln(output.error(`tui: unknown view "${String(wanted).slice(0, 40)}". Use one of: ${VIEWS.join(', ')}`));+ return { success: false, exitCode: 2, data: { error: 'unknown-view' } };+ }++ const bundle = locateTuiBundle();+ if (bundle === null) {+ output.writeln(output.warning('tui: the terminal console is not available in this install (plugins/ruflo-console/dist/tui.mjs not found).'));+ output.writeln('From a ruflo checkout: node plugins/ruflo-console/scripts/build-tui.mjs');+ return { success: false, exitCode: 1, data: { error: 'bundle-missing' } };+ }++ let mod: TuiModule;+ try {+ mod = (await import(pathToFileURL(bundle).href)) as TuiModule;+ } catch (error) {+ output.writeln(output.error(`tui: could not load the console bundle: ${error instanceof Error ? error.message.slice(0, 160) : 'unknown error'}`));+ return { success: false, exitCode: 1, data: { error: 'bundle-load-failed' } };+ }++ const stop = new AbortController();+ const onSignal = () => stop.abort();+ process.once('SIGTERM', onSignal);+ process.once('SIGHUP', onSignal);++ try {+ const code = await mod.runTui(+ { cwd: ctx.cwd ?? process.cwd(), view: wanted, ...(cliEntry() !== undefined && { cliEntry: cliEntry() }), ...(process.env.CLAUDE_CONFIG_DIR !== undefined && { configDir: process.env.CLAUDE_CONFIG_DIR }) },+ { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, env: process.env, signal: stop.signal },+ );+ return { success: code === 0, exitCode: code };+ } finally {+ process.off('SIGTERM', onSignal);+ process.off('SIGHUP', onSignal);+ }+ },+};++export default tuiCommand;diff --git a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.tsindex 5b158e42d2..7ceb215ec4 100644--- a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts@@ -124,7 +124,7 @@ export const RUFLO_CLI_COMMANDS = ['ruvector', 'benchmark', 'guidance', 'appliance', 'appliance-advanced','transfer-store', 'cleanup', 'autopilot', 'gaia-bench', 'metaharness','eject', 'funnel', 'settings', 'auth', 'proxy', 'advisor', 'spinner',- 'announcements',+ 'announcements', 'tui',] as const;export interface ImplementationLoopStep {diff --git a/v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md b/v3/docs/adr/ADR-489-ruflo-tui-standalone-console.mdnew file mode 100644index 0000000000..d438dea071--- /dev/null+++ b/v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md@@ -0,0 +1,180 @@+# ADR 489: `ruflo tui`: the console in a terminal of its own, over the same views++Status: Proposed (phase 1, a read-only Overview and Cost, is implemented in the draft PR that adds this file; phases 2 to 4 are a roadmap)++Date: 2026-10-11++Builds on: ADR-407 (the cockpit), ADR-446 (plugin mods), ADR-448 (the Room), ADR-481 (one sanitiser for drawn text), ADR-486 (session workspace), ADR-150 (plugin skills dispatched by the CLI, with graceful degradation), ADR-437 (multi-provider cost ledger). Security inputs: #3983 (every confirm route bound to the card the person saw), #3981 (no transcript text or path in a model-facing answer).++Numbering: 488 is the highest on `main` and no open pull request names 489 (checked 2026-10-11 before committing). ADR-487 exists twice, so check again at merge.++## 1. Context++rUv's goal: a TUI for ruflo, part of `npx ruflo`, that reuses the ruflo-console components and works both on its own and as the mod inside Claude Code+(ruflo-mods). A standalone host should eventually drive Codex and OpenRouter. The agreed starting point was a **thin shell first**: a `ruflo tui` entry+that embeds the existing views, Codex and OpenRouter through their own CLI or API, Claude Code staying a supported host, and not a new agent harness.++This ADR records what the code showed, the decision, and the first slice. Every number below was measured on `main` at 72255a2f4 unless it says otherwise.++## 2. Findings (evidence)++### 2.1 The host boundary already exists++`plugins/ruflo-console/hooks/host.ts` defines `Host`, "the engine as `session.start` bound it": 31 required members and 3 optional ones (`fs`, `run`, `spawn`,+`every`, `after`, `storeGet/Set`, `openPane`, `blit`, `toolCall`, `rufloSnapshot`, `httpSend` …). Its contract says any member may be refused and a refusal is+a missing fact, never a crash. `register.ts` `hostOf($, …)` is the one place that spells `$.noun.method(...)`: the Claude Code adapter. The controller+(`createController(state, host)`), every view (`(ctx) => RenderElement`, built only from `ctx.kit.Box|Text|Button`, optional `Raster|Input`) and the page+(`paneView`) are plain functions over that interface.++Static check over all 343 `.ts` files under `hooks/` (comments stripped; the rules are asserted by `tests/tui-boundary.spec.ts`):++| class | meaning | files | where |+|---|---|---|---|+| host-neutral | no engine call, no Node module, no package; reads files through `Host.fs`, runs the ruflo CLI through `Host.run` | **315** | top level 97, `data/` 103, `views/` 98, `gfx/` 17 |+| host-engine-dependent | calls a `Host` member only the Claude Code host can answer (panes, `blit`, prompt box, `toolCall`, `rufloSnapshot`, dialogs, toasts) | **26** | top level 23, `views/` 3 (`wf-control`, `wf-guide`, `wf-templates`) |+| Claude-Code-only | touches `$` or `on(...)` directly | **2** | `register.ts`, `model-tools.ts` (the model-facing `console_*` tools) |++95 files import `claude-code`, all as types; no file imports a Node module or a package. The "about 113 files" in the question is the+top level of `hooks/` (122 `.ts` files: 97 host-neutral, 23 engine-dependent, 2 engine-only); the whole folder has 343. "Host-neutral" is a statement about imports, not about usefulness: many neutral views+draw `n/a` on a host that cannot measure what they read (see 2.4).++### 2.2 What it renders to: no terminal library, no escapes++The console uses no TUI library and writes no terminal escape sequence. Views build an element tree; the Claude Code engine lays it out and draws it. `Raster`+(`gfx/raster.ts`, `[codePoint, fg, bg]` triplets as base64) is Claude Code's own element, a picture the engine paints. A search for Kitty found nothing in the+console. The premise "renders to Kitty / 256-colour" is therefore not in the code; the 256-colour note in the project memory is about Claude Code inside tmux.+A standalone host needs its own renderer for `Box|Text|Button`; `Raster` can take its existing words fallback (`picture()` in `views/common.ts`) until a later phase.++### 2.3 How `npx ruflo` dispatches, and where `tui` fits++`ruflo/bin/ruflo.js` is a thin wrapper that loads `@claude-flow/cli`. The CLI maps a command name to a lazy `import('./<name>.js')` in+`src/commands/index.ts`, and lists names in `src/mcp-tools/capability-brain.ts` (pinned by `guidance-brain.test.ts`: 52 became 53). `commands/metaharness.ts`+is the precedent for a command that runs plugin code: it finds `plugins/ruflo-metaharness` in the CLI's **own** install (`plugins/own-install.ts`+`ownPluginDirs`, which stops at `node_modules` so a repository cannot supply code that ruflo then runs), degrades gracefully when it is absent, and+`scripts/prepare-publish.mjs` copies the plugin into the tarball. `tui` follows exactly that shape.++### 2.4 What a standalone host can and cannot know++| Source | Claude Code host | Standalone host |+|---|---|---|+| ruflo files (`.claude-flow/*`, `.swarm/*`, helpers manifest) | `$.fs` | Node `fs`, confined (see 4) |+| ruflo CLI JSON probes | `$.process.run` | `execFile` of **this** CLI, no shell |+| session cost, context % (`usage()`) | engine | **n/a** (no Claude session) |+| `ruflo-mods` budget and routing (`rufloSnapshot`) | `$.ruflo` | **n/a** (mods not seated) |+| panes, focus, blit, prompt box, slash commands, tool calls | engine | refused |++So in phase 1 the Cost page shows `n/a` for Claude Code spend, context and the budget ladder, and shows what is on disk: the provider ledger when+`ruflo-cost-tracker` data exists, and the router's counts. That is true, not a defect; but it means Cost is thin until phase 2 reads Codex and OpenRouter spend.+The shared chrome also still draws Claude-only affordances (Ask Claude, the Claude-control card, "ruflo-mods · asks first" rows). They are drawn inert and dimmed+in this phase; hiding them needs a host capability flag (phase 2, see 6).++### 2.5 Node floor and what ships++Node `>=20` (root, `ruflo`, `@claude-flow/cli` all declare it). The console is TypeScript with extensionless, bundler-style imports and constructor+parameter properties (`gfx/raster.ts`), so it cannot be compiled by the CLI's `tsc` (NodeNext) and Node's native type stripping (22.18+) refuses it: the+standalone host needs a **bundle**. `esbuild` bundles `tui/main.ts` and everything it reaches into one ESM file: **1247 KiB minified, 437 KiB gzipped**+(1.9 MB unminified), no dependency left to install. `esbuild` is present in the repo's `node_modules` only through another tool; it is not a declared devDependency (decision A below).++## 3. Decision++### 3.1 The `Host` interface is the adapter boundary. Do not invent a second one.++Name the existing `hooks/host.ts` contract as the boundary and enforce it with a test (`tests/tui-boundary.spec.ts`): `hooks/` has no value import of the+engine declarations, no Node module and no package; only `register.ts` and `model-tools.ts` reach `$`; `tui/` imports neither. There are then two adapters:++| | Claude Code mods adapter (exists) | Standalone terminal adapter (this PR) |+|---|---|---|+| Host | `hostOf($, …)` in `register.ts` | `tui/node-host.ts` `createNodeHost` |+| Kit (draws `Box|Text|Button`) | the engine's element table, `$.ui.resolve` | `tui/ansi.ts` `terminalKit` + `render` |+| Loop | engine render, input and timers | `tui/run.ts` (alternate screen, raw keys, a timer) |+| Page | `paneView(ctx)` | **the same `paneView(ctx)`** (`tui/session.ts`) |++The rule for adding a view: it renders against `Ctx` and uses only `ctx.kit`; if it needs a member only one host has, it reads it through an optional `Host`+member and shows `n/a` where it is absent. No view forks per host.++### 3.2 Placement: one source of truth, a sibling folder, a build-time bundle++- Source stays in `plugins/ruflo-console/`. The standalone adapter lives beside it in `plugins/ruflo-console/tui/` (not in `hooks/`, which must stay Node-free).+ Nothing is copied or forked; `tui/` imports `../hooks/*` by relative path.+- `plugins/ruflo-console/scripts/build-tui.mjs` bundles `tui/main.ts` to `plugins/ruflo-console/dist/tui.mjs` (gitignored).+- `@claude-flow/cli` gains `src/commands/tui.ts`: it finds `plugins/ruflo-console/dist/tui.mjs` in its own install (`ownPluginDirs`, never the working directory),+ imports it, and calls `runTui`. No bundle is a message and exit 1; no terminal is one plain frame and exit 0. Ruflo works without it.+- Publishing: `scripts/prepare-publish.mjs` must run the build and copy `plugins/ruflo-console/dist` into `plugins/ruflo-console/` of the CLI tarball, as it+ does for `ruflo-metaharness`. **This PR does not change the publish path** (it cannot be exercised without a release); until it does, `npx ruflo tui` reports the+ bundle as missing on a registry install and works from a checkout after `node plugins/ruflo-console/scripts/build-tui.mjs`. See decision B.+- This is not a new npm package and not one of the four bundled leaves: no `@claude-flow/*` version, pin or standalone publish changes. The CLI's "bundled+ versus standalone leaves" rule is untouched; the cost is the +437 KiB gzip tarball weight in phase 1b.++Rejected: a new `@claude-flow/tui` package (a fifth artifact to version, publish and pin, for code that has one consumer); moving views into `cli/src` (a fork of+343 files and a circular dependency, since the plugin would then import the CLI); compiling the console with the CLI's `tsc` (its imports are not NodeNext);+requiring `tsx` or Node 22 at runtime (a dependency or a floor bump).++### 3.3 Renderer++A 200-line renderer (`tui/ansi.ts`): `Box` row and column, rounded and single borders, `paddingX`, `gap`, `Text` colour (theme names, `#rrggbb` as truecolor or the nearest+256-cube), bold, dim, italic, inverse, word wrap and `truncate-end`, `Button` as an inert `[label]`. No `Raster`, no `Input` (the views already have fallbacks for both).+**No dependency.** Ink, blessed or similar would bring a React or a native layer into a CLI that has neither; if a later phase needs real input fields it may+add one as an **optional, lazily imported** dependency, per the published-train rule, and say so here first.++### 3.4 Security constraints on the new host (each is enforced and tested)++| Constraint | How it holds on the standalone host |+|---|---|+| Confirm gate bound to the card the person saw (#3983) | Phase 1 has **no write path**: buttons are inert, no key maps to an action, `askChoice` rejects, and `run` only accepts the ruflo CLI. The controller's `confirm(seen)` binding is unchanged and unexercised. A write phase must port the #3983 tests to this host before it lifts any refusal. |+| One sanitiser for drawn text (ADR-481, `modelLine`) | `modelLine` guards what a **model** reads and lives in `model-tools.ts` (engine-only), so it is not imported. The terminal needs the same guarantee for what a **person's terminal** executes: `ansi.ts` `clean` is the chokepoint (OSC/CSI/C1/invisible removed, a line holding a secret or invite withheld whole, using the same `ESCAPES`, `INVISIBLE`, `hasSecret`, `hasInvite`). The mod gets this from the engine; here it is ours. `tui-render.spec.ts` feeds OSC title injection, `\u001b[2J`, `\u001b[?1049h`, a GitHub token and an Anthropic key through every colour depth. |+| Path and transcript leaks (#3981) | Reads are confined to the project, `~/.claude` (or `CLAUDE_CONFIG_DIR`) and `~/.claude-flow`, symlinks resolved before the check (tests: `../`, a link out of the project, `~/.ssh`). The page is drawn for a person (`ctx.text` false), so session previews follow ADR-486; the model-facing path (`viewText`, `console_state`) is untouched. **Not a model channel:** non-TTY output is one plain frame; if someone pipes it to a model that is their choice, and it still passes `clean`. |+| No credentials in output or child processes | `run` starts only `process.execPath <this cli.js> …` (no shell, fixed argv) with an environment allowlist (`PATH`, `HOME`, `LANG`, `TERM`, `CLAUDE_FLOW_*`, `RUFLO_*` …): `OPENROUTER_API_KEY` and friends do not reach the child (test). `fetchText`, `httpSend`, `spawn` are refused. Nothing is written to disk (the store is in memory). |+| A repository cannot supply code that ruflo runs | The bundle is loaded from the CLI's own install only (`ownPluginDirs`); a `plugins/ruflo-console/dist/tui.mjs` inside the opened project is ignored (test). |++### 3.5 Codex and OpenRouter++The console already has an AI terminal (`harness.ts`) that asks `codex`, `claude` or both through `Host.spawn`, and OpenRouter and other OpenAI-compatible+endpoints through `Host.httpSend` with the key named by `keyEnv` (`OPENROUTER_API_KEY`; `convoTargets`, `data/wf-targets.ts`), plus the multi-provider cost ledger (ADR-437). The+standalone host reuses all of it by **implementing `spawn` and `httpSend`**, not by writing a harness: `spawn` for an allowlist of binaries (`codex`, `claude`) in a+read-only sandbox mode by default, `httpSend` for the configured hosts only with the key read from the environment at call time and never stored, logged or drawn.+Both stay refused in phase 1.++### 3.6 Claude Code remains a first-class host++`/ruflo` in Claude Code is unchanged: `register.ts` and the 342 other files were not touched by this PR. `ruflo tui` is an additional front end over the same state,+not a replacement and not a second implementation.++## 4. Phases++1. **Phase 1 (this PR, draft): the vertical slice.** `ruflo tui [--view overview|cost]`; alternate screen, keys `o c Tab r j k PgUp PgDn g G q`, auto-refresh every 3 s; headless prints one plain frame; read-only; the boundary and security tests; ADR.+1b. **Publish wiring.** `prepare-publish.mjs` builds and stages the bundle; a CI job runs `ruflo tui` headless from the packed tarball; decide on `esbuild` as a declared devDependency.+2. **Host capabilities and more pages.** `Host.capabilities` so chrome and rows that need Claude Code are hidden, not drawn inert; Swarm, Room, Events, Missions read-only; Raster to half-block cells; Windows and tmux verification; `NO_COLOR` and width (CJK, emoji) handling.+3. **Drive Codex and OpenRouter** (3.5) behind the confirm gate, with #3983's tests ported; the AI terminal page; per-provider spend read from the CLIs' own reports and the ledger.+4. **Actions.** Pressable buttons and fields (an optional lazily loaded input dependency, or hand-rolled), the confirm card, the palette; each write goes through `Runner` as in the mod.++## 5. Risks++- **Chrome that lies.** Inert Claude-only controls are visible until phase 2. They are dimmed and the footer says read-only; still a rough edge.+- **Drift.** A new view may import something engine-specific. Mitigation: `tui-boundary.spec.ts` (imports) and a headless smoke over the pages the TUI opens.+- **Bundle size.** 437 KiB gzip for a feature many will not use. It loads lazily, only for `tui`. Dropping the unused pages from the bundle (tree-shaking by an explicit page list) is a phase 2 option.+- **A second place to sanitise.** The engine's escape handling is not inherited. `clean` is one function with a test; any new drawing path must go through `render`.+- **Terminal variance.** Raw mode, alternate screen and SGR 256/truecolor are standard xterm behaviour; other terminals, tmux colour depth and Windows are unverified (section 7).+- **Probe cost.** Overview and Cost run the ruflo CLI as a child (version, memory stats, model stats). That is a Node start per probe each cadence; they inherit the controller's cadence and `MAX_PARALLEL_PROBES`.++## 6. Out of scope++An agent tool loop or any new harness; new model providers beyond what `convoTargets` already offers; editing files or settings from the TUI; mouse support;+a web or desktop front end; publishing, version bumps, and the Slack or dashboard connectors. The console's version and changelog are not touched by phase 1.++## 7. Verification++Run on this machine (Linux 6.17, Node 22.23.2, a pty from `script`): 36 new vitest tests in `plugins/ruflo-console/tests/tui-{host,render,session,boundary}.spec.ts` and 6 in `v3/@claude-flow/cli/__tests__/tui-command.test.ts`,+all passing; `tsc -p plugins/ruflo-console` reports no error in `tui/` or the new tests (7 errors exist in other files already on `main`); `node …/cli.js tui` against this repository printed the+real CLI version (`v3.56.5`), the real swarm id, daemon state and helpers manifest; the pty run entered the alternate screen once, switched to Cost on `c`, scrolled on `j`, quit on `q`, left raw mode and the+alternate screen, exit 0.++**Unverified:** Node 20 (the declared floor; the bundle targets it but only 22 was run), macOS Terminal, iTerm2, kitty, Windows Terminal and conhost (raw mode and SGR), tmux/screen colour depth, a terminal narrower than 40 columns, wide+characters, `npx ruflo tui` from a registry install (the bundle is not staged by `prepare-publish.mjs` yet), and every page other than Overview and Cost.++## 8. Decisions for the owner++- **A.** Declare `esbuild` as a root devDependency (build-time only, changes `package-lock.json`)? Today it resolves only because another tool pulls it in.+- **B.** Wire the bundle into `prepare-publish.mjs` now (adds ~437 KiB gzip to the CLI tarball and a build step to the release) or hold until phase 2 makes the page set worth it?+- **C.** Which pages are in the standalone shell after Overview and Cost: Swarm, Room, Events, Missions? Each is read-only first.+- **D.** For Codex and OpenRouter: is read-only sandboxing by default the right default, and may `httpSend` reach only `openrouter.ai` plus hosts named in `convoTargets`?+- **E.** Exit code when `tui` is not in a terminal: it prints one frame and exits 0 so pipes and CI do not fail; say if a non-zero exit is preferred.diff --git a/v3/docs/adr/INDEX-mod-system.md b/v3/docs/adr/INDEX-mod-system.mdindex 4bf07a7863..6c16752805 100644--- a/v3/docs/adr/INDEX-mod-system.md+++ b/v3/docs/adr/INDEX-mod-system.md@@ -87,3 +87,4 @@ Other ADRs outside 404-451 that the mod ADRs lean on: 150 (removable integration- **ADRs with no stated parent:** 434, 436, 437, 438, 439, 440, 441 carry no `Builds on` or `Extends` line.- **2026-10-07 additions.** Rows for 477, 478 and 479 were added. 478's link is to a file added by the change that builds that page. 479 is not a mod ADR; it is listed because 476 (hive-mind gating) and the toasts sit on the same MCP and console surfaces. ADRs 454 to 476 are not in these tables.| 487 | Optional ruvnet-brain grounding (detect-only) in the console and mods | Accepted | 10-09 | 404, 443, 444, 481 | — | this PR | console 0.42.0, mods 0.5.0 | `grounding.spec`, `grounding.test.ts` |+| 489 | `ruflo tui`: the console in a terminal of its own, over the same `Host` boundary (standalone adapter, read-only Overview and Cost) | Proposed (phase 1 in draft PR) | 10-11 | 407, 446, 448, 481, 486; related 150 | — | draft PR | not shipped | `tui-boundary.spec`, `tui-host.spec`, `tui-render.spec`, `tui-session.spec`, `tui-command.test.ts` |